From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- files/pt-br/web/api/abortsignal/aborted/index.html | 62 + files/pt-br/web/api/abortsignal/index.html | 101 ++ files/pt-br/web/api/abstractworker/index.html | 103 ++ .../web/api/abstractworker/onerror/index.html | 104 ++ .../pt-br/web/api/ambient_light_events/index.html | 116 ++ .../web/api/angle_instanced_arrays/index.html | 88 ++ files/pt-br/web/api/animation/cancel/index.html | 120 ++ .../pt-br/web/api/animation/currenttime/index.html | 112 ++ files/pt-br/web/api/animation/index.html | 171 +++ files/pt-br/web/api/animation/playstate/index.html | 152 +++ .../api/animationevent/animationevent/index.html | 134 ++ .../api/animationevent/animationname/index.html | 102 ++ .../web/api/animationevent/elapsedtime/index.html | 103 ++ files/pt-br/web/api/animationevent/index.html | 194 +++ .../animationevent/initanimationevent/index.html | 134 ++ .../api/animationevent/pseudoelement/index.html | 102 ++ files/pt-br/web/api/api_de_desempenho/index.html | 138 +++ .../web/api/api_push/best_practices/index.html | 73 ++ files/pt-br/web/api/api_push/index.html | 172 +++ files/pt-br/web/api/api_web_audio/index.html | 480 ++++++++ .../api_web_audio/sintetizador_simples/index.html | 579 +++++++++ files/pt-br/web/api/attr/index.html | 132 ++ files/pt-br/web/api/attr/localname/index.html | 133 ++ .../web/api/audiocontext/currenttime/index.html | 114 ++ files/pt-br/web/api/audiocontext/index.html | 258 ++++ files/pt-br/web/api/audionode/index.html | 191 +++ .../pt-br/web/api/background_tasks_api/index.html | 509 ++++++++ .../web/api/batterymanager/charging/index.html | 33 + .../web/api/batterymanager/chargingtime/index.html | 34 + .../api/batterymanager/dischargingtime/index.html | 34 + files/pt-br/web/api/batterymanager/index.html | 140 +++ .../pt-br/web/api/batterymanager/level/index.html | 34 + .../api/batterymanager/onchargingchange/index.html | 35 + .../batterymanager/onchargingtimechange/index.html | 35 + .../ondischargintimechange/index.html | 35 + .../api/batterymanager/onlevelchange/index.html | 35 + files/pt-br/web/api/biquadfilternode/index.html | 186 +++ files/pt-br/web/api/blob/blob/index.html | 65 + files/pt-br/web/api/blob/index.html | 130 ++ files/pt-br/web/api/blob/size/index.html | 60 + files/pt-br/web/api/blob/slice/index.html | 115 ++ files/pt-br/web/api/blob/type/index.html | 68 ++ files/pt-br/web/api/body/index.html | 97 ++ files/pt-br/web/api/body/json/index.html | 89 ++ files/pt-br/web/api/broadcastchannel/index.html | 81 ++ files/pt-br/web/api/cache/index.html | 282 +++++ .../web/api/cameracontrol/autofocus/index.html | 61 + files/pt-br/web/api/cameracontrol/index.html | 108 ++ .../api/canvasrenderingcontext2d/arc/index.html | 138 +++ .../api/canvasrenderingcontext2d/arcto/index.html | 147 +++ .../canvasrenderingcontext2d/beginpath/index.html | 184 +++ .../canvasrenderingcontext2d/clearrect/index.html | 195 +++ .../api/canvasrenderingcontext2d/clip/index.html | 195 +++ .../canvasrenderingcontext2d/closepath/index.html | 170 +++ .../api/canvasrenderingcontext2d/fill/index.html | 196 +++ .../canvasrenderingcontext2d/fillrect/index.html | 179 +++ .../canvasrenderingcontext2d/fillstyle/index.html | 213 ++++ .../web/api/canvasrenderingcontext2d/index.html | 450 +++++++ .../api/canvasrenderingcontext2d/lineto/index.html | 176 +++ .../api/canvasrenderingcontext2d/moveto/index.html | 176 +++ .../quadraticcurveto/index.html | 182 +++ .../api/canvasrenderingcontext2d/rect/index.html | 177 +++ .../api/canvasrenderingcontext2d/stroke/index.html | 187 +++ .../canvasrenderingcontext2d/strokerect/index.html | 177 +++ files/pt-br/web/api/characterdata/index.html | 94 ++ files/pt-br/web/api/childnode/after/index.html | 187 +++ files/pt-br/web/api/childnode/index.html | 78 ++ files/pt-br/web/api/childnode/remove/index.html | 100 ++ files/pt-br/web/api/clipboardevent/index.html | 59 + .../pt-br/web/api/closeevent/closeevent/index.html | 71 ++ files/pt-br/web/api/closeevent/index.html | 239 ++++ files/pt-br/web/api/console/assert/index.html | 148 +++ files/pt-br/web/api/console/clear/index.html | 38 + files/pt-br/web/api/console/count/index.html | 168 +++ files/pt-br/web/api/console/dir/index.html | 108 ++ files/pt-br/web/api/console/error/index.html | 160 +++ files/pt-br/web/api/console/index.html | 242 ++++ files/pt-br/web/api/console/info/index.html | 154 +++ files/pt-br/web/api/console/log/index.html | 119 ++ files/pt-br/web/api/console/table/index.html | 143 +++ files/pt-br/web/api/console/time/index.html | 103 ++ files/pt-br/web/api/console/timeend/index.html | 90 ++ files/pt-br/web/api/console/timestamp/index.html | 106 ++ files/pt-br/web/api/console/warn/index.html | 139 +++ files/pt-br/web/api/console_api/index.html | 68 ++ files/pt-br/web/api/crypto/index.html | 72 ++ files/pt-br/web/api/crypto/subtle/index.html | 51 + files/pt-br/web/api/cryptokey/algorithm/index.html | 112 ++ .../pt-br/web/api/cryptokey/extractable/index.html | 110 ++ files/pt-br/web/api/cryptokey/index.html | 120 ++ files/pt-br/web/api/cryptokey/type/index.html | 117 ++ files/pt-br/web/api/cryptokey/usages/index.html | 123 ++ files/pt-br/web/api/css/index.html | 136 +++ files/pt-br/web/api/css_object_model/index.html | 133 ++ .../pt-br/web/api/customelementregistry/index.html | 93 ++ files/pt-br/web/api/datatransfer/index.html | 383 ++++++ files/pt-br/web/api/deviceacceleration/index.html | 42 + files/pt-br/web/api/devicerotationrate/index.html | 92 ++ files/pt-br/web/api/devicestorage.get/index.html | 58 + .../web/api/devicestorage.onchange/index.html | 30 + .../web/api/document/activeelement/index.html | 164 +++ files/pt-br/web/api/document/alinkcolor/index.html | 36 + files/pt-br/web/api/document/anchors/index.html | 107 ++ files/pt-br/web/api/document/bgcolor/index.html | 35 + files/pt-br/web/api/document/body/index.html | 44 + .../pt-br/web/api/document/characterset/index.html | 65 + files/pt-br/web/api/document/close/index.html | 27 + files/pt-br/web/api/document/compatmode/index.html | 42 + .../pt-br/web/api/document/contenttype/index.html | 46 + .../web/api/document/createelement/index.html | 82 ++ .../web/api/document/createelementns/index.html | 90 ++ .../web/api/document/currentscript/index.html | 99 ++ .../pt-br/web/api/document/defaultview/index.html | 28 + files/pt-br/web/api/document/designmode/index.html | 104 ++ files/pt-br/web/api/document/doctype/index.html | 59 + files/pt-br/web/api/document/document/index.html | 87 ++ .../web/api/document/documentelement/index.html | 43 + .../pt-br/web/api/document/documenturi/index.html | 53 + .../web/api/document/elementfrompoint/index.html | 132 ++ .../web/api/document/elementoregistrado/index.html | 132 ++ .../pt-br/web/api/document/execcommand/index.html | 174 +++ files/pt-br/web/api/document/fullscreen/index.html | 83 ++ .../web/api/document/getelementbyid/index.html | 133 ++ .../api/document/getelementsbyclassname/index.html | 104 ++ .../web/api/document/getelementsbyname/index.html | 90 ++ .../api/document/getelementsbytagname/index.html | 113 ++ .../pt-br/web/api/document/getselection/index.html | 8 + files/pt-br/web/api/document/hasfocus/index.html | 146 +++ files/pt-br/web/api/document/head/index.html | 102 ++ files/pt-br/web/api/document/height/index.html | 44 + files/pt-br/web/api/document/images/index.html | 38 + .../web/api/document/implementation/index.html | 52 + files/pt-br/web/api/document/importnode/index.html | 84 ++ files/pt-br/web/api/document/index.html | 402 ++++++ .../web/api/document/keydown_event/index.html | 178 +++ .../web/api/document/keypress_event/index.html | 170 +++ .../pt-br/web/api/document/keyup_event/index.html | 151 +++ files/pt-br/web/api/document/location/index.html | 108 ++ files/pt-br/web/api/document/origin/index.html | 60 + .../web/api/document/queryselector/index.html | 107 ++ .../web/api/document/queryselectorall/index.html | 110 ++ files/pt-br/web/api/document/readystate/index.html | 102 ++ files/pt-br/web/api/document/referrer/index.html | 33 + files/pt-br/web/api/document/scripts/index.html | 84 ++ files/pt-br/web/api/document/url/index.html | 19 + files/pt-br/web/api/document/write/index.html | 108 ++ files/pt-br/web/api/document/writeln/index.html | 43 + files/pt-br/web/api/documentfragment/index.html | 234 ++++ files/pt-br/web/api/domexception/index.html | 150 +++ .../domimplementation/createdocument/index.html | 83 ++ files/pt-br/web/api/domimplementation/index.html | 81 ++ files/pt-br/web/api/domstring/index.html | 52 + files/pt-br/web/api/domstringlist/index.html | 43 + files/pt-br/web/api/domstringmap/index.html | 141 +++ files/pt-br/web/api/element/accesskey/index.html | 18 + .../web/api/element/addeventlistener/index.html | 322 +++++ files/pt-br/web/api/element/animate/index.html | 202 +++ files/pt-br/web/api/element/attributes/index.html | 166 +++ files/pt-br/web/api/element/classlist/index.html | 171 +++ files/pt-br/web/api/element/classname/index.html | 123 ++ files/pt-br/web/api/element/click_event/index.html | 276 +++++ files/pt-br/web/api/element/closest/index.html | 127 ++ .../pt-br/web/api/element/getattribute/index.html | 76 ++ .../api/element/getboundingclientrect/index.html | 84 ++ .../api/element/getelementsbyclassname/index.html | 108 ++ files/pt-br/web/api/element/id/index.html | 119 ++ files/pt-br/web/api/element/index.html | 529 ++++++++ files/pt-br/web/api/element/innerhtml/index.html | 148 +++ .../web/api/element/insertadjacenthtml/index.html | 138 +++ files/pt-br/web/api/element/matches/index.html | 165 +++ .../web/api/element/mousedown_event/index.html | 235 ++++ .../web/api/element/mouseenter_event/index.html | 314 +++++ .../web/api/element/mouseover_event/index.html | 262 ++++ files/pt-br/web/api/element/name/index.html | 79 ++ files/pt-br/web/api/element/outerhtml/index.html | 144 +++ .../pt-br/web/api/element/queryselector/index.html | 94 ++ .../web/api/element/queryselectorall/index.html | 118 ++ .../web/api/element/removeattribute/index.html | 36 + .../web/api/element/scrollintoview/index.html | 89 ++ files/pt-br/web/api/element/scrollleft/index.html | 83 ++ files/pt-br/web/api/element/scrolltop/index.html | 69 ++ files/pt-br/web/api/element/scrollwidth/index.html | 116 ++ .../pt-br/web/api/element/setattribute/index.html | 58 + .../web/api/element/setattributens/index.html | 33 + files/pt-br/web/api/element/tagname/index.html | 119 ++ .../web/api/element/touchstart_event/index.html | 174 +++ files/pt-br/web/api/encoding_api/index.html | 55 + .../comparativo_entre_event_targets/index.html | 167 +++ files/pt-br/web/api/event/currenttarget/index.html | 129 ++ .../web/api/event/defaultprevented/index.html | 79 ++ files/pt-br/web/api/event/event/index.html | 69 ++ files/pt-br/web/api/event/index.html | 146 +++ files/pt-br/web/api/event/initevent/index.html | 137 +++ files/pt-br/web/api/event/istrusted/index.html | 57 + .../pt-br/web/api/event/preventdefault/index.html | 113 ++ files/pt-br/web/api/event/srcelement/index.html | 74 ++ .../api/event/stopimmediatepropagation/index.html | 99 ++ .../pt-br/web/api/event/stoppropagation/index.html | 93 ++ files/pt-br/web/api/event/target/index.html | 69 ++ files/pt-br/web/api/event/type/index.html | 60 + files/pt-br/web/api/eventlistener/index.html | 48 + .../web/api/eventsource/eventsource/index.html | 157 +++ files/pt-br/web/api/eventsource/index.html | 175 +++ files/pt-br/web/api/eventsource/onerror/index.html | 121 ++ .../web/api/eventtarget/dispatchevent/index.html | 43 + .../web/api/eventtarget/eventtarget/index.html | 70 ++ files/pt-br/web/api/eventtarget/index.html | 124 ++ .../api/eventtarget/removeeventlistener/index.html | 138 +++ .../web/api/fetch_api/basic_concepts/index.html | 66 + files/pt-br/web/api/fetch_api/index.html | 85 ++ .../pt-br/web/api/fetch_api/using_fetch/index.html | 311 +++++ .../fetch_api/uso_de_busca_cross-global/index.html | 35 + files/pt-br/web/api/file/index.html | 146 +++ .../using_files_from_web_applications/index.html | 351 ++++++ files/pt-br/web/api/filelist/index.html | 134 ++ .../pt-br/web/api/filereader/filereader/index.html | 54 + files/pt-br/web/api/filereader/index.html | 162 +++ files/pt-br/web/api/filereader/onload/index.html | 29 + .../api/filereader/readasarraybuffer/index.html | 107 ++ .../api/filereader/readasbinarystring/index.html | 120 ++ .../web/api/filereader/readasdataurl/index.html | 111 ++ .../pt-br/web/api/filereader/readastext/index.html | 104 ++ files/pt-br/web/api/formdata/append/index.html | 177 +++ files/pt-br/web/api/formdata/delete/index.html | 138 +++ files/pt-br/web/api/formdata/entries/index.html | 77 ++ files/pt-br/web/api/formdata/formdata/index.html | 184 +++ files/pt-br/web/api/formdata/get/index.html | 142 +++ files/pt-br/web/api/formdata/getall/index.html | 74 ++ files/pt-br/web/api/formdata/has/index.html | 81 ++ files/pt-br/web/api/formdata/index.html | 170 +++ files/pt-br/web/api/formdata/set/index.html | 150 +++ files/pt-br/web/api/fullscreenoptions/index.html | 29 + files/pt-br/web/api/gamepad_api/index.html | 90 ++ .../web/api/geolocation/clearwatch/index.html | 84 ++ .../api/geolocation/getcurrentposition/index.html | 127 ++ files/pt-br/web/api/geolocation/index.html | 75 ++ .../web/api/geolocation/watchposition/index.html | 140 +++ .../api/geolocationcoordinates/altitude/index.html | 45 + .../web/api/geolocationcoordinates/index.html | 141 +++ .../web/api/geolocationposition/coords/index.html | 116 ++ files/pt-br/web/api/geolocationposition/index.html | 61 + .../web/api/geolocationpositionerror/index.html | 128 ++ files/pt-br/web/api/globaleventhandlers/index.html | 536 ++++++++ .../web/api/globaleventhandlers/onabort/index.html | 44 + .../web/api/globaleventhandlers/onblur/index.html | 94 ++ .../api/globaleventhandlers/onchange/index.html | 46 + .../web/api/globaleventhandlers/onclick/index.html | 83 ++ .../globaleventhandlers/oncontextmenu/index.html | 48 + .../web/api/globaleventhandlers/onerror/index.html | 97 ++ .../web/api/globaleventhandlers/onfocus/index.html | 36 + .../web/api/globaleventhandlers/onkeyup/index.html | 61 + .../web/api/globaleventhandlers/onload/index.html | 74 ++ .../onlostpointercapture/index.html | 70 ++ .../api/globaleventhandlers/onscroll/index.html | 94 ++ files/pt-br/web/api/history/index.html | 89 ++ files/pt-br/web/api/history_api/exemplo/index.html | 418 +++++++ files/pt-br/web/api/history_api/index.html | 257 ++++ .../api/htmlcanvaselement/getcontext/index.html | 292 +++++ .../web/api/htmlcanvaselement/height/index.html | 79 ++ files/pt-br/web/api/htmlcanvaselement/index.html | 264 ++++ .../web/api/htmlcanvaselement/todataurl/index.html | 157 +++ files/pt-br/web/api/htmlcollection/index.html | 68 ++ .../getdistributednodes/index.html | 100 ++ files/pt-br/web/api/htmlcontentelement/index.html | 116 ++ .../web/api/htmlcontentelement/seletor/index.html | 98 ++ files/pt-br/web/api/htmldivelement/index.html | 133 ++ files/pt-br/web/api/htmlelement/blur/index.html | 89 ++ files/pt-br/web/api/htmlelement/click/index.html | 115 ++ .../web/api/htmlelement/contenteditable/index.html | 102 ++ .../web/api/htmlelement/contextmenu/index.html | 44 + files/pt-br/web/api/htmlelement/dataset/index.html | 97 ++ files/pt-br/web/api/htmlelement/focus/index.html | 62 + files/pt-br/web/api/htmlelement/index.html | 410 +++++++ files/pt-br/web/api/htmlelement/lang/index.html | 51 + .../web/api/htmlelement/offsetheight/index.html | 126 ++ .../web/api/htmlelement/offsetleft/index.html | 142 +++ .../web/api/htmlelement/offsetparent/index.html | 40 + .../pt-br/web/api/htmlelement/offsettop/index.html | 62 + .../web/api/htmlelement/offsetwidth/index.html | 65 + files/pt-br/web/api/htmlinputelement/index.html | 643 ++++++++++ .../web/api/htmlinputelement/select/index.html | 52 + .../htmlinputelement/setselectionrange/index.html | 173 +++ files/pt-br/web/api/htmloptionelement/index.html | 129 ++ .../web/api/htmloptionelement/option/index.html | 101 ++ .../api/htmlselectelement/checkvalidity/index.html | 98 ++ files/pt-br/web/api/htmlselectelement/index.html | 290 +++++ files/pt-br/web/api/htmlshadowelement/index.html | 67 + files/pt-br/web/api/htmlspanelement/index.html | 72 ++ files/pt-br/web/api/idbcursor/index.html | 181 +++ files/pt-br/web/api/idbfactory/index.html | 210 ++++ files/pt-br/web/api/imagecapture/index.html | 116 ++ files/pt-br/web/api/index.html | 32 + .../basic_concepts_behind_indexeddb/index.html | 249 ++++ files/pt-br/web/api/indexeddb_api/index.html | 167 +++ .../api/indexeddb_api/usando_indexeddb/index.html | 1281 ++++++++++++++++++++ files/pt-br/web/api/keyboardevent/index.html | 439 +++++++ files/pt-br/web/api/location/assign/index.html | 120 ++ files/pt-br/web/api/location/index.html | 184 +++ files/pt-br/web/api/location/reload/index.html | 114 ++ files/pt-br/web/api/location/search/index.html | 55 + files/pt-br/web/api/mediadevices/index.html | 251 ++++ files/pt-br/web/api/mediastreamtrack/index.html | 181 +++ files/pt-br/web/api/messagechannel/index.html | 152 +++ files/pt-br/web/api/messageport/index.html | 117 ++ .../web/api/messageport/postmessage/index.html | 81 ++ files/pt-br/web/api/mouseevent/clientx/index.html | 149 +++ files/pt-br/web/api/mouseevent/clienty/index.html | 91 ++ files/pt-br/web/api/mouseevent/index.html | 336 +++++ files/pt-br/web/api/mutationobserver/index.html | 221 ++++ .../pt-br/web/api/navigation_timing_api/index.html | 153 +++ files/pt-br/web/api/navigator/battery/index.html | 40 + .../web/api/navigator/cookieenabled/index.html | 49 + .../web/api/navigator/devicememory/index.html | 39 + .../pt-br/web/api/navigator/geolocation/index.html | 46 + .../web/api/navigator/getusermedia/index.html | 184 +++ files/pt-br/web/api/navigator/index.html | 119 ++ files/pt-br/web/api/navigator/share/index.html | 87 ++ files/pt-br/web/api/navigatorid/index.html | 120 ++ .../pt-br/web/api/navigatorid/platform/index.html | 63 + .../pt-br/web/api/navigatorid/useragent/index.html | 89 ++ files/pt-br/web/api/navigatorlanguage/index.html | 148 +++ .../web/api/navigatorlanguage/language/index.html | 131 ++ files/pt-br/web/api/navigatoronline/index.html | 134 ++ .../web/api/navigatoronline/online/index.html | 91 ++ .../online_and_offline_events/index.html | 99 ++ files/pt-br/web/api/navigatorplugins/index.html | 69 ++ .../api/navigatorplugins/javaenabled/index.html | 54 + files/pt-br/web/api/node/appendchild/index.html | 56 + files/pt-br/web/api/node/baseuri/index.html | 82 ++ files/pt-br/web/api/node/childnodes/index.html | 66 + files/pt-br/web/api/node/clonenode/index.html | 175 +++ files/pt-br/web/api/node/contains/index.html | 98 ++ .../index.html" | 55 + files/pt-br/web/api/node/firstchild/index.html | 66 + files/pt-br/web/api/node/index.html | 303 +++++ files/pt-br/web/api/node/innertext/index.html | 86 ++ files/pt-br/web/api/node/insertbefore/index.html | 152 +++ files/pt-br/web/api/node/isconnected/index.html | 118 ++ files/pt-br/web/api/node/lastchild/index.html | 34 + files/pt-br/web/api/node/nextsibling/index.html | 66 + files/pt-br/web/api/node/parentnode/index.html | 116 ++ .../pt-br/web/api/node/previoussibling/index.html | 46 + files/pt-br/web/api/node/removechild/index.html | 72 ++ files/pt-br/web/api/node/replacechild/index.html | 69 ++ files/pt-br/web/api/node/textcontent/index.html | 138 +++ files/pt-br/web/api/nodefilter/index.html | 163 +++ files/pt-br/web/api/nodelist/index.html | 155 +++ files/pt-br/web/api/notificacoes/index.html | 217 ++++ files/pt-br/web/api/notificationaction/index.html | 79 ++ files/pt-br/web/api/offlineaudiocontext/index.html | 150 +++ files/pt-br/web/api/page_visibility_api/index.html | 209 ++++ .../api/parentnode/childelementcount/index.html | 98 ++ files/pt-br/web/api/parentnode/children/index.html | 131 ++ files/pt-br/web/api/parentnode/index.html | 163 +++ .../web/api/parentnode/queryselector/index.html | 101 ++ files/pt-br/web/api/path2d/index.html | 82 ++ files/pt-br/web/api/performance/index.html | 138 +++ files/pt-br/web/api/performance/now/index.html | 160 +++ files/pt-br/web/api/performance/tojson/index.html | 61 + files/pt-br/web/api/positionoptions/index.html | 109 ++ .../pt-br/web/api/processinginstruction/index.html | 39 + files/pt-br/web/api/pushmanager/index.html | 187 +++ .../api/randomsource/getrandomvalues/index.html | 116 ++ files/pt-br/web/api/randomsource/index.html | 108 ++ files/pt-br/web/api/request/index.html | 167 +++ files/pt-br/web/api/request/request/index.html | 155 +++ files/pt-br/web/api/response/index.html | 130 ++ files/pt-br/web/api/rtccertificate/index.html | 47 + files/pt-br/web/api/rtcdatachannel/index.html | 130 ++ files/pt-br/web/api/rtcicetransport/index.html | 91 ++ .../rtcpeerconnection/connectionstate/index.html | 64 + files/pt-br/web/api/rtcpeerconnection/index.html | 360 ++++++ .../web/api/sele\303\247\303\243o/index.html" | 206 ++++ files/pt-br/web/api/sensor/index.html | 89 ++ files/pt-br/web/api/server-sent_events/index.html | 79 ++ .../using_server-sent_events/index.html | 189 +++ files/pt-br/web/api/service_worker_api/index.html | 322 +++++ .../using_service_workers/index.html | 522 ++++++++ .../web/api/serviceworkercontainer/index.html | 175 +++ .../api/serviceworkercontainer/register/index.html | 140 +++ .../serviceworkerglobalscope/clients/index.html | 63 + .../web/api/serviceworkerglobalscope/index.html | 152 +++ files/pt-br/web/api/sharedworker/index.html | 188 +++ files/pt-br/web/api/sharedworker/port/index.html | 111 ++ files/pt-br/web/api/speechgrammar/index.html | 79 ++ files/pt-br/web/api/speechsynthesis/index.html | 194 +++ .../web/api/speechsynthesisutterance/index.html | 177 +++ .../api/speechsynthesisutterance/voice/index.html | 130 ++ files/pt-br/web/api/storage/clear/index.html | 131 ++ files/pt-br/web/api/storage/getitem/index.html | 79 ++ files/pt-br/web/api/storage/index.html | 119 ++ files/pt-br/web/api/storage/key/index.html | 72 ++ files/pt-br/web/api/storage/length/index.html | 130 ++ files/pt-br/web/api/storage/removeitem/index.html | 124 ++ files/pt-br/web/api/storage/setitem/index.html | 131 ++ files/pt-br/web/api/storagemanager/index.html | 53 + .../pt-br/web/api/streams_api/concepts/index.html | 121 ++ files/pt-br/web/api/streams_api/index.html | 157 +++ .../web/api/subtlecrypto/derivekey/index.html | 270 +++++ .../web/api/subtlecrypto/generatekey/index.html | 197 +++ .../web/api/subtlecrypto/importkey/index.html | 169 +++ files/pt-br/web/api/subtlecrypto/index.html | 83 ++ files/pt-br/web/api/svgaelement/index.html | 74 ++ .../api/svgaelement/svgalement.target/index.html | 105 ++ .../web/api/svganimatetransformelement/index.html | 48 + files/pt-br/web/api/url/createobjecturl/index.html | 42 + files/pt-br/web/api/url/index.html | 113 ++ files/pt-br/web/api/url/revokeobjecturl/index.html | 107 ++ files/pt-br/web/api/url/searchparams/index.html | 45 + files/pt-br/web/api/urlsearchparams/get/index.html | 109 ++ files/pt-br/web/api/urlsearchparams/index.html | 177 +++ .../web/api/urlsearchparams/values/index.html | 112 ++ files/pt-br/web/api/validitystate/index.html | 85 ++ files/pt-br/web/api/web_animations_api/index.html | 86 ++ .../usando_a_web_animations_api/index.html | 358 ++++++ files/pt-br/web/api/web_crypto_api/index.html | 132 ++ .../pt-br/web/api/web_storage_api_pt_br/index.html | 139 +++ .../using_the_web_storage_api/index.html | 267 ++++ files/pt-br/web/api/web_workers_api/index.html | 213 ++++ files/pt-br/web/api/webgl_api/index.html | 278 +++++ .../index.html | 226 ++++ .../tutorial/getting_started_with_webgl/index.html | 71 ++ files/pt-br/web/api/webgl_api/tutorial/index.html | 39 + files/pt-br/web/api/webrtc_api/index.html | 197 +++ .../pt-br/web/api/webrtc_api/protocols/index.html | 70 ++ .../simples_rtcdatachannel_amostra/index.html | 272 +++++ files/pt-br/web/api/websocket/index.html | 323 +++++ files/pt-br/web/api/webvr_api/index.html | 151 +++ .../api/webvr_api/using_the_webvr_api/index.html | 440 +++++++ files/pt-br/web/api/window/alert/index.html | 47 + .../web/api/window/applicationcache/index.html | 33 + files/pt-br/web/api/window/closed/index.html | 59 + files/pt-br/web/api/window/confirm/index.html | 49 + files/pt-br/web/api/window/crypto/index.html | 128 ++ files/pt-br/web/api/window/document/index.html | 56 + files/pt-br/web/api/window/event/index.html | 72 ++ files/pt-br/web/api/window/fullscreen/index.html | 44 + files/pt-br/web/api/window/getselection/index.html | 129 ++ files/pt-br/web/api/window/history/index.html | 52 + files/pt-br/web/api/window/index.html | 381 ++++++ files/pt-br/web/api/window/innerheight/index.html | 137 +++ files/pt-br/web/api/window/length/index.html | 52 + files/pt-br/web/api/window/location/index.html | 272 +++++ files/pt-br/web/api/window/matchmedia/index.html | 106 ++ files/pt-br/web/api/window/navigator/index.html | 54 + .../pt-br/web/api/window/ondevicelight/index.html | 99 ++ files/pt-br/web/api/window/onscroll/index.html | 98 ++ files/pt-br/web/api/window/opendialog/index.html | 90 ++ files/pt-br/web/api/window/performance/index.html | 33 + .../pt-br/web/api/window/popstate_event/index.html | 144 +++ files/pt-br/web/api/window/print/index.html | 56 + files/pt-br/web/api/window/prompt/index.html | 66 + .../api/window/requestanimationframe/index.html | 106 ++ .../web/api/window/requestidlecallback/index.html | 70 ++ files/pt-br/web/api/window/resize_event/index.html | 190 +++ files/pt-br/web/api/window/scroll/index.html | 57 + files/pt-br/web/api/window/scrollby/index.html | 53 + .../pt-br/web/api/window/scrollbypages/index.html | 41 + files/pt-br/web/api/window/scrollto/index.html | 56 + files/pt-br/web/api/window/scrolly/index.html | 76 ++ .../pt-br/web/api/window/sessionstorage/index.html | 143 +++ files/pt-br/web/api/window/setcursor/index.html | 28 + files/pt-br/web/api/window/setimmediate/index.html | 107 ++ files/pt-br/web/api/window/url/index.html | 100 ++ .../web/api/window/window.localstorage/index.html | 123 ++ files/pt-br/web/api/windowbase64/atob/index.html | 72 ++ files/pt-br/web/api/windowbase64/index.html | 120 ++ files/pt-br/web/api/windoweventhandlers/index.html | 189 +++ .../windoweventhandlers/onhashchange/index.html | 158 +++ .../api/windoweventhandlers/onpopstate/index.html | 61 + .../api/windoweventhandlers/onstorage/index.html | 101 ++ .../api/windoworworkerglobalscope/fetch/index.html | 305 +++++ .../web/api/windoworworkerglobalscope/index.html | 189 +++ .../setinterval/index.html | 629 ++++++++++ .../web/api/windowtimers/cleartimeout/index.html | 100 ++ files/pt-br/web/api/windowtimers/index.html | 116 ++ files/pt-br/web/api/worker/index.html | 166 +++ files/pt-br/web/api/xmldocument/async/index.html | 37 + files/pt-br/web/api/xmldocument/index.html | 61 + .../pt-br/web/api/xmlhttprequest/abort/index.html | 118 ++ files/pt-br/web/api/xmlhttprequest/index.html | 724 +++++++++++ .../xmlhttprequest/onreadystatechange/index.html | 120 ++ files/pt-br/web/api/xmlhttprequest/open/index.html | 72 ++ .../web/api/xmlhttprequest/readystate/index.html | 154 +++ .../requisicoes_sincronas_e_assincronas/index.html | 234 ++++ files/pt-br/web/api/xmlhttprequest/send/index.html | 129 ++ .../api/xmlhttprequest/setrequestheader/index.html | 77 ++ .../web/api/xmlhttprequest/timeout/index.html | 51 + .../usando_xmlhttprequest/index.html | 688 +++++++++++ 489 files changed, 65272 insertions(+) create mode 100644 files/pt-br/web/api/abortsignal/aborted/index.html create mode 100644 files/pt-br/web/api/abortsignal/index.html create mode 100644 files/pt-br/web/api/abstractworker/index.html create mode 100644 files/pt-br/web/api/abstractworker/onerror/index.html create mode 100644 files/pt-br/web/api/ambient_light_events/index.html create mode 100644 files/pt-br/web/api/angle_instanced_arrays/index.html create mode 100644 files/pt-br/web/api/animation/cancel/index.html create mode 100644 files/pt-br/web/api/animation/currenttime/index.html create mode 100644 files/pt-br/web/api/animation/index.html create mode 100644 files/pt-br/web/api/animation/playstate/index.html create mode 100644 files/pt-br/web/api/animationevent/animationevent/index.html create mode 100644 files/pt-br/web/api/animationevent/animationname/index.html create mode 100644 files/pt-br/web/api/animationevent/elapsedtime/index.html create mode 100644 files/pt-br/web/api/animationevent/index.html create mode 100644 files/pt-br/web/api/animationevent/initanimationevent/index.html create mode 100644 files/pt-br/web/api/animationevent/pseudoelement/index.html create mode 100644 files/pt-br/web/api/api_de_desempenho/index.html create mode 100644 files/pt-br/web/api/api_push/best_practices/index.html create mode 100644 files/pt-br/web/api/api_push/index.html create mode 100644 files/pt-br/web/api/api_web_audio/index.html create mode 100644 files/pt-br/web/api/api_web_audio/sintetizador_simples/index.html create mode 100644 files/pt-br/web/api/attr/index.html create mode 100644 files/pt-br/web/api/attr/localname/index.html create mode 100644 files/pt-br/web/api/audiocontext/currenttime/index.html create mode 100644 files/pt-br/web/api/audiocontext/index.html create mode 100644 files/pt-br/web/api/audionode/index.html create mode 100644 files/pt-br/web/api/background_tasks_api/index.html create mode 100644 files/pt-br/web/api/batterymanager/charging/index.html create mode 100644 files/pt-br/web/api/batterymanager/chargingtime/index.html create mode 100644 files/pt-br/web/api/batterymanager/dischargingtime/index.html create mode 100644 files/pt-br/web/api/batterymanager/index.html create mode 100644 files/pt-br/web/api/batterymanager/level/index.html create mode 100644 files/pt-br/web/api/batterymanager/onchargingchange/index.html create mode 100644 files/pt-br/web/api/batterymanager/onchargingtimechange/index.html create mode 100644 files/pt-br/web/api/batterymanager/ondischargintimechange/index.html create mode 100644 files/pt-br/web/api/batterymanager/onlevelchange/index.html create mode 100644 files/pt-br/web/api/biquadfilternode/index.html create mode 100644 files/pt-br/web/api/blob/blob/index.html create mode 100644 files/pt-br/web/api/blob/index.html create mode 100644 files/pt-br/web/api/blob/size/index.html create mode 100644 files/pt-br/web/api/blob/slice/index.html create mode 100644 files/pt-br/web/api/blob/type/index.html create mode 100644 files/pt-br/web/api/body/index.html create mode 100644 files/pt-br/web/api/body/json/index.html create mode 100644 files/pt-br/web/api/broadcastchannel/index.html create mode 100644 files/pt-br/web/api/cache/index.html create mode 100644 files/pt-br/web/api/cameracontrol/autofocus/index.html create mode 100644 files/pt-br/web/api/cameracontrol/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/arc/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/arcto/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/beginpath/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/clearrect/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/clip/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/closepath/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/fill/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/fillrect/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/fillstyle/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/lineto/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/moveto/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/quadraticcurveto/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/rect/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/stroke/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/strokerect/index.html create mode 100644 files/pt-br/web/api/characterdata/index.html create mode 100644 files/pt-br/web/api/childnode/after/index.html create mode 100644 files/pt-br/web/api/childnode/index.html create mode 100644 files/pt-br/web/api/childnode/remove/index.html create mode 100644 files/pt-br/web/api/clipboardevent/index.html create mode 100644 files/pt-br/web/api/closeevent/closeevent/index.html create mode 100644 files/pt-br/web/api/closeevent/index.html create mode 100644 files/pt-br/web/api/console/assert/index.html create mode 100644 files/pt-br/web/api/console/clear/index.html create mode 100644 files/pt-br/web/api/console/count/index.html create mode 100644 files/pt-br/web/api/console/dir/index.html create mode 100644 files/pt-br/web/api/console/error/index.html create mode 100644 files/pt-br/web/api/console/index.html create mode 100644 files/pt-br/web/api/console/info/index.html create mode 100644 files/pt-br/web/api/console/log/index.html create mode 100644 files/pt-br/web/api/console/table/index.html create mode 100644 files/pt-br/web/api/console/time/index.html create mode 100644 files/pt-br/web/api/console/timeend/index.html create mode 100644 files/pt-br/web/api/console/timestamp/index.html create mode 100644 files/pt-br/web/api/console/warn/index.html create mode 100644 files/pt-br/web/api/console_api/index.html create mode 100644 files/pt-br/web/api/crypto/index.html create mode 100644 files/pt-br/web/api/crypto/subtle/index.html create mode 100644 files/pt-br/web/api/cryptokey/algorithm/index.html create mode 100644 files/pt-br/web/api/cryptokey/extractable/index.html create mode 100644 files/pt-br/web/api/cryptokey/index.html create mode 100644 files/pt-br/web/api/cryptokey/type/index.html create mode 100644 files/pt-br/web/api/cryptokey/usages/index.html create mode 100644 files/pt-br/web/api/css/index.html create mode 100644 files/pt-br/web/api/css_object_model/index.html create mode 100644 files/pt-br/web/api/customelementregistry/index.html create mode 100644 files/pt-br/web/api/datatransfer/index.html create mode 100644 files/pt-br/web/api/deviceacceleration/index.html create mode 100644 files/pt-br/web/api/devicerotationrate/index.html create mode 100644 files/pt-br/web/api/devicestorage.get/index.html create mode 100644 files/pt-br/web/api/devicestorage.onchange/index.html create mode 100644 files/pt-br/web/api/document/activeelement/index.html create mode 100644 files/pt-br/web/api/document/alinkcolor/index.html create mode 100644 files/pt-br/web/api/document/anchors/index.html create mode 100644 files/pt-br/web/api/document/bgcolor/index.html create mode 100644 files/pt-br/web/api/document/body/index.html create mode 100644 files/pt-br/web/api/document/characterset/index.html create mode 100644 files/pt-br/web/api/document/close/index.html create mode 100644 files/pt-br/web/api/document/compatmode/index.html create mode 100644 files/pt-br/web/api/document/contenttype/index.html create mode 100644 files/pt-br/web/api/document/createelement/index.html create mode 100644 files/pt-br/web/api/document/createelementns/index.html create mode 100644 files/pt-br/web/api/document/currentscript/index.html create mode 100644 files/pt-br/web/api/document/defaultview/index.html create mode 100644 files/pt-br/web/api/document/designmode/index.html create mode 100644 files/pt-br/web/api/document/doctype/index.html create mode 100644 files/pt-br/web/api/document/document/index.html create mode 100644 files/pt-br/web/api/document/documentelement/index.html create mode 100644 files/pt-br/web/api/document/documenturi/index.html create mode 100644 files/pt-br/web/api/document/elementfrompoint/index.html create mode 100644 files/pt-br/web/api/document/elementoregistrado/index.html create mode 100644 files/pt-br/web/api/document/execcommand/index.html create mode 100644 files/pt-br/web/api/document/fullscreen/index.html create mode 100644 files/pt-br/web/api/document/getelementbyid/index.html create mode 100644 files/pt-br/web/api/document/getelementsbyclassname/index.html create mode 100644 files/pt-br/web/api/document/getelementsbyname/index.html create mode 100644 files/pt-br/web/api/document/getelementsbytagname/index.html create mode 100644 files/pt-br/web/api/document/getselection/index.html create mode 100644 files/pt-br/web/api/document/hasfocus/index.html create mode 100644 files/pt-br/web/api/document/head/index.html create mode 100644 files/pt-br/web/api/document/height/index.html create mode 100644 files/pt-br/web/api/document/images/index.html create mode 100644 files/pt-br/web/api/document/implementation/index.html create mode 100644 files/pt-br/web/api/document/importnode/index.html create mode 100644 files/pt-br/web/api/document/index.html create mode 100644 files/pt-br/web/api/document/keydown_event/index.html create mode 100644 files/pt-br/web/api/document/keypress_event/index.html create mode 100644 files/pt-br/web/api/document/keyup_event/index.html create mode 100644 files/pt-br/web/api/document/location/index.html create mode 100644 files/pt-br/web/api/document/origin/index.html create mode 100644 files/pt-br/web/api/document/queryselector/index.html create mode 100644 files/pt-br/web/api/document/queryselectorall/index.html create mode 100644 files/pt-br/web/api/document/readystate/index.html create mode 100644 files/pt-br/web/api/document/referrer/index.html create mode 100644 files/pt-br/web/api/document/scripts/index.html create mode 100644 files/pt-br/web/api/document/url/index.html create mode 100644 files/pt-br/web/api/document/write/index.html create mode 100644 files/pt-br/web/api/document/writeln/index.html create mode 100644 files/pt-br/web/api/documentfragment/index.html create mode 100644 files/pt-br/web/api/domexception/index.html create mode 100644 files/pt-br/web/api/domimplementation/createdocument/index.html create mode 100644 files/pt-br/web/api/domimplementation/index.html create mode 100644 files/pt-br/web/api/domstring/index.html create mode 100644 files/pt-br/web/api/domstringlist/index.html create mode 100644 files/pt-br/web/api/domstringmap/index.html create mode 100644 files/pt-br/web/api/element/accesskey/index.html create mode 100644 files/pt-br/web/api/element/addeventlistener/index.html create mode 100644 files/pt-br/web/api/element/animate/index.html create mode 100644 files/pt-br/web/api/element/attributes/index.html create mode 100644 files/pt-br/web/api/element/classlist/index.html create mode 100644 files/pt-br/web/api/element/classname/index.html create mode 100644 files/pt-br/web/api/element/click_event/index.html create mode 100644 files/pt-br/web/api/element/closest/index.html create mode 100644 files/pt-br/web/api/element/getattribute/index.html create mode 100644 files/pt-br/web/api/element/getboundingclientrect/index.html create mode 100644 files/pt-br/web/api/element/getelementsbyclassname/index.html create mode 100644 files/pt-br/web/api/element/id/index.html create mode 100644 files/pt-br/web/api/element/index.html create mode 100644 files/pt-br/web/api/element/innerhtml/index.html create mode 100644 files/pt-br/web/api/element/insertadjacenthtml/index.html create mode 100644 files/pt-br/web/api/element/matches/index.html create mode 100644 files/pt-br/web/api/element/mousedown_event/index.html create mode 100644 files/pt-br/web/api/element/mouseenter_event/index.html create mode 100644 files/pt-br/web/api/element/mouseover_event/index.html create mode 100644 files/pt-br/web/api/element/name/index.html create mode 100644 files/pt-br/web/api/element/outerhtml/index.html create mode 100644 files/pt-br/web/api/element/queryselector/index.html create mode 100644 files/pt-br/web/api/element/queryselectorall/index.html create mode 100644 files/pt-br/web/api/element/removeattribute/index.html create mode 100644 files/pt-br/web/api/element/scrollintoview/index.html create mode 100644 files/pt-br/web/api/element/scrollleft/index.html create mode 100644 files/pt-br/web/api/element/scrolltop/index.html create mode 100644 files/pt-br/web/api/element/scrollwidth/index.html create mode 100644 files/pt-br/web/api/element/setattribute/index.html create mode 100644 files/pt-br/web/api/element/setattributens/index.html create mode 100644 files/pt-br/web/api/element/tagname/index.html create mode 100644 files/pt-br/web/api/element/touchstart_event/index.html create mode 100644 files/pt-br/web/api/encoding_api/index.html create mode 100644 files/pt-br/web/api/event/comparativo_entre_event_targets/index.html create mode 100644 files/pt-br/web/api/event/currenttarget/index.html create mode 100644 files/pt-br/web/api/event/defaultprevented/index.html create mode 100644 files/pt-br/web/api/event/event/index.html create mode 100644 files/pt-br/web/api/event/index.html create mode 100644 files/pt-br/web/api/event/initevent/index.html create mode 100644 files/pt-br/web/api/event/istrusted/index.html create mode 100644 files/pt-br/web/api/event/preventdefault/index.html create mode 100644 files/pt-br/web/api/event/srcelement/index.html create mode 100644 files/pt-br/web/api/event/stopimmediatepropagation/index.html create mode 100644 files/pt-br/web/api/event/stoppropagation/index.html create mode 100644 files/pt-br/web/api/event/target/index.html create mode 100644 files/pt-br/web/api/event/type/index.html create mode 100644 files/pt-br/web/api/eventlistener/index.html create mode 100644 files/pt-br/web/api/eventsource/eventsource/index.html create mode 100644 files/pt-br/web/api/eventsource/index.html create mode 100644 files/pt-br/web/api/eventsource/onerror/index.html create mode 100644 files/pt-br/web/api/eventtarget/dispatchevent/index.html create mode 100644 files/pt-br/web/api/eventtarget/eventtarget/index.html create mode 100644 files/pt-br/web/api/eventtarget/index.html create mode 100644 files/pt-br/web/api/eventtarget/removeeventlistener/index.html create mode 100644 files/pt-br/web/api/fetch_api/basic_concepts/index.html create mode 100644 files/pt-br/web/api/fetch_api/index.html create mode 100644 files/pt-br/web/api/fetch_api/using_fetch/index.html create mode 100644 files/pt-br/web/api/fetch_api/uso_de_busca_cross-global/index.html create mode 100644 files/pt-br/web/api/file/index.html create mode 100644 files/pt-br/web/api/file/using_files_from_web_applications/index.html create mode 100644 files/pt-br/web/api/filelist/index.html create mode 100644 files/pt-br/web/api/filereader/filereader/index.html create mode 100644 files/pt-br/web/api/filereader/index.html create mode 100644 files/pt-br/web/api/filereader/onload/index.html create mode 100644 files/pt-br/web/api/filereader/readasarraybuffer/index.html create mode 100644 files/pt-br/web/api/filereader/readasbinarystring/index.html create mode 100644 files/pt-br/web/api/filereader/readasdataurl/index.html create mode 100644 files/pt-br/web/api/filereader/readastext/index.html create mode 100644 files/pt-br/web/api/formdata/append/index.html create mode 100644 files/pt-br/web/api/formdata/delete/index.html create mode 100644 files/pt-br/web/api/formdata/entries/index.html create mode 100644 files/pt-br/web/api/formdata/formdata/index.html create mode 100644 files/pt-br/web/api/formdata/get/index.html create mode 100644 files/pt-br/web/api/formdata/getall/index.html create mode 100644 files/pt-br/web/api/formdata/has/index.html create mode 100644 files/pt-br/web/api/formdata/index.html create mode 100644 files/pt-br/web/api/formdata/set/index.html create mode 100644 files/pt-br/web/api/fullscreenoptions/index.html create mode 100644 files/pt-br/web/api/gamepad_api/index.html create mode 100644 files/pt-br/web/api/geolocation/clearwatch/index.html create mode 100644 files/pt-br/web/api/geolocation/getcurrentposition/index.html create mode 100644 files/pt-br/web/api/geolocation/index.html create mode 100644 files/pt-br/web/api/geolocation/watchposition/index.html create mode 100644 files/pt-br/web/api/geolocationcoordinates/altitude/index.html create mode 100644 files/pt-br/web/api/geolocationcoordinates/index.html create mode 100644 files/pt-br/web/api/geolocationposition/coords/index.html create mode 100644 files/pt-br/web/api/geolocationposition/index.html create mode 100644 files/pt-br/web/api/geolocationpositionerror/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onabort/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onblur/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onchange/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onclick/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/oncontextmenu/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onerror/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onfocus/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onkeyup/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onload/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onlostpointercapture/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onscroll/index.html create mode 100644 files/pt-br/web/api/history/index.html create mode 100644 files/pt-br/web/api/history_api/exemplo/index.html create mode 100644 files/pt-br/web/api/history_api/index.html create mode 100644 files/pt-br/web/api/htmlcanvaselement/getcontext/index.html create mode 100644 files/pt-br/web/api/htmlcanvaselement/height/index.html create mode 100644 files/pt-br/web/api/htmlcanvaselement/index.html create mode 100644 files/pt-br/web/api/htmlcanvaselement/todataurl/index.html create mode 100644 files/pt-br/web/api/htmlcollection/index.html create mode 100644 files/pt-br/web/api/htmlcontentelement/getdistributednodes/index.html create mode 100644 files/pt-br/web/api/htmlcontentelement/index.html create mode 100644 files/pt-br/web/api/htmlcontentelement/seletor/index.html create mode 100644 files/pt-br/web/api/htmldivelement/index.html create mode 100644 files/pt-br/web/api/htmlelement/blur/index.html create mode 100644 files/pt-br/web/api/htmlelement/click/index.html create mode 100644 files/pt-br/web/api/htmlelement/contenteditable/index.html create mode 100644 files/pt-br/web/api/htmlelement/contextmenu/index.html create mode 100644 files/pt-br/web/api/htmlelement/dataset/index.html create mode 100644 files/pt-br/web/api/htmlelement/focus/index.html create mode 100644 files/pt-br/web/api/htmlelement/index.html create mode 100644 files/pt-br/web/api/htmlelement/lang/index.html create mode 100644 files/pt-br/web/api/htmlelement/offsetheight/index.html create mode 100644 files/pt-br/web/api/htmlelement/offsetleft/index.html create mode 100644 files/pt-br/web/api/htmlelement/offsetparent/index.html create mode 100644 files/pt-br/web/api/htmlelement/offsettop/index.html create mode 100644 files/pt-br/web/api/htmlelement/offsetwidth/index.html create mode 100644 files/pt-br/web/api/htmlinputelement/index.html create mode 100644 files/pt-br/web/api/htmlinputelement/select/index.html create mode 100644 files/pt-br/web/api/htmlinputelement/setselectionrange/index.html create mode 100644 files/pt-br/web/api/htmloptionelement/index.html create mode 100644 files/pt-br/web/api/htmloptionelement/option/index.html create mode 100644 files/pt-br/web/api/htmlselectelement/checkvalidity/index.html create mode 100644 files/pt-br/web/api/htmlselectelement/index.html create mode 100644 files/pt-br/web/api/htmlshadowelement/index.html create mode 100644 files/pt-br/web/api/htmlspanelement/index.html create mode 100644 files/pt-br/web/api/idbcursor/index.html create mode 100644 files/pt-br/web/api/idbfactory/index.html create mode 100644 files/pt-br/web/api/imagecapture/index.html create mode 100644 files/pt-br/web/api/index.html create mode 100644 files/pt-br/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/pt-br/web/api/indexeddb_api/index.html create mode 100644 files/pt-br/web/api/indexeddb_api/usando_indexeddb/index.html create mode 100644 files/pt-br/web/api/keyboardevent/index.html create mode 100644 files/pt-br/web/api/location/assign/index.html create mode 100644 files/pt-br/web/api/location/index.html create mode 100644 files/pt-br/web/api/location/reload/index.html create mode 100644 files/pt-br/web/api/location/search/index.html create mode 100644 files/pt-br/web/api/mediadevices/index.html create mode 100644 files/pt-br/web/api/mediastreamtrack/index.html create mode 100644 files/pt-br/web/api/messagechannel/index.html create mode 100644 files/pt-br/web/api/messageport/index.html create mode 100644 files/pt-br/web/api/messageport/postmessage/index.html create mode 100644 files/pt-br/web/api/mouseevent/clientx/index.html create mode 100644 files/pt-br/web/api/mouseevent/clienty/index.html create mode 100644 files/pt-br/web/api/mouseevent/index.html create mode 100644 files/pt-br/web/api/mutationobserver/index.html create mode 100644 files/pt-br/web/api/navigation_timing_api/index.html create mode 100644 files/pt-br/web/api/navigator/battery/index.html create mode 100644 files/pt-br/web/api/navigator/cookieenabled/index.html create mode 100644 files/pt-br/web/api/navigator/devicememory/index.html create mode 100644 files/pt-br/web/api/navigator/geolocation/index.html create mode 100644 files/pt-br/web/api/navigator/getusermedia/index.html create mode 100644 files/pt-br/web/api/navigator/index.html create mode 100644 files/pt-br/web/api/navigator/share/index.html create mode 100644 files/pt-br/web/api/navigatorid/index.html create mode 100644 files/pt-br/web/api/navigatorid/platform/index.html create mode 100644 files/pt-br/web/api/navigatorid/useragent/index.html create mode 100644 files/pt-br/web/api/navigatorlanguage/index.html create mode 100644 files/pt-br/web/api/navigatorlanguage/language/index.html create mode 100644 files/pt-br/web/api/navigatoronline/index.html create mode 100644 files/pt-br/web/api/navigatoronline/online/index.html create mode 100644 files/pt-br/web/api/navigatoronline/online_and_offline_events/index.html create mode 100644 files/pt-br/web/api/navigatorplugins/index.html create mode 100644 files/pt-br/web/api/navigatorplugins/javaenabled/index.html create mode 100644 files/pt-br/web/api/node/appendchild/index.html create mode 100644 files/pt-br/web/api/node/baseuri/index.html create mode 100644 files/pt-br/web/api/node/childnodes/index.html create mode 100644 files/pt-br/web/api/node/clonenode/index.html create mode 100644 files/pt-br/web/api/node/contains/index.html create mode 100644 "files/pt-br/web/api/node/entendendo_o_uso_do_m\303\251todo_appendchild-javascript/index.html" create mode 100644 files/pt-br/web/api/node/firstchild/index.html create mode 100644 files/pt-br/web/api/node/index.html create mode 100644 files/pt-br/web/api/node/innertext/index.html create mode 100644 files/pt-br/web/api/node/insertbefore/index.html create mode 100644 files/pt-br/web/api/node/isconnected/index.html create mode 100644 files/pt-br/web/api/node/lastchild/index.html create mode 100644 files/pt-br/web/api/node/nextsibling/index.html create mode 100644 files/pt-br/web/api/node/parentnode/index.html create mode 100644 files/pt-br/web/api/node/previoussibling/index.html create mode 100644 files/pt-br/web/api/node/removechild/index.html create mode 100644 files/pt-br/web/api/node/replacechild/index.html create mode 100644 files/pt-br/web/api/node/textcontent/index.html create mode 100644 files/pt-br/web/api/nodefilter/index.html create mode 100644 files/pt-br/web/api/nodelist/index.html create mode 100644 files/pt-br/web/api/notificacoes/index.html create mode 100644 files/pt-br/web/api/notificationaction/index.html create mode 100644 files/pt-br/web/api/offlineaudiocontext/index.html create mode 100644 files/pt-br/web/api/page_visibility_api/index.html create mode 100644 files/pt-br/web/api/parentnode/childelementcount/index.html create mode 100644 files/pt-br/web/api/parentnode/children/index.html create mode 100644 files/pt-br/web/api/parentnode/index.html create mode 100644 files/pt-br/web/api/parentnode/queryselector/index.html create mode 100644 files/pt-br/web/api/path2d/index.html create mode 100644 files/pt-br/web/api/performance/index.html create mode 100644 files/pt-br/web/api/performance/now/index.html create mode 100644 files/pt-br/web/api/performance/tojson/index.html create mode 100644 files/pt-br/web/api/positionoptions/index.html create mode 100644 files/pt-br/web/api/processinginstruction/index.html create mode 100644 files/pt-br/web/api/pushmanager/index.html create mode 100644 files/pt-br/web/api/randomsource/getrandomvalues/index.html create mode 100644 files/pt-br/web/api/randomsource/index.html create mode 100644 files/pt-br/web/api/request/index.html create mode 100644 files/pt-br/web/api/request/request/index.html create mode 100644 files/pt-br/web/api/response/index.html create mode 100644 files/pt-br/web/api/rtccertificate/index.html create mode 100644 files/pt-br/web/api/rtcdatachannel/index.html create mode 100644 files/pt-br/web/api/rtcicetransport/index.html create mode 100644 files/pt-br/web/api/rtcpeerconnection/connectionstate/index.html create mode 100644 files/pt-br/web/api/rtcpeerconnection/index.html create mode 100644 "files/pt-br/web/api/sele\303\247\303\243o/index.html" create mode 100644 files/pt-br/web/api/sensor/index.html create mode 100644 files/pt-br/web/api/server-sent_events/index.html create mode 100644 files/pt-br/web/api/server-sent_events/using_server-sent_events/index.html create mode 100644 files/pt-br/web/api/service_worker_api/index.html create mode 100644 files/pt-br/web/api/service_worker_api/using_service_workers/index.html create mode 100644 files/pt-br/web/api/serviceworkercontainer/index.html create mode 100644 files/pt-br/web/api/serviceworkercontainer/register/index.html create mode 100644 files/pt-br/web/api/serviceworkerglobalscope/clients/index.html create mode 100644 files/pt-br/web/api/serviceworkerglobalscope/index.html create mode 100644 files/pt-br/web/api/sharedworker/index.html create mode 100644 files/pt-br/web/api/sharedworker/port/index.html create mode 100644 files/pt-br/web/api/speechgrammar/index.html create mode 100644 files/pt-br/web/api/speechsynthesis/index.html create mode 100644 files/pt-br/web/api/speechsynthesisutterance/index.html create mode 100644 files/pt-br/web/api/speechsynthesisutterance/voice/index.html create mode 100644 files/pt-br/web/api/storage/clear/index.html create mode 100644 files/pt-br/web/api/storage/getitem/index.html create mode 100644 files/pt-br/web/api/storage/index.html create mode 100644 files/pt-br/web/api/storage/key/index.html create mode 100644 files/pt-br/web/api/storage/length/index.html create mode 100644 files/pt-br/web/api/storage/removeitem/index.html create mode 100644 files/pt-br/web/api/storage/setitem/index.html create mode 100644 files/pt-br/web/api/storagemanager/index.html create mode 100644 files/pt-br/web/api/streams_api/concepts/index.html create mode 100644 files/pt-br/web/api/streams_api/index.html create mode 100644 files/pt-br/web/api/subtlecrypto/derivekey/index.html create mode 100644 files/pt-br/web/api/subtlecrypto/generatekey/index.html create mode 100644 files/pt-br/web/api/subtlecrypto/importkey/index.html create mode 100644 files/pt-br/web/api/subtlecrypto/index.html create mode 100644 files/pt-br/web/api/svgaelement/index.html create mode 100644 files/pt-br/web/api/svgaelement/svgalement.target/index.html create mode 100644 files/pt-br/web/api/svganimatetransformelement/index.html create mode 100644 files/pt-br/web/api/url/createobjecturl/index.html create mode 100644 files/pt-br/web/api/url/index.html create mode 100644 files/pt-br/web/api/url/revokeobjecturl/index.html create mode 100644 files/pt-br/web/api/url/searchparams/index.html create mode 100644 files/pt-br/web/api/urlsearchparams/get/index.html create mode 100644 files/pt-br/web/api/urlsearchparams/index.html create mode 100644 files/pt-br/web/api/urlsearchparams/values/index.html create mode 100644 files/pt-br/web/api/validitystate/index.html create mode 100644 files/pt-br/web/api/web_animations_api/index.html create mode 100644 files/pt-br/web/api/web_animations_api/usando_a_web_animations_api/index.html create mode 100644 files/pt-br/web/api/web_crypto_api/index.html create mode 100644 files/pt-br/web/api/web_storage_api_pt_br/index.html create mode 100644 files/pt-br/web/api/web_storage_api_pt_br/using_the_web_storage_api/index.html create mode 100644 files/pt-br/web/api/web_workers_api/index.html create mode 100644 files/pt-br/web/api/webgl_api/index.html create mode 100644 files/pt-br/web/api/webgl_api/tutorial/adicionando_conteudo_2d_a_um_contexto_webgl/index.html create mode 100644 files/pt-br/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html create mode 100644 files/pt-br/web/api/webgl_api/tutorial/index.html create mode 100644 files/pt-br/web/api/webrtc_api/index.html create mode 100644 files/pt-br/web/api/webrtc_api/protocols/index.html create mode 100644 files/pt-br/web/api/webrtc_api/simples_rtcdatachannel_amostra/index.html create mode 100644 files/pt-br/web/api/websocket/index.html create mode 100644 files/pt-br/web/api/webvr_api/index.html create mode 100644 files/pt-br/web/api/webvr_api/using_the_webvr_api/index.html create mode 100644 files/pt-br/web/api/window/alert/index.html create mode 100644 files/pt-br/web/api/window/applicationcache/index.html create mode 100644 files/pt-br/web/api/window/closed/index.html create mode 100644 files/pt-br/web/api/window/confirm/index.html create mode 100644 files/pt-br/web/api/window/crypto/index.html create mode 100644 files/pt-br/web/api/window/document/index.html create mode 100644 files/pt-br/web/api/window/event/index.html create mode 100644 files/pt-br/web/api/window/fullscreen/index.html create mode 100644 files/pt-br/web/api/window/getselection/index.html create mode 100644 files/pt-br/web/api/window/history/index.html create mode 100644 files/pt-br/web/api/window/index.html create mode 100644 files/pt-br/web/api/window/innerheight/index.html create mode 100644 files/pt-br/web/api/window/length/index.html create mode 100644 files/pt-br/web/api/window/location/index.html create mode 100644 files/pt-br/web/api/window/matchmedia/index.html create mode 100644 files/pt-br/web/api/window/navigator/index.html create mode 100644 files/pt-br/web/api/window/ondevicelight/index.html create mode 100644 files/pt-br/web/api/window/onscroll/index.html create mode 100644 files/pt-br/web/api/window/opendialog/index.html create mode 100644 files/pt-br/web/api/window/performance/index.html create mode 100644 files/pt-br/web/api/window/popstate_event/index.html create mode 100644 files/pt-br/web/api/window/print/index.html create mode 100644 files/pt-br/web/api/window/prompt/index.html create mode 100644 files/pt-br/web/api/window/requestanimationframe/index.html create mode 100644 files/pt-br/web/api/window/requestidlecallback/index.html create mode 100644 files/pt-br/web/api/window/resize_event/index.html create mode 100644 files/pt-br/web/api/window/scroll/index.html create mode 100644 files/pt-br/web/api/window/scrollby/index.html create mode 100644 files/pt-br/web/api/window/scrollbypages/index.html create mode 100644 files/pt-br/web/api/window/scrollto/index.html create mode 100644 files/pt-br/web/api/window/scrolly/index.html create mode 100644 files/pt-br/web/api/window/sessionstorage/index.html create mode 100644 files/pt-br/web/api/window/setcursor/index.html create mode 100644 files/pt-br/web/api/window/setimmediate/index.html create mode 100644 files/pt-br/web/api/window/url/index.html create mode 100644 files/pt-br/web/api/window/window.localstorage/index.html create mode 100644 files/pt-br/web/api/windowbase64/atob/index.html create mode 100644 files/pt-br/web/api/windowbase64/index.html create mode 100644 files/pt-br/web/api/windoweventhandlers/index.html create mode 100644 files/pt-br/web/api/windoweventhandlers/onhashchange/index.html create mode 100644 files/pt-br/web/api/windoweventhandlers/onpopstate/index.html create mode 100644 files/pt-br/web/api/windoweventhandlers/onstorage/index.html create mode 100644 files/pt-br/web/api/windoworworkerglobalscope/fetch/index.html create mode 100644 files/pt-br/web/api/windoworworkerglobalscope/index.html create mode 100644 files/pt-br/web/api/windoworworkerglobalscope/setinterval/index.html create mode 100644 files/pt-br/web/api/windowtimers/cleartimeout/index.html create mode 100644 files/pt-br/web/api/windowtimers/index.html create mode 100644 files/pt-br/web/api/worker/index.html create mode 100644 files/pt-br/web/api/xmldocument/async/index.html create mode 100644 files/pt-br/web/api/xmldocument/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/abort/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/onreadystatechange/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/open/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/readystate/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/requisicoes_sincronas_e_assincronas/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/send/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/setrequestheader/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/timeout/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/usando_xmlhttprequest/index.html (limited to 'files/pt-br/web/api') diff --git a/files/pt-br/web/api/abortsignal/aborted/index.html b/files/pt-br/web/api/abortsignal/aborted/index.html new file mode 100644 index 0000000000..6158b810e9 --- /dev/null +++ b/files/pt-br/web/api/abortsignal/aborted/index.html @@ -0,0 +1,62 @@ +--- +title: AbortSignal.aborted +slug: Web/API/AbortSignal/aborted +tags: + - API + - AbortSignal + - Propriedade + - aborted +translation_of: Web/API/AbortSignal/aborted +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

A propriedade aborted é apenas para leitura e fornece um valor {{domxref("Boolean")}} indicando se as solicitações ao objeto sinal de comunicação DOM forão abortadas (true) ou não (false).

+ +

Sintaxe

+ +
var isAborted = abortSignal.aborted;
+ +

Valor

+ +

Um valor {{domxref("Boolean")}}

+ +

Exemplos

+ +

No fragmento abaixo, criamos um novo objeto AbortController e recebemos dele um sinal {{domxref("AbortSignal")}} (disponível na propriedade signal). Depois checamos se o sinal foi ou não abortado usando a propriedade aborted, e então enviamos um log apropriado para o console.

+ +
var controller = new AbortController();
+var signal = controller.signal;
+
+// ...
+
+signal.aborted ? console.log('Pedido foi abortado') : console.log('Pedido nao foi abortado');
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('DOM WHATWG', '#dom-abortsignal-onabort', 'onabort')}}{{Spec2('DOM WHATWG')}}Definição Inicial
+ +

Compatibilidade de Navegadores

+ + + +

{{Compat("api.AbortSignal.aborted")}}

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/abortsignal/index.html b/files/pt-br/web/api/abortsignal/index.html new file mode 100644 index 0000000000..1bfd9766c7 --- /dev/null +++ b/files/pt-br/web/api/abortsignal/index.html @@ -0,0 +1,101 @@ +--- +title: AbortSignal +slug: Web/API/AbortSignal +tags: + - API + - AbortSignal + - DOM + - Experimental + - Interface + - Referencia +translation_of: Web/API/AbortSignal +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

A interface AbortSignal  representa o sinal de um objeto que permite a você se comunicar com uma Requisição de DOM (como Fetch) e aborta-la se necessário via um objeto {{domxref("AbortController")}}

+ +

Propriedades

+ +

A interface AbortSignal também herda propriedades de sua interface pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("AbortSignal.aborted")}} {{readonlyInline}}
+
Um {{domxref("Boolean")}} que indica quando a(s) Request(s) com a qual o sinal está se comunicando está/estão abortadas(true) ou não(false).
+
+ +

Handlers de Eventos

+ +
+
{{domxref("AbortSignal.onabort")}}
+
Invocado quando um {{event("abort_(dom_abort_api)", "abort")}} evento dispara, ex: quando as requests do DOM que o sinal estão se comunicando são/estão abortadas.
+
+ +

Métodos

+ +

A interface AbortSignal também herda métodos de sua interface pai, {{domxref("EventTarget")}}.

+ +

Exemplos

+ +

No exemplo de código a seguir, nós vamos focar em fazer download de um vídeo usando a Fetch API.

+ +

Nós primeiro criaremos um controller usando o construtor do {{domxref("AbortController.AbortController","AbortController()")}}, e então pegar a referência de seu objeto {{domxref("AbortSignal")}} associado usando a propriedade {{domxref("AbortController.signal")}}.

+ +

Quando a requisição Fetch é iniciada, nós passamos o AbortSignal  como uma opção dentro do objeto de opções da request (veja {signal}, abaixo). Isso associa o sinal e o controller com a requisição fetch e nos permite aborta-la chamando {{domxref("AbortController.abort()")}}, como visto abaixo no segundo event listener.

+ +
var controller = new AbortController();
+var signal = controller.signal;
+
+var downloadBtn = document.querySelector('.download');
+var abortBtn = document.querySelector('.abort');
+
+downloadBtn.addEventListener('click', fetchVideo);
+
+abortBtn.addEventListener('click', function() {
+  controller.abort();
+  console.log('Download aborted');
+});
+
+function fetchVideo() {
+  ...
+  fetch(url, {signal}).then(function(response) {
+    ...
+  }).catch(function(e) {
+    reports.textContent = 'Download error: ' + e.message;
+  })
+}
+ +
+

Nota: Quando abort() é chamado, a promessa do fetch() é rejeitada com um AbortError.

+
+ +

Você pode encontrar um exemplo completo no GitHub — veja abort-api (see it running live also).

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#interface-AbortSignal', 'AbortSignal')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Compatibilidade de Browser

+ + + +

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

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/abstractworker/index.html b/files/pt-br/web/api/abstractworker/index.html new file mode 100644 index 0000000000..824ccd2aaa --- /dev/null +++ b/files/pt-br/web/api/abstractworker/index.html @@ -0,0 +1,103 @@ +--- +title: AbstractWorker +slug: Web/API/AbstractWorker +translation_of: Web/API/AbstractWorker +--- +

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

+ +

Resumo

+ +

A interface AbstractWorker abstrai propriedades e métodos comuns para todo o tipo de Workers, sendo {{domxref("Worker")}} ou {{domxref("SharedWorker")}}.

+ +

Propriedades

+ +

A interface AbstractWorker não herda qualquer propriedade..

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
É um {{ domxref("EventListener") }} que é chamado sempre que um {{domxref("ErrorEvent")}} do tipo error borbulha através do Worker.
+
+ +

Métodos

+ +

A interface AbstractWorker não implementa ou herda qualquer método.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "#the-abstractworker-abstract-interface", "AbstractWorker")}}{{Spec2('HTML WHATWG')}}Sem mudanças para {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#the-abstractworker-abstract-interface", "AbstractWorker")}}{{Spec2('HTML5 W3C')}}Definição Inicial
+ +

Compatibilidade de Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + + +

 

diff --git a/files/pt-br/web/api/abstractworker/onerror/index.html b/files/pt-br/web/api/abstractworker/onerror/index.html new file mode 100644 index 0000000000..b6ce35361e --- /dev/null +++ b/files/pt-br/web/api/abstractworker/onerror/index.html @@ -0,0 +1,104 @@ +--- +title: AbstractWorker.onerror +slug: Web/API/AbstractWorker/onerror +translation_of: Web/API/AbstractWorker/onerror +--- +

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

+ +

Resumo

+ +

A propriedade AbstractWorker.onerror da interface {{domxref("AbstractWorker")}} representa um {{domxref("EventHandler")}}, que é uma função a ser chamada quando o evento {{event("error")}} ocorre através de um balão de notificação {{domxref("Worker")}}.

+ +

Sintaxe

+ +
myWorker.onerror = function() { ... };
+ +

Exemplo

+ +

O seguinte trecho de código mostra criação de um objeto Worker usando o construtor de Worker() e criando um manipulador onerror no objeto resultante:

+ +
var myWorker = new Worker("worker.js");
+
+myWorker.onerror = function() {
+  console.log('Há um erro com o seu worker!');
+}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "#handler-abstractworker-onerror", "AbstractWorker.onerror")}}{{Spec2('HTML WHATWG')}}Nenhuma mudança em {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#handler-abstractworker-onerror", "AbstractWorker.onerror")}}{{Spec2('Web Workers')}}Definição inicial.
+ +

Compatibilidade dos Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(4)}}{{CompatGeckoDesktop("1.9.1")}}1010.64
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico4.4{{CompatGeckoMobile("1.9.1")}}1.0.11011.55.1
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/ambient_light_events/index.html b/files/pt-br/web/api/ambient_light_events/index.html new file mode 100644 index 0000000000..d011d08e08 --- /dev/null +++ b/files/pt-br/web/api/ambient_light_events/index.html @@ -0,0 +1,116 @@ +--- +title: Ambient Light Events +slug: Web/API/Ambient_Light_Events +tags: + - Ambiente de luz + - Ambiente de luz API + - Ambiente e luz HTML5 API +translation_of: Web/API/Ambient_Light_Events +--- +
Os eventos de luz ambiente são uma maneira útil de tornar uma página da Web ou uma aplicação consciente de qualquer alteração na intensidade da luz. Isso permite que eles reajam a tal mudança, por exemplo alterando o contraste de cores da interface do usuário (UI) ou alterando a exposição necessária para tirar uma foto.
+ +
 
+ +

Eventos de  luz

+ +

Quando o sensor de luz de um dispositivo detecta uma mudança no nível de luz, ele notifica o navegador dessa alteração. Quando o navegador obtém tal notificação, ele dispara um evento DeviceLightEvent que fornece informações sobre a intensidade da luz exata.

+ +

Este evento pode ser capturado no nível do objeto da janela usando o método addEventListener (usando o nome do evento devicelight) ou anexando um manipulador de eventos à propriedade window.ondevicelight.

+ +

Uma vez capturado, o objeto de evento dá acesso à intensidade da luz expressa em lux através da propriedade DeviceLightEvent.value.

+ +

Exemplo

+ +
window.addEventListener('devicelight', function(event) {
+  var html = document.getElementsByTagName('html')[0];
+
+  if (event.value < 50) {
+    html.classList.add('darklight');
+    html.classList.remove('brightlight');
+  } else {
+    html.classList.add('brightlight');
+    html.classList.remove('darklight');
+  }
+});
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstatusComentário
Sensor de luz ambiente A definição de "Ambient Light Events" nessa especificação. +

Rascunho do Editor

+
Definição inicial
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
{{domxref("DeviceLightEvent")}}{{CompatNo}}{{CompatGeckoDesktop("22.0")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
{{domxref("DeviceLightEvent")}}{{CompatNo}}support{{CompatGeckoMobile("15.0")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] O evento "devicelight" é implementado e a preferência ativada por padrão no Firefox Mobile para Android (15.0) e no Firefox OS (B2G). Começando com Gecko 22.0 geckoRelease ("22.0"), uma implementação de desktop para Mac OS X também está disponível. O suporte para o Windows 7 está em andamento (veja bug (754199)).

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/angle_instanced_arrays/index.html b/files/pt-br/web/api/angle_instanced_arrays/index.html new file mode 100644 index 0000000000..18f90385a0 --- /dev/null +++ b/files/pt-br/web/api/angle_instanced_arrays/index.html @@ -0,0 +1,88 @@ +--- +title: ANGLE_instanced_arrays +slug: Web/API/ANGLE_instanced_arrays +tags: + - API + - Reference + - WebGL + - WebGL extension +translation_of: Web/API/ANGLE_instanced_arrays +--- +
{{APIRef("WebGL")}}
+ +

A extenção ANGLE_instanced_arrays é parte do WebGL API e permite desenhar o mesmo objeto, ou grupos de objectos semelhantes várias vezes, se eles compartilham os mesmos dados de vértice, contagem primitiva e tipo.

+ +

As extensões WebGL estão disponíveis usando o método {{domxref("WebGLRenderingContext.getExtension()")}}. Para mais informações, veja também Usando Extenções no WebGL tutorial.

+ +
+

Disponibilidade: Esta extenção só está disponível para contextos {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}}. Em {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}}, a funcionalidade desta extenção está disponível no contexto WebGL2 por padrão e as constantes e métodos estao disponíveis sem o sufixo "ANGLE".

+ +

Apesar do nome "ANGLE", esta extenção funciona em qualquer dispositivo se o hardware oferece suporte a ele e não apenas no Windows ao usar a biblioteca ANGLE. "ANGLE" apenas indica que essa extencão foi escrita pelos autores da biblioteca ANGLE.

+
+ +

Constantes

+ +

Essa extensão expõe uma nova constante, que pode ser usada no método {{domxref("WebGLRenderingContext.getVertexAttrib()", "gl.getVertexAttrib()")}}:

+ +
+
ext.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE
+
Retorna um {{domxref("GLint")}} descrevendo o divisor de frequência usado para renderização instanciada quando usado no {{domxref("WebGLRenderingContext.getVertexAttrib()", "gl.getVertexAttrib()")}} como parâmetro pname.
+
+ +

Métodos

+ +

Essa extensão expõe três novos métodos.

+ +
+
{{domxref("ANGLE_instanced_arrays.drawArraysInstancedANGLE()", "ext.drawArraysInstancedANGLE()")}}
+
+

Se comporta de forma idêntica a {{domxref("WebGLRenderingContext.drawArrays()", "gl.drawArrays()")}} exceto que múltiplo instâncias do intervalo de elementos são executadas e a instância avança para cada iteração.

+
+
{{domxref("ANGLE_instanced_arrays.drawElementsInstancedANGLE()", "ext.drawElementsInstancedANGLE()")}}
+
+

Comporta-se de forma idêntica para o {{domxref("WebGLRenderingContext.drawElements()", "gl.drawElements()")}} exceto que várias instâncias do conjunto de elementos são executadas e a instância avança entre cada conjunto.

+
+
{{domxref("ANGLE_instanced_arrays.vertexAttribDivisorANGLE()", "ext.vertexAttribDivisorANGLE()")}}
+
+

Modifica a taxa na qual os atributos de vértice genéricos avançam ao renderizar várias instâncias de primitivos com {{domxref("ANGLE_instanced_arrays.drawArraysInstancedANGLE()", "ext.drawArraysInstancedANGLE()")}} e {{domxref("ANGLE_instanced_arrays.drawElementsInstancedANGLE()", "ext.drawElementsInstancedANGLE()")}}.

+
+
+ +

Exemplos

+ +

Habilitando a extenção:

+ +
var ext = gl.getExtension('ANGLE_instanced_arrays');
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ANGLE_instanced_arrays', '', 'ANGLE_instanced_arrays')}}{{Spec2('ANGLE_instanced_arrays')}}definição inicial.
+ +

Compatibilidade do navegador

+ + + +

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

+ +

Ver também

+ + diff --git a/files/pt-br/web/api/animation/cancel/index.html b/files/pt-br/web/api/animation/cancel/index.html new file mode 100644 index 0000000000..ceb1b7cf6c --- /dev/null +++ b/files/pt-br/web/api/animation/cancel/index.html @@ -0,0 +1,120 @@ +--- +title: Animation.cancel() +slug: Web/API/Animation/cancel +translation_of: Web/API/Animation/cancel +--- +

{{ SeeCompatTable() }}{{ APIRef("Web Animations API") }}

+ +

O método Animation.cancel() da interface  {{domxref("Animation")}} , limpa todas as  {{domxref("KeyframeEffect", "keyframeEffects")}} geradas pela animação e aborta esta execução.

+ +
+

Quando uma animação é cancelada, os valores de {{domxref("Animation.startTime", "startTime")}} e {{domxref("Animation.currentTime", "currentTime")}} são definidos como null.

+
+ +

Sintaxe

+ +
+
// cancela animação
+animation.cancel();
+
+ +

Parametros

+ +

Nenhum.

+ +

Valor de retorno

+ +

Nenhum.

+ +
+
+ +

Exceptions

+ +

Se o método {{domxref("Animation.playState")}} da animação estiver executando quando a operação for cancelada, esta ação vai rejeitar a {{domxref("Animation.finished", "current finished promise")}} com a {{domxref("DOMException")}} nomeada AbortError.

+ +
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations', '#dom-animation-cancel', 'Animation.cancel()' )}}{{Spec2('Web Animations')}}Editor's draft.
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(40)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{ CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/animation/currenttime/index.html b/files/pt-br/web/api/animation/currenttime/index.html new file mode 100644 index 0000000000..e5b7c25559 --- /dev/null +++ b/files/pt-br/web/api/animation/currenttime/index.html @@ -0,0 +1,112 @@ +--- +title: Animation.currentTime +slug: Web/API/Animation/currentTime +translation_of: Web/API/Animation/currentTime +--- +

{{APIRef("Web Animations")}}{{SeeCompatTable}}

+ +

A propriedade Animation.currentTime da Web Animations API retorna e altera o tempo atual da animação em milésimos de segundos, seja estando em execução ou pausada.

+ +

Se a animação não tem uma {{domxref("AnimationTimeline", "timeline")}}, está inativa, ou ainda não foi colocada em execução, o valor de retorno do currentTime será null

+ +

Sintaxe

+ +
vartempoAtual = Animation.currentTime;
+Animation.currentTime = novoTempo;
+ +

Valor

+ +

Um número que representará no tempo atual da animação em milésimos de segundos, ou null para desativar a animação.

+ +

Examples

+ +

No jogo Drink Me/Eat Me, O tamanho da Alice é animado e pode crescer ou diminuir. No início do jogo, o tamanho dela foi colocado entre os dois extremos do animation's currentTime no meio do KeyframeEffect's duration, desta maneira:

+ +
aliceChange.currentTime = aliceChange.effect.timing.duration / 2;
+ +

Outra forma mais genérica para encontrar o marco de 50% da animação pode ser feito da seguinte forma:

+ +
animation.currentTime =
+  animation.effect.getComputedTiming().delay +
+  animation.effect.getComputedTiming().activeDuration / 2;
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('Web Animations', '#dom-animation-currenttime', 'currentTime')}}{{Spec2("Web Animations")}} 
+ +

Compatibilidade de Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop(48)}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(39.0)}}{{CompatGeckoMobile(48)}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(39.0)}}
+
+ +

[1] A Web Animations API está ativa por padrão apenas no Firefox Developer Edition e nas versões do Nightly. Você pode habilitá-la em versões beta configurando a preferência dom.animations-api.core.enabled para true, e também desativar em qualquer Firefox mudando esta mesma preferência para false.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/animation/index.html b/files/pt-br/web/api/animation/index.html new file mode 100644 index 0000000000..09d2f0091c --- /dev/null +++ b/files/pt-br/web/api/animation/index.html @@ -0,0 +1,171 @@ +--- +title: Animation +slug: Web/API/Animation +tags: + - API + - Animations + - Experimental + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Animations + - waapi + - web animation api +translation_of: Web/API/Animation +--- +

{{ APIRef("Web Animations API") }}{{SeeCompatTable}}

+ +

A interface Animation da Web Animations API representa um único player de animação e fornece controles e uma linha do tempo (timeline) para um nó de animação ou recurso.

+ +

Construtor

+ +
+
{{domxref("Animation.Animation()", "Animation()")}}
+
Cria uma nova instância do objeto Animation.
+
+ +

Propriedades

+ +
+
{{domxref("Animation.currentTime")}}
+
O valor do tempo atual da animação, em milissegundos, esteja ela executando ou pausada. Se a animação não tem uma {{domxref("AnimationTimeline", "timeline")}}, está inativa ou ainda não foi executada, este valor é null.
+
+ +
+
{{domxref("Animation.effect")}}
+
Obtém e define o {{domxref("KeyframeEffect")}} associado a essa animação.
+
{{domxref("Animation.finished")}} {{readOnlyInline}}
+
Retorna a Primise de finalização atual para essa animação.
+
+ +
+
{{domxref("Animation.id")}}
+
Obtém e define a String usada para identificar a animação.
+
{{domxref("Animation.oncancel")}}
+
Obtém e define o manipulador para o evento cancel.
+
{{domxref("Animation.onfinish")}}
+
Obtém e define o manipulador para o evento finish.
+
{{domxref("Animation.playState")}} {{readOnlyInline}}
+
Retorna um valor enumerado descrevendo o estado de execução de uma animação.
+
+ +
+
{{domxref("Animation.playbackRate")}}
+
Obtém ou define a taxa de execução da animação.
+
+ +
+
{{domxref("Animation.ready")}} {{readOnlyInline}}
+
Retorna a promessa atual para quando essa animação estiver pronta.
+
+ +
+
{{domxref("Animation.startTime")}}
+
Obtém ou define o tempo agendado quando a execução de uma animação deve começar.
+
+ +
+
{{domxref("Animation.timeline")}}
+
Obtém ou define a {{domxref("AnimationTimeline", "timeline")}} associada a essa animação.
+
+ +

Métodos

+ +
+
{{domxref("Animation.cancel()")}}
+
Limpa todos os {{domxref("KeyframeEffect", "keyframeEffects")}} causados por essa animação e aborta sua execução.
+
+ +
+
{{domxref("Animation.finish()")}}
+
Vai até um dos extremos dessa animação, dependendo se ela está executando ou retornando.
+
+ +
+
{{domxref("Animation.pause()")}}
+
Suspende a execução de uma animação.
+
+ +
+
{{domxref("Animation.play()")}}
+
Inicia ou continua a execução de uma animação ou a recomeça se ela tiver terminado anteriormente.
+
+ +
+
{{domxref("Animation.reverse()")}}
+
Move a animação ao contrário, parando no início da animação.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("Web Animations", "#the-animation-interface", "Animation")}}{{Spec2("Web Animations")}}Definição inicial
+ +

Compatibilidade com navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(39.0)}} [1]{{CompatGeckoDesktop(40.0)}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}} [1]{{CompatGeckoDesktop(40.0)}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Implementado como AnimationPlayer (nome da interface em uma versão primária da especificação).

+ +

[2] Anteriormente ao Firefox 40, estava disponível como AnimationPlayer. Em ambos os casos, é necessário definir a preferência dom.animations-api.core.enabled para poder usá-la.

+ +

 

diff --git a/files/pt-br/web/api/animation/playstate/index.html b/files/pt-br/web/api/animation/playstate/index.html new file mode 100644 index 0000000000..a31d8d7c64 --- /dev/null +++ b/files/pt-br/web/api/animation/playstate/index.html @@ -0,0 +1,152 @@ +--- +title: Animation.playState +slug: Web/API/Animation/playState +translation_of: Web/API/Animation/playState +--- +

{{APIRef("Web Animations")}}{{SeeCompatTable}}

+ +


+ A propriedade Animation.playState do Web Animations API retorna e altera um valor enumerado que descreve o estado de reprodução da animação.

+ +
+

Essa propriedade é apenas de leitura para Animações CSS e Transições.

+
+ +

Sintaxe

+ +
var estadoAtualDaReproducao = Animation.playState;
+
+Animation.playState =novoEstado;
+
+ +

Valor

+ +
+
idle
+
O tempo atual da animação não está acertado e não há tarefas pendentes.
+
pending
+
A animação está aguardando a realização de algumas tarefas para ser completada.
+
running
+
A animação está rodando.
+
paused
+
A animação está parada e a propriedade {{domxref("Animation.currentTime")}} não está sendo atualizada.
+
finished
+
A animação alcançou um de seus finais e a propriedade {{domxref("Animation.currentTime")}} não está sendo atualizada.
+
+ +

Exemplo

+ +

No jogo Growing/Shrinking Alice Game , os jogadores podem chegar ao final com a Alice chorando em uma poça de lágrimas. No jogo, por razões de performance, as lágrimas só são animadas quando estão visiveis. Então elas devem ficar pausadas enquanto a animação ocorre, como no exemplo:

+ +
// Configurando a animação das lágrimas
+
+tears.forEach(function(el) {
+  el.animate(
+    tearsFalling,
+    {
+      delay: getRandomMsRange(-1000, 1000), // aleatório para cada lágrima
+      duration: getRandomMsRange(2000, 6000), // aleatório para cada lágrima
+      iterations: Infinity,
+      easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)"
+    });
+  el.playState = 'paused';
+});
+
+
+// Rodar as lágrimas caindo quando o final precisa aparecer.
+
+tears.forEach(function(el) {
+  el.playState = 'playing';
+});
+
+
+// Reseta a animação e coloca o estado em pause.
+
+tears.forEach(function(el) {
+  el.playState = "paused";
+  el.currentTime = 0;
+});
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentários
{{SpecName('Web Animations', '#play-state', 'playState')}}{{Spec2("Web Animations")}}Initial definition.
+ +

Compatibilidade de Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(39.0)}} [1]{{CompatGeckoDesktop(48)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(39.0)}} [1]{{CompatChrome(39.0)}} [1]{{CompatGeckoMobile(48)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Antes do Chrome 50, este atributo retorna idle para animações que ainda não foram reproduzidas . A partir do Chrome 50, ele retorna paused.

+ +

[2] A Web Animations API está ativa por padrão apenas no Firefox Developer Edition e nas versões do Nightly. Você pode habilitá-la em versões beta configurando a preferência dom.animations-api.core.enabled para true, e também desativar em qualquer Firefox mudando esta mesma preferência para false.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/animationevent/animationevent/index.html b/files/pt-br/web/api/animationevent/animationevent/index.html new file mode 100644 index 0000000000..77fcdeb37e --- /dev/null +++ b/files/pt-br/web/api/animationevent/animationevent/index.html @@ -0,0 +1,134 @@ +--- +title: AnimationEvent() +slug: Web/API/AnimationEvent/AnimationEvent +tags: + - AnimationEvent + - Apps + - CSSOM + - Experimental + - Referencia +translation_of: Web/API/AnimationEvent/AnimationEvent +--- +

{{APIRef("Web Animations API")}}{{SeeCompatTable}}

+ +

O construtor AnimationEvent()retorna o recente criado {{domxref("AnimationEvent")}}, representando um evento em relação a animação.

+ +

Síntaxe

+ +
animationEvent = new AnimationEvent(type, {animationName: aPropertyName,
+                                           elapsedTime  : aFloat,
+                                           pseudoElement: aPseudoElementName});
+
+ +

Argumentos

+ +

O construtor AnimationEvent() também herda argumentos do {{domxref("Event.Event", "Event()")}}.

+ +
+
type
+
Um {{domxref("DOMString")}} representando o nome do tipo de AnimationEvent. É caso sensitivo e pode ser: 'animationstart', 'animationend', ou 'animationiteration'.
+
animationName {{optional_inline}}
+
Um{{domxref("DOMString")}} contendo o valor do {{cssxref("animation-name")}} propriedade CSS associada com a transição. É por padrão "".
+
elapsedTime {{optional_inline}}
+
Um ponto flutuante dando a quantidade de tempo que a animação esteve rodando, em segundos, quando o evento termina, excluindo qualquer tempo que ela passou pausada. Para um evento "animationstart", elapsedTime é 0.0 a não ser que haja um valor negativo para animation-delay, nesse caso o evento terminará com elapsedTime contendo  (-1 * delay). É por padrão 0.0.
+
pseudoElement {{optional_inline}}
+
É um {{domxref("DOMString")}}, começando com"::", contendo o nome do pseudo-element que a animação roda. Se a animação não roda em um pseudo-elementomas em um elemento, então temos um string vazio "" .É por padrão ""
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesEstadoComentário
{{ SpecName('CSS3 Animations', '#AnimationEvent-interface', 'AnimationEvent()') }}{{ Spec2('CSS3 Animations')}}Initial definition.
+ +

Compatibilidade com os Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(43.0)}}{{ CompatGeckoDesktop("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
pseudoElement{{CompatNo}}{{ CompatGeckoDesktop("23.0") }} +

{{CompatNo}}

+
{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(43.0)}}
pseudoElement{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também 

+ + diff --git a/files/pt-br/web/api/animationevent/animationname/index.html b/files/pt-br/web/api/animationevent/animationname/index.html new file mode 100644 index 0000000000..62a739e4e2 --- /dev/null +++ b/files/pt-br/web/api/animationevent/animationname/index.html @@ -0,0 +1,102 @@ +--- +title: AnimationEvent.animationName +slug: Web/API/AnimationEvent/animationName +tags: + - AnimationEvent + - Animação Web + - Apps + - CSSOM + - Propriedade + - Referencia +translation_of: Web/API/AnimationEvent/animationName +--- +

{{SeeCompatTable}}{{ apiref("Web Animations API") }}

+ +

AnimationEvent.animationName é uma propriedade só de leitura do{{domxref("DOMString")}} contendo o valor de {{cssxref("animation-name")}} propriedade CSS relacionada com a trasição.

+ +

Síntaxe

+ +
name = AnimationEvent.animationName
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{ SpecName('CSS3 Animations', '#AnimationEvent-animationName', 'AnimationEvent.animationName') }}{{ Spec2('CSS3 Animations')}}Initial definition.
+ +

Compatibilidade com os Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ +

 

+ +

 

+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/animationevent/elapsedtime/index.html b/files/pt-br/web/api/animationevent/elapsedtime/index.html new file mode 100644 index 0000000000..4d04b30c90 --- /dev/null +++ b/files/pt-br/web/api/animationevent/elapsedtime/index.html @@ -0,0 +1,103 @@ +--- +title: AnimationEvent.elapsedTime +slug: Web/API/AnimationEvent/elapsedTime +tags: + - AnimationEvent + - Animações Web + - Apps + - CSSOM + - Experimental + - Propriedade + - Referencia +translation_of: Web/API/AnimationEvent/elapsedTime +--- +

{{SeeCompatTable}}{{ apiref("Web Animations API") }}

+ +

Sumário

+ +

AnimationEvent.elapsedTime é uma propriedade só de leitura com um ponto flutuante dando a quantidade de tempo que animação esteve rodando, em segundos, quando o evento termina, excluirá o tempo em que ela esteve em pausa. Para um evento "animationstart" , elapsedTime é 0.0 a não ser que tenha um valor negativo para {{cssxref("animation-delay")}}, nesse caso o evento irá terminar com elapsedTime contendo (-1 * delay).

+ +

Síntaxe

+ +
time = AnimationEvent.elapsedTime
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Animations', '#AnimationEvent-elapsedTime', 'AnimationEvent.elapsedTime') }}{{ Spec2('CSS3 Animations')}}Initial definition.
+ +

Compatibilidade com os Navegadores

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{ CompatGeckoMobile("6.0") }}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatChrome(43.0)}}
+
+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/animationevent/index.html b/files/pt-br/web/api/animationevent/index.html new file mode 100644 index 0000000000..c2abeb0bf6 --- /dev/null +++ b/files/pt-br/web/api/animationevent/index.html @@ -0,0 +1,194 @@ +--- +title: AnimationEvent +slug: Web/API/AnimationEvent +tags: + - API + - Animação Web + - Experimental + - Expérimental(2) + - Interface + - NeedsTranslation + - Reference + - Referencia + - Référence(2) + - TopicStub +translation_of: Web/API/AnimationEvent +--- +

{{SeeCompatTable}}{{APIRef("Web Animations API")}}

+ +

A interface AnimationEvent  representa eventos provendo informações relacionadas a animações.

+ +

{{InheritanceDiagram}}

+ +

Propriedades

+ +

Também propriedades herdadas pelo pai {{domxref("Event")}}.

+ +
+
{{domxref("AnimationEvent.animationName")}} {{readonlyInline}}
+
O {{domxref("DOMString")}} contém o valor do {{cssxref("animation-name")}} propriedade CSS associada com a transição.
+
{{domxref("AnimationEvent.elapsedTime")}} {{readonlyInline}}
+
É um ponto flutuante dado pela quantidade de tempo que a animação está rodando, em segundos, quando esse evento termina, excluindo o tempo em que animação esteve pausada. Para o evento "animationstart", elapsedTime é 0.0 a não ser que haja um valor negativo para {{cssxref("animation-delay")}}, nesse caso o evento terminará com elapsedTime contendo  (-1 * delay).
+
{{domxref("AnimationEvent.pseudoElement")}} {{readonlyInline}}
+
Um {{domxref("DOMString")}} começa com  '::', contendo o nome do pseudo-elemento onde a animação roda. Se a animação não rodar no pseudo-elemento mas no elemento, então teremos um string vazio ' '.
+
+ +

Constructores

+ +
+
{{domxref("AnimationEvent.AnimationEvent", "AnimationEvent()")}}
+
Cria um evento AnimationEvent com os dados parâmetros.
+
+ +

Métodos

+ +

Também herda métodos do pai {{domxref("Event")}}.

+ +
+
{{domxref("AnimationEvent.initAnimationEvent()")}} {{non-standard_inline}}{{deprecated_inline}}
+
Inicializa um AnimationEvent criado usando diminuído {{domxref("Document.createEvent()", "Document.createEvent(\"AnimationEvent\")")}} método.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{ SpecName('CSS3 Animations', '#AnimationEvent-interface', 'AnimationEvent') }}{{ Spec2('CSS3 Animations') }}Definição inicial.
+ +

Compatibilidade com o Navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support +

1.0 {{ property_prefix("webkit") }}

+ +

{{CompatChrome(43.0)}}

+
{{ CompatGeckoDesktop("6.0") }}10.012 {{ property_prefix("o") }}
+ 12.10
+ 15.0 {{ property_prefix("webkit") }}
4.0 {{ property_prefix("webkit") }}
AnimationEvent() constructor +

{{CompatChrome(43.0)}}

+
{{ CompatGeckoDesktop("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
initAnimationEvent() {{non-standard_inline}}{{deprecated_inline}}1.0{{ CompatGeckoDesktop("6.0") }}
+ Removed in {{ CompatGeckoDesktop("23.0") }}
10.0124.0
pseudoelement{{CompatNo}}{{ CompatGeckoDesktop("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{ property_prefix("webkit") }}{{ CompatGeckoMobile("6.0") }}10.012 {{ property_prefix("o") }}
+ 12.10
+ 15.0 {{ property_prefix("webkit") }}
{{CompatVersionUnknown}}{{ property_prefix("webkit") }}{{CompatChrome(43.0)}}
AnimationEvent() constructor{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(43.0)}}
initAnimationEvent() {{non-standard_inline}}{{deprecated_inline}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("6.0") }}
+ Removed in {{ CompatGeckoMobile("23.0") }}
10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}
pseudoelement{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/animationevent/initanimationevent/index.html b/files/pt-br/web/api/animationevent/initanimationevent/index.html new file mode 100644 index 0000000000..e9b0819b98 --- /dev/null +++ b/files/pt-br/web/api/animationevent/initanimationevent/index.html @@ -0,0 +1,134 @@ +--- +title: AnimationEvent.initAnimationEvent() +slug: Web/API/AnimationEvent/initAnimationEvent +tags: + - AnimationEvent + - Apps + - CSSOM + - Método(2) + - Não-padrão + - Obsolento + - Web Animations +translation_of: Web/API/AnimationEvent/initAnimationEvent +--- +

{{obsolete_header}}{{non-standard_header}}{{ apiref("Web Animations API") }}

+ +

Sumário

+ +

AnimationEvent.initAnimationEvent() é um método iniciado com o evento da animção criando um depreciativo {{domxref("Document.createEvent()", "Document.createEvent(\"AnimationEvent\")")}} método.

+ +

AnimationEvent criado desse modo não é confiável.

+ +
+

Note: Durante o processo de padronização, esse método foi removido das especificações. É que ele foi depreciado e esse processo foi removido da maioria das implementações . Não use este método; ao invés, use o construtor padrão, {{domxref("AnimationEvent.AnimationEvent", "AnimationEvent()")}}, para criar um sintético {{domxref("AnimationEvent")}}.

+
+ +

Syntax

+ +
animationEvent.initAnimationEvent(typeArg, canBubbleArg, cancelableArg, animationNameArg, elapsedTimeArg);
+ +

Parâmetros

+ +
+
typeArg
+
Um {{domxref("DOMString")}} identificado com um tipo específico de evento animação que ocorreu. Os seguintes valores são aceitados: + + + + + + + + + + + + + + + + + + + + + +
ValorSignificado
animationstartA animação começou.
animationendA animação terminou.
animationiterationA iteração corrente se completou.
+
+
canBubbleArg
+
Uma {{domxref("Boolean")}} bandeira indicando se o evento pode ser bolha (true) ou não (false).
+
cancelableArg
+
Uma {{domxref("Boolean")}} bandeira indicando se o evento associado pode ser evitado (true) ou não (false).
+
animationNameArg
+
Um {{domxref("DOMString")}} contendo o valor do{{cssxref("animation-name")}} propriedade CSS associada com a transição.
+
elapsedTimeArg
+
Um ponto flutuante indicando a quantidade de tempo que a animação esteve rodando, em segundos, com o tempo do evento terminar, excluirá-se o tempo em que a animação esteve em pausa.Para um "animationstart" evento, elapsedTime é 0.0 a não ser que haja um valor negativo para animation-delay, nesse caso o evento irá terminar com elapsedTime contendo (-1 * delay).
+
+ +

Especificações

+ +

Esse método é não-padrão e não é parte de qualquer especificação, no entanto ele esteve presente nos primeiros rascunhos de {{SpecName("CSS3 Animations")}}.

+ +

Compatibilidade com os Navegadores

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}
+ Removed in {{ CompatGeckoDesktop("23.0") }}
10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ +

 

+ +

 

+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{ CompatGeckoMobile("6.0") }}
+ Removed in {{ CompatGeckoMobile("23.0") }}
10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/animationevent/pseudoelement/index.html b/files/pt-br/web/api/animationevent/pseudoelement/index.html new file mode 100644 index 0000000000..0e68a22532 --- /dev/null +++ b/files/pt-br/web/api/animationevent/pseudoelement/index.html @@ -0,0 +1,102 @@ +--- +title: AnimationEvent.pseudoElement +slug: Web/API/AnimationEvent/pseudoElement +tags: + - AnimationEvent + - Animação Web + - Apps + - CSSOM + - Propriedade + - Referencia +translation_of: Web/API/AnimationEvent/pseudoElement +--- +

{{SeeCompatTable}}{{ apiref("Web Animations API") }}

+ +

Sumário

+ +

AnimationEvent.pseudoElement é uma propriedade só de leitura do {{domxref("DOMString")}}, começando com '::', contendo o nome do pseudo-element em que a animação roda. Se a animação não roda em um pseudo-elemento mas em um elemento, então temos uma string vazia : ''.

+ +

Síntaxe

+ +
name = AnimationEvent.pseudoElement
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{ SpecName('CSS3 Animations', '#AnimationEvent-pseudoElement', 'AnimationEvent.pseudoElement') }}{{ Spec2('CSS3 Animations')}}Initial definition.
+ +

Compatibilidade com os Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{ CompatGeckoDesktop("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+

 

+ +

 

+ + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/api_de_desempenho/index.html b/files/pt-br/web/api/api_de_desempenho/index.html new file mode 100644 index 0000000000..1b6997e293 --- /dev/null +++ b/files/pt-br/web/api/api_de_desempenho/index.html @@ -0,0 +1,138 @@ +--- +title: API de Desempenho +slug: Web/API/API_de_Desempenho +translation_of: Web/API/Performance_API +--- +
{{DefaultAPISidebar("High Resolution Time")}}
+ +

The High Resolution Time standard defines a {{domxref("Performance")}} interface that supports client-side latency measurements within applications. The {{domxref("Performance")}} interfaces are considered high resolution because they are accurate to a thousandth of a millisecond (subject to hardware or software constraints). The interfaces support a number of use cases including calculating frame-rates (potentially important in animations) and benchmarking (such as the time to load a resource).

+ +

Since a platform's system clock is subject to various skews (such as NTP adjustments), the interfaces support a monotonic clock i.e. a clock that is always increasing. As such, the Performance API defines a {{domxref("DOMHighResTimeStamp")}} type rather than using the {{jsxref("Date.now","Date.now()")}} interface.

+ +

DOMHighResTimeStamp

+ +

The {{domxref("DOMHighResTimeStamp")}} type, as its name implies, represents a high resolution point in time. This type is a double and is used by the performance interfaces. The value could be a discrete point in time or the difference in time between two discrete points in time.

+ +

The unit of DOMHighResTimeStamp is milliseconds and should be accurate to 5 µs (microseconds). However, If the browser is unable to provide a time value accurate to 5 microseconds (because, for example, due to hardware or software constraints), the browser can represent the value as a time in milliseconds accurate to a millisecond.

+ +

Methods

+ +

The {{domxref("Performance")}} interface has two methods. The {{domxref("Performance.now","now()")}} method returns a {{domxref("DOMHighResTimeStamp")}} whose value that depends on the {{domxref("PerformanceTiming.navigationStart","navigation start")}} and scope. If the scope is a window, the value is the time the browser context was created and if the scope is a {{domxref("Worker","worker")}}, the value is the time the worker was created.

+ +

The {{domxref("Performance.toJSON","toJSON()")}} method returns a serialization of the {{domxref("Performance")}} object, for those attributes that can be serialized.

+ +

Properties

+ +

The {{domxref("Performance")}} interface has two properties. The {{domxref("Performance.timing","timing")}} property returns a {{domxref("PerformanceTiming")}} object containing latency-related performance information such as the start of navigation time, start and end times for redirects, start and end times for responses, etc.

+ +

The {{domxref("Performance.navigation","navigation")}} property returns a {{domxref("PerformanceNavigation")}} object representing the type of navigation that occurs in the given browsing context, such as the page was navigated to from history, the page was navigated to by following a link, etc.

+ +

Interfaces

+ +
+
{{domxref('Performance')}}
+
Provides methods and properties containing timing-related performance information for the given page.
+
{{domxref('PerformanceEntry')}}
+
Provides methods and properties the encapsulate a single performance metric that is part of the performance timeline.
+
{{domxref('PerformanceFrameTiming')}}
+
Provides methods and properties containing frame timing data about the browser's event loop.
+
{{domxref('PerformanceMark')}}
+
An abstract interface for performance entries with an entry type of "mark". Entries of this type are created by calling performance.mark() to add a named DOMHighResTimeStamp (the mark) to the browser's performance timeline.
+
{{domxref('PerformanceMeasure')}}
+
An abstract interface for performance entries with an entry type of "measure". Entries of this type are created by calling performance.measure() to add a namedDOMHighResTimeStamp (the measure) between two marks to the browser's performance timeline.
+
{{domxref('PerformanceNavigationTiming')}}
+
Provides methods and properties to store and retrieve high resolution timestamps or metrics regarding the browser's document navigation events.
+
{{domxref('PerformanceObserver')}}
+
Provides methods and properties used to observe performance measurement events and be notified of new performance entries as they are recorded in the browser's performance timeline.
+
{{domxref('PerformanceResourceTiming')}}
+
Provides methods and properties for retrieving and analyzing detailed network timing data regarding the loading of an application's resources.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time')}}{{Spec2('Highres Time')}}Initial definition.
{{SpecName('Highres Time Level 2')}}{{Spec2('Highres Time Level 2')}}Adds performance attribute on Window and WorkerGlobalScope.
{{SpecName('Highres Time Level 3')}}{{Spec2('Highres Time Level 3')}}Add timeOrigin property to Performance interface.
{{SpecName('Frame Timing')}}{{Spec2('Frame Timing')}}Adds PerformanceFrameTiming interface.
{{SpecName('Navigation Timing')}}{{Spec2('Navigation Timing')}}Adds the PerformanceTiming and PerformanceNavigation interfaces. Adds timing and navigation properties to the Performance interface.
{{SpecName('Navigation Timing Level 2')}}{{Spec2('Navigation Timing Level 2')}}Adds the PerformanceNavigationTiming interface. Obsolete's the the PerformanceTiming interface, the PerformanceNavigation interface, as well as the timing and navigation properties to the Performance interface.
{{SpecName('Performance Timeline')}}{{Spec2('Performance Timeline')}}Adds the PerformanceEntry interface, the PerformanceEntryList type, as well as the getEntries(), getEntriesByType(), and getEntriesByName() methods on the Performance interface.
{{SpecName('Performance Timeline Level 2')}}{{Spec2('Performance Timeline Level 2')}}Adds serializer to the PerformanceEntry interface as well as adding the PerformanceObserver interface and callback
{{SpecName('Resource Timing')}}{{Spec2('Resource Timing')}}Adds the PerformanceResourceTiming interface. Adds the clearResourceTimings() method, the setResourceTimingBufferSize() method, and the onresourcetimingbufferfull event handler to the Performance interface. Also adds the Timing-Allow-Origin response header.
{{SpecName('Resource Timing 2')}}{{Spec2('Resource Timing 2')}}Adds the nextHopProtocol, workerStart, transferSize, encodedBodySize, and decodedBodySize properties to the PerformanceResourceTiming interface.
{{SpecName('Resource Timing 3')}}{{Spec2('Resource Timing 3')}}
{{SpecName('User Timing')}}{{Spec2('User Timing')}}Adds mark(), clearMarks(), measure() and clearMeasures() methods to the Performance interface. Adds the PerformanceMark and PeformanceMeasure interfaces.
{{SpecName('User Timing Level 2')}}{{Spec2('User Timing Level 2')}}
+ +

Implementation status

+ +

As shown in the {{domxref("Performance")}} interface's Browser Compatibility table, most of these interfaces are broadly implemented by desktop browsers.

+ +

To test your browser's support for the {{domxref("Performance")}} interface, run the perf-api-support application.

+ +

See Also

+ + diff --git a/files/pt-br/web/api/api_push/best_practices/index.html b/files/pt-br/web/api/api_push/best_practices/index.html new file mode 100644 index 0000000000..9b0fafd2b7 --- /dev/null +++ b/files/pt-br/web/api/api_push/best_practices/index.html @@ -0,0 +1,73 @@ +--- +title: Melhores práticas +slug: Web/API/API_Push/Best_Practices +tags: + - Apps + - Iniciante + - Melhores Práticas + - Notificações + - Push API + - Usabilidade +translation_of: Web/API/Push_API/Best_Practices +--- +

{{draft}}

+ +

Este artigo proporciona um compilado das melhores práticas a serem usadas enquanto estiver desenvolvendo websites e aplicações que usem Notificações push para engajamento de usuários.

+ +
+

“Se feito de uma maneira correta, as notificações ajudam os usuarios, se não, so irritam.” — Conversa entre dois desenvolvedores a respeito da etica das notificações push.

+
+ +

Visão Geral do web push notifications

+ +

Notificações Web Push (criadas usando uma combinação das APIs de Notificações, Push e Service Worker) são parte de um movimento crescente em que desenvolvedores e comerciantes estão usando para conseguir atenção para seus sites. Uma procura rápida pelo termo "web push notifications", irá resultar em vários artigos, em que especialistas em marketing que acreditam que deve-se usar a API de Push para recapturar a atenção de pessoas que saíram de seu site para que possam terminar o que estavam fazendo, por exemplo, uma compra, ou então enviar as últimas notícias e até recomendação de produtos

+ +

O Lado obscuro

+ +

Essa novidade oferece uma oportunidade nova e inexplorada para sites empresariais chegarem aos seus consumidores finais. Seu usuário trocou de aba para responder um email? Consiga-os de volta com uma oferta que expira em um tempo limitado ou oferecendo frete grátis, o qual ele não vai poder ignorar

+ +

Mas sério, qual o melhor uso das notificações push? Ou é apenas uma nova interação dos bons e velhos pop-ups?

+ +
+

O envio de notificações push não corre o risco de acabar na pasta de spam. Nem pode ser bloqueado por bloqueadores de anúncios. Ele aparece na sua área de trabalho, mesmo quando o site está fechado. No celular, ele aparece na barra de notificações, assim como as notificações por push do aplicativo, mesmo quando o navegador não está em execução.” — um site de marketing anonimo

+
+ +

Bons usos das notificações

+ +

Mas há também um lado bom no que se diz respeito as notificações por push. Digamos que você e sua equipe usem normalmente um programa de bate-papo para se comunicar, mas hoje você está feliz e saltitante trabalhando e surge um problema. Digamos que seu gerente tenha encontrado um problema nas aprovações e queira receber seu feedback sobre algo antes que ela prossiga.

+ +

Neste documento, falaremos sobre o uso correto das notificações por push da web. Às vezes, eles podem eliminar a frustração e o aborrecimento e, às vezes, causá-los. Cabe a você, como desenvolvedor, fazer recomendações (e decisões) sábias sobre o uso de notificações por push.

+ +

O que se espera alcançar com as notificações push?

+ +

Como tudo, com grande poder vem uma grande responsabilidade. Toda notificação push devem ser úteis e sensíveis ao tempo, o usuário sempre deve fornecer a permissão antes de recebe-la primeiro e deve-se oferecer uma maneira fácil de optar por não receber mais no futuro.

+ +

Temos que responder algumas perguntas basicas para verificar se as notificações são necessarias:

+ + + +

Além da questão de saber se uma notificação por push é necessária, existem muitas variedades de notificações por push, variando de casual e efêmera a persistente e exigente.

+ +

Aconselhamos que você use as notificações que exigem uma interação de forma conciente e com moderação, pois estas podem irritar seu usuario e afasta-lo. Suas notificações devem ser acolhedoras, não hostis.

+ +

Gerando confiança

+ +

Alguns estudos mostraram que até 60% das notificações por push não chegam ao usuário final. Permitir que seu usuario receba notificações por push em tempo real exige confiança, por parte do aplicativo. Você pode criar confiança ao ter um site bem projetado que forneça um bom conteúdo e que mostre respeito pelo usuário alem de um valor claro para que o usuario aceite as notificações push.

+ +

Mitigações dos navegadores

+ +

Por causa dos abusos da utilização das notificações por push no passado, os desenvolvedores de navegadores começaram a implementar estratégias para ajudar a mitigar esse problema. Por exemplo, o Safari 12.1 agora exige - e outros navegadores já o fazem ou estão planejando[1] fazer—que o usuário interaja com a página de alguma forma antes que ela possa solicitar permissão para executar notificações por push, assim como já acontece com os popups. Isso pelo menos impede que o usuário receba espontaneamente essa pergunta em páginas da Web que apenas olharam de uma só vez, raramente ou nunca mais.

+ +

[1] No caso do Firefox, veja {{bug(1524619)}}, podemos observar que Firefox 68 implementa isso, desabilitado por padrão, usando a preferência dom.webnotifications.requireuserinteraction.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/api_push/index.html b/files/pt-br/web/api/api_push/index.html new file mode 100644 index 0000000000..563b711cd8 --- /dev/null +++ b/files/pt-br/web/api/api_push/index.html @@ -0,0 +1,172 @@ +--- +title: API Push +slug: Web/API/API_Push +tags: + - API + - Experimental + - Notificações + - Push + - Referencia + - Service Workers +translation_of: Web/API/Push_API +--- +
{{DefaultAPISidebar("Push API")}}{{SeeCompatTable}}
+ +

A API Push torna possível que aplicações web recebam mensagens enviadas a elas de um servidor, indepententemente de aplicação estar ou não em primeiro plano, ou até mesmo carregada, em um agente de usuário. Isso permite que desenvolvedores entreguem notificações e atualizações assíncronas a usuários que optarem por elas, resultando num melhor engajamento com conteúdo novo oportuno.

+ +
+

Nota: Esta documentação cobre a especificação W3C da API Push; se você procura pela documentação do sistema de notificação proprietária do mecanismo push, veja Simple Push.

+
+ +

Conceitos e uso de Push

+ +

Para uma aplicação receber mensagens push, ela precisa ter um service worker ativo. Quando o service worker está ativo, ele pode se inscrever para utilizar notificações push {{domxref("PushManager.subscribe()")}}.

+ +

O resultado de {{domxref("PushSubscription")}} inclui toda informação que a aplicação precisa para receber uma mensagem push: um endpoint e a chave encriptada necessária para o envio de dados.

+ +

O service worker será iniciado conforme o necessário para lidar com as mensagens recebidas, que são entregues ao manipulador de evento {{domxref("ServiceWorkerGlobalScope.onpush")}} . Isto permite que a aplicação reaja a cada mensagem recebida, por exemplo para exibir a notificação ao usuário (usando {{domxref("ServiceWorkerRegistration.showNotification()")}}.)

+ +

Cada assinatura é única para um service worker.  O endpoint para a assinatura é uma capability URL única: o conhecimento do endpoint é tudo que é necessário para enviar uma mensagem para sua aplicação. A URL do endpoint precisa ser mantida em segredo, ou outras aplicações estranhas poderão enviar mensagens push para a sua aplicação.

+ +

A ativação de um service worker para entregar mensagens push pode resultar em um aumento de uso de recursos, particularmente de bateria. Diferentes navegadores tem diferentes formas para lidar com isso — atualmente não existe uma forma padrão. Firefox permite um número limitado (cota) de mensagens push para serem enviadas para uma aplicação, embora as mensagens Push que gerem notificações são isentas deste limite.  O limite é atualizado a cada site visitado. Numa comparação, Chrome não aplica nenhum limite, mas requer que cada mensagem push exiba uma notificação.

+ +
+

Nota: A partir do Gecko 44, a cota permitida de mensagens push por aplicação não é incrementada quando uma nova notificação é disparada quando outra está visível, por um período de três segundos. Isso lida com casos em que várias notificações são recebidas ao mesmo tempo, mas nem todas estão visíveis.

+
+ +
+

Nota: Chrome atualmente requer que você crie um projeto no Google Cloud Messaging para enviar mensagens push e use um número do projeto e chave da API para o envio de notificações push. Isto também requer um app manifest com alguns parâmetros especiais para usar o serviço. Essa restrição deverá ser removida no futuro.

+
+ +

Interfaces

+ +
+
{{domxref("PushEvent")}}
+
Representa uma ação push enviada para o global scope de um {{domxref("ServiceWorker")}}. Ele contém informações enviadas de uma aplicação para um {{domxref("PushSubscription")}}.
+
{{domxref("PushManager")}}
+
Fornece uma forma de receber notificações de servidor third-party bem como solicitar URL para notificações push. Essa interface substitui a funcionalidade oferecida que está obsoleta {{domxref("PushRegistrationManager")}} interface.
+
{{domxref("PushMessageData")}}
+
Fornece acesso aos dados push enviados por um servidor, e inclui métodos para manipular os dados recebidos.
+
{{domxref("PushSubscription")}}
+
Fornece a URL de assinatura do endpoint e permite o cancelamento da assinatura de um serviço push.
+
+ +

Service worker additions

+ +

As seguintes informações adicionais para a Service Worker API foram especificadas na Push API spec, para fornecer um ponto de entrada para usar mensagens Push, e para monitorar e responder os eventos de envio e assinatura.

+ +
+
{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}
+
Retorna uma referência para a interface {{domxref("PushManager")}} para administrar assinaturas push incluindo subscrever, obter uma assinatura ativa e acessar o status de permissão de envio. Este é o ponto de entrada para usar mensagens Push.
+
{{domxref("ServiceWorkerGlobalScope.onpush")}}
+
Um manipulador de eventos disparado sempre que um evento  {{Event("push")}} ocorre; isto é, sempre que uma mensagem do servidor de envio for recebida.
+
{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}
+
Um manipulador de eventos disparado sempre que um evento  {{Event("pushsubscriptionchange")}} ocorre; por exemplo, quando uma assinatura push está inválida, ou está prestes a ser invalidada (ex. quando um serviço push service define um tempo de expiração.)
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Push API")}}{{Spec2("Push API")}}Definição Inicial
+ +

Compatibilidade em Browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(42.0)}}{{CompatGeckoDesktop(44.0)}}[1]{{CompatNo}}[2]{{CompatUnknown}}{{CompatUnknown}}
{{domxref("PushEvent.data")}},
+ {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatGeckoDesktop(44.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Suporte básico{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
{{domxref("PushEvent.data")}},
+ {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Atualmente disponível apenas nas versões desktop do Firefox; ainda, mensagens push são encaminhadas apenas quando o Firefox está em execução.

+ +

[2] Ainda não implementado. Veja Microsoft Edge status information.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/api_web_audio/index.html b/files/pt-br/web/api/api_web_audio/index.html new file mode 100644 index 0000000000..8f582eb524 --- /dev/null +++ b/files/pt-br/web/api/api_web_audio/index.html @@ -0,0 +1,480 @@ +--- +title: API Web Áudio +slug: Web/API/API_Web_Audio +tags: + - Web Audio API + - api de áudio + - áudio api + - áudio web +translation_of: Web/API/Web_Audio_API +--- +
+

A API de áudio da web disponibiliza um poderoso e versátil sistema de controle de áudio para a Web, permitindo aos desenvolvedores escolher arquivos de áudio, adicionar efeitos a estes arquivos, criar reprodutores de áudio, aplicar spatial effects (como panning) e muito mais.

+
+ +

Web audio: conceitos e uso

+ +

A API de Web audio envolve manipulação de operações com áudio dentro de um contexto de áudio, e foi desenvolvida para permitir o roteamento modular. Operações básicas de áudio são feitas com audio nodes (nós de áudio), que são ligados para formar gráficos de roteamento de áudio. Várias fontes - com diferentes tipos de layout de canal - são suportados mesmo em um único contexto. Este design modular permite flexibilidade para criar funções de áudio complexas com efeitos dinâmicos.

+ +

Audio nodes são ligados pelas suas entradas e saídas, formando uma cadeia que começa com uma ou mais fontes, passa por um ou mais nodes e então acaba em um destino (embora você não tenha que fornecer um destino, por exemplo, se você quiser apenas visualizar alguns dados de áudio). Um fluxo de trabalho simples, com Web áudio, seria algo parecido com isso:

+ +
    +
  1. Crie um contexto de áudio
  2. +
  3. Dentro do contexto, crie fontes de áudio — como <audio>, oscilador, stream
  4. +
  5. Crie efeitos de áudio, como reverb, biquad filter, panner, compressor
  6. +
  7. Escolha o destino final de áudio, por exemplo os auto-falantes de seu sistema
  8. +
  9. Conecte as fontes de áudio com os efeitos, e os efeitos com o destino.
  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.

+ +

O sincronismo é controlado com alta precisão e baixa latência, permitindo aos desenvolvedores escrever códigos que respondam com precisão a eventos e capazes de gerar exemplos específicos, mesmo com uma alta taxa de amostragem. Dessa forma, aplicações como baterias eletrônicas e seqüenciadores estarão facilmente ao alcance dos desenvolvedores.

+ +

A API de Web Audio também permite o controle de como o áudio será ordenado. Usando um sistema baseado em um modelo de source-listener, a API permite controlar os painéis de modelo para serem usados e tratados com atenuação de distância induzida ou doppler shift induzido por uma fonte em movimento (ou um ouvinte em movimento).

+ +
+

Nota: Você pode ver mais detalhes sobre a teoria da API de Web Audio em nosso artigo Basic concepts behind Web Audio API.

+
+ +

Web Audio: Interfaces da API

+ +

A API de Web Audio possui um total de 28 interfaces e eventos associados, que nós dividimos e categorizamos em 9 funcionalidades.

+ +

Definições gerais de grafos de áudio (audio graph)

+ +

Definições gerais que moldam os grafos de áudio no uso da API de Web Audio.

+ +
+
{{domxref("AudioContext")}}
+
A interface AudioContext representa um grafo de processamento de áudio construído a partir de módulos de áudio ligados entre si, cada um representado por um {{domxref("AudioNode")}}. Um contexto de áudio (audio context) controla a criação dosnós que ele contém e a execução do processamento de áudio, ou a decodificação. Como tudo acontece dentro de um contexto, você deve criar um AudioContext antes de fazer qualquer outra coisa.
+
{{domxref("AudioNode")}}
+
A interface AudioNode representa um módulo de processamento de áudio como uma fonte de áudio (por exemplo, um HTML {{HTMLElement("áudio")}} ou um elemento {{HTMLElement("vídeo")}}), destino de áudio, módulo de processamento intermediário (por exemplo, um filtro como {{domxref("BiquadFilterNode")}}, ou controle de volume, como {{domxref("GainNode")}}).
+
{{domxref("AudioParam")}}
+
A interface AudioParam representa um parâmetro relacionado ao áudio, como um parâmetro de um {{domxref("AudioNode")}}. Ele pode ser configurado com um valor específico ou uma mudança de valor, e pode ser programado para "acontecer" em um momento específico e seguindo um padrão específico.
+
{{event("ended_(Web_Audio)", "ended")}} (event)
+
O evento ended é disparado quando a reprodução parou porque o fim da mídia foi atingido.
+
+ +

Definindo fontes de áudio

+ +

Interfaces que definem fontes de áudio para uso na API de Web Audio.

+ +
+
{{domxref("OscillatorNode")}}
+
A interface OscillatorNode representa uma onda senoidal. Esta interface é um módulo de processamento de áudio que gera uma onda senoidal com determinada frequência.
+
{{domxref("AudioBuffer")}}
+
A interface AudioBuffer representa uma pequena porção de áudio armazenada na memória, criada a partir de um arquivo de áudio usando o método {{ domxref("AudioContext.decodeAudioData()") }}, ou criado com os dados brutos usando o método {{ domxref("AudioContext.createBuffer()") }}. Uma vez decodificado neste formato o áudio pode ser colocada em um {{ domxref("AudioBufferSourceNode") }}.
+
{{domxref("AudioBufferSourceNode")}}
+
A interface AudioBufferSourceNode representa uma fonte de áudio que consiste em dados de áudio na memória, armazenados em um {{domxref ("AudioBuffer")}}. É um {{domxref ("AudioNode")}} que atua como uma fonte de áudio.
+
{{domxref("MediaElementAudioSourceNode")}}
+
A interface MediaElementAudioSourceNode  representa uma fonte de audio consiste de um HTML5 {{ htmlelement("audio") }} ou {{ htmlelement("video") }} elemento. É uma {{domxref("AudioNode")}} que atua como uma fonte de áudio.
+
{{domxref("MediaStreamAudioSourceNode")}}
+
The MediaStreamAudioSourceNode interface represents an audio source consisting of a WebRTC {{domxref("MediaStream")}} (such as a webcam or microphone.) It is an {{domxref("AudioNode")}} that acts as an audio source.
+
+ +

Definindo filtros de efeitos de áudio

+ +

Interfaces para definição de efeitos que você deseja aplicar em suas fontes de áudio.

+ +
+
{{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 AudioBuffer, 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("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")}}
+
Used to define a periodic waveform that can be used to shape the output of an {{ domxref("OscillatorNode") }}.
+
+ +

Definindo destinos de áudio

+ +

Uma vez que você tenha feito o processamento do seu áudio, estas interfaces definirão aonde será a saída do áudio.

+ +
+
{{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 MediaElementAudioSourceNode 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 MediaStream obtained from {{ domxref("Navigator.getUserMedia") }}. It is an {{domxref("AudioNode")}} that acts as an audio destination.
+
+ +

Análise dos dados e visualização

+ +

Se você deseja extrair tempo, frequencia e outras informações do seu áudio, o AnalyserNode é o que você necessita.

+ +
+
{{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.
+
+ +

Dividindo e mesclando canais de áudio

+ +

Para dividir e mesclar canais de áudio, você utilizará essas 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 outputs. 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.
+
+ +

Processamento de áudio por JavaScript

+ +

Se você quiser usar um script externo para processar sua fonte de áudio, Node e eventos abaixo tornarão isto possível.

+ +
+
{{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.
+
+ +

Áudio offline

+ +

Manipular áudio offline é possível com estas interfaces.

+ +
+
{{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.
+
+ +

Interfaces obsoletas

+ +

As interfaces a seguir foram definidas em versões antigas das especificações da API de Web Audio, mas agora elas estão obsoletas e serão substituidas por outras 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

+ +

Este exemplo mostra uma grande variedade de funções da API de Web Audio que podem ser utilizadas. Você pode ver este código em ação na demo Voice-change-o-matic (também verificar o código-fonte completo no Github) - esta é uma demonstração de um modificador de voz de brinquedo experimental; aconselhamos manter seus alto-falantes baixo ao utilizá-lo, pelo menos para começar!

+ +

As linhas API de Web Audio estão destacadas; se você quiser encontrar mais informações sobre os diferentes métodos, faça uma busca através das páginas de referência.

+ +
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

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Audio API')}}{{Spec2('Web Audio API')}} 
+ +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}23{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}251.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
+
+ +

 

+ +

Veja também

+ + + + diff --git a/files/pt-br/web/api/api_web_audio/sintetizador_simples/index.html b/files/pt-br/web/api/api_web_audio/sintetizador_simples/index.html new file mode 100644 index 0000000000..b0fdf2a0c4 --- /dev/null +++ b/files/pt-br/web/api/api_web_audio/sintetizador_simples/index.html @@ -0,0 +1,579 @@ +--- +title: 'Tutorial e exemplo: Teclado de Sintetizador Simples' +slug: Web/API/API_Web_Audio/Sintetizador_simples +tags: + - Audio + - Exemplo + - Guía + - Media + - Oscilador + - Piano + - Sintetizador + - Tutorial + - Web Audio API +translation_of: Web/API/Web_Audio_API/Simple_synth +--- +
{{DefaultAPISidebar("Web Audio API")}}
+ +

Este artigo apresenta o código e uma demonstração funcional de um teclado que você pode tocar usando seu mouse. O teclado lhe permite alternar entre formas de onda padrões e customizadas. Esse exemplo utiliza das seguintes interfaces de Web API: {{domxref("AudioContext")}}, {{domxref("OscillatorNode")}}, {{domxref("PeriodicWave")}}, e {{domxref("GainNode")}}.

+ +

Já que {{domxref("OscillatorNode")}} é baseado no {{domxref("AudioScheduledSourceNode")}}, isso até certo ponto também é um exemplo pra isto.

+ +

O Teclado Visual

+ +

HTML

+ +

Existem três componentes primários para o display do nosso teclado virtual. O primeito do qual é o teclado musical em si. Nós extraimos em um par de elementos {{HTMLElement("div")}} aninhados para permitir a rolagem horizontal caso as teclas não encaixem na tela.

+ +

O Teclado

+ +

Primeiro, criamos o espaço no qual construiremos o teclado. Estaremos construindo o teclado programaticamente, considerando que ao fazer desse jeito teremos a flexibilidade de configurar cada tecla conforme determinamos as informações apropriadas para tecla correspondente. No nosso caso, pegamos a frequência de cada tecla através de uma tabela, mas poderia ser calculado de forma algoritmica também.

+ +
<div class="container">
+  <div class="keyboard"></div>
+</div>
+
+ +

O {{HTMLElement("div")}} nomeado de "container" é a barra de rolagem que permite o teclado ser rolado horizontalmente se for largo demais para o espaço disponivel. As teclas em si serão inseridas no bloco de classe "keyboard".

+ +

A barra de opções

+ +

Abaixo do teclado, colocaremos alguns controles para configurar o camada. Por enquanto, teremos dois controles: Um para controlar o volume e outro para selecionar a forma de onda periodica usada ao gerar as notas.

+ +
O controle de volume
+ +

Primeiro criamos o <div> para conter a barra de opções, para ser personalizado conforme preciso. Então estabelecemos uma caixa que será apresentada no lado esquerdo da barra e colocar um rotulo e um elemento {{HTMLElement("input")}} do tipo "range". O elemento range será tipicamente apresentado como o controle da barra de rolagem ; configuramos ele para permitir qualquer valor entre 0.0 e 1.0 em cada posição.

+ +
<div class="settingsBar">
+  <div class="left">
+    <span>Volume: </span>
+    <input type="range" min="0.0" max="1.0" step="0.01"
+        value="0.5" list="volumes" name="volume">
+    <datalist id="volumes">
+      <option value="0.0" label="Mute">
+      <option value="1.0" label="100%">
+    </datalist>
+  </div>
+
+ +

Especificamos um valor padrão de 0.5, e provemos um elemento {{HTMLElement("datalist")}} no qual é conectado ao range usando o atributo {{htmlattrxref("name")}} para achar uma lista de opções cujo ID encaixa; nesse caso, o conjunto de informações é nomeado de "volume". isso nos permite prover um conjunto de valores comuns e strings especiais que o browser pode de forma opcional escolher mostrar de alguma maneira; e então atribuimos nomes aos valores 0.0 ("Mute") e 1.0 ("100%").

+ +
A seleção de forma de onda
+ +

E no lado da barra de configurações, colocamos um rótulo e um elemento {{HTMLElement("select")}} nomeado de "waveform" cujas opções correspondem as formas de onda disponiveis.

+ +
  <div class="right">
+    <span>Current waveform: </span>
+    <select name="waveform">
+      <option value="sine">Sine</option>
+      <option value="square" selected>Square</option>
+      <option value="sawtooth">Sawtooth</option>
+      <option value="triangle">Triangle</option>
+      <option value="custom">Custom</option>
+    </select>
+  </div>
+</div>
+ + + +

JavaScript

+ +

O código em JavaScript começa inicializando algumas váriaveis.

+ +
let audioContext = new (window.AudioContext || window.webkitAudioContext)();
+let oscList = [];
+let masterGainNode = null;
+
+ +
    +
  1. audioContext é colocado para referenciar o objeto global {{domxref("AudioContext")}} (ou webkitAudioContext se  necessário).
  2. +
  3. oscillators está colocado para conter uma lista de todos os osciladores atualmente tocando. Ele começa nulo, afinal não há nenhum oscilador tocando ainda.
  4. +
  5. masterGainNode é colocado como nulo; durante o processo de setup, ele será configurado para contar um {{domxref("GainNode")}} no quall todos os osciladores irão se conectar para permitir o volume geral a ser controlado por apenas uma barra de rolagem.
  6. +
+ +
let keyboard = document.querySelector(".keyboard");
+let wavePicker = document.querySelector("select[name='waveform']");
+let volumeControl = document.querySelector("input[name='volume']");
+
+ +

Referencias aos elementos que precisaremos acessar são obtidas através dp:

+ + + +
let noteFreq = null;
+let customWaveform = null;
+let sineTerms = null;
+let cosineTerms = null;
+
+ +

Enfim, variaveis globais que serão usadas quando as formas de onda são criadas:

+ + + +

Criando a tabela de notas

+ +

A função createNoteTable() constrói a matriz noteFreq para conter uma matriz de objetos representando cada oitava. Cada oitava, possui uma propriedade para cada nota nessa oitava; O nome dessa propriedade é o nome da nota (utilizando da notação em inglês, como "C" para representar "dó"), e o valor é a frequência, em Hertz, daquela nota.

+ +
function createNoteTable() {
+  let noteFreq = [];
+  for (let i=0; i< 9; i++) {
+    noteFreq[i] = [];
+  }
+
+  noteFreq[0]["A"] = 27.500000000000000;
+  noteFreq[0]["A#"] = 29.135235094880619;
+  noteFreq[0]["B"] = 30.867706328507756;
+
+  noteFreq[1]["C"] = 32.703195662574829;
+  noteFreq[1]["C#"] = 34.647828872109012;
+  noteFreq[1]["D"] = 36.708095989675945;
+  noteFreq[1]["D#"] = 38.890872965260113;
+  noteFreq[1]["E"] = 41.203444614108741;
+  noteFreq[1]["F"] = 43.653528929125485;
+  noteFreq[1]["F#"] = 46.249302838954299;
+  noteFreq[1]["G"] = 48.999429497718661;
+  noteFreq[1]["G#"] = 51.913087197493142;
+  noteFreq[1]["A"] = 55.000000000000000;
+  noteFreq[1]["A#"] = 58.270470189761239;
+  noteFreq[1]["B"] = 61.735412657015513;
+
+ +

... várias oitavas não mostradas para manter breve ...

+ + + +
  noteFreq[7]["C"] = 2093.004522404789077;
+  noteFreq[7]["C#"] = 2217.461047814976769;
+  noteFreq[7]["D"] = 2349.318143339260482;
+  noteFreq[7]["D#"] = 2489.015869776647285;
+  noteFreq[7]["E"] = 2637.020455302959437;
+  noteFreq[7]["F"] = 2793.825851464031075;
+  noteFreq[7]["F#"] = 2959.955381693075191;
+  noteFreq[7]["G"] = 3135.963487853994352;
+  noteFreq[7]["G#"] = 3322.437580639561108;
+  noteFreq[7]["A"] = 3520.000000000000000;
+  noteFreq[7]["A#"] = 3729.310092144719331;
+  noteFreq[7]["B"] = 3951.066410048992894;
+
+  noteFreq[8]["C"] = 4186.009044809578154;
+  return noteFreq;
+}
+
+ +

O resultado é uma matriz, noteFreq, com um objeto para cada oitava. Cada objeto de oitava tem propriedades nomeadas nela onde a propriedade é o nome da nota com a notação em inglês (Como "C" para representar "dó") e o valor da propriedade é a frequência da nota em Hertz.. o objeto resultando se parece com isso:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OctaveNotes
0"A" ⇒ 27.5"A#" ⇒ 29.14"B" ⇒ 30.87
1"C" ⇒ 32.70"C#" ⇒ 34.65"D" ⇒ 36.71"D#" ⇒ 38.89"E" ⇒ 41.20"F" ⇒ 43.65"F#" ⇒ 46.25"G" ⇒ 49"G#" ⇒ 51.9"A" ⇒ 55"A#" ⇒ 58.27"B" ⇒ 61.74
2. . .
+ +

Com esta tabela no lugar, podemos descobrir a frequência para uma dada nota em uma oitava particular relativamente fácil. Se queremos a frequência pra nota G# na primeira oitava, nós simplesmente usamos  noteFreq[1]["G#"] e conseguimos o valor 51.9 como resultado.

+ +
+

Os valores na tabela de exemplo acima foram arredondados para duas casas decimais.

+
+ + + +

Construindo o teclado

+ +

A função setup() é responsavel por construir o teclado e preparar a aplicação para tocar a música.

+ +
function setup() {
+  noteFreq = createNoteTable();
+
+  volumeControl.addEventListener("change", changeVolume, false);
+
+  masterGainNode = audioContext.createGain();
+  masterGainNode.connect(audioContext.destination);
+  masterGainNode.gain.value = volumeControl.value;
+
+  // Create the keys; skip any that are sharp or flat; for
+  // our purposes we don't need them. Each octave is inserted
+  // into a <div> of class "octave".
+
+  noteFreq.forEach(function(keys, idx) {
+    let keyList = Object.entries(keys);
+    let octaveElem = document.createElement("div");
+    octaveElem.className = "octave";
+
+    keyList.forEach(function(key) {
+      if (key[0].length == 1) {
+        octaveElem.appendChild(createKey(key[0], idx, key[1]));
+      }
+    });
+
+    keyboard.appendChild(octaveElem);
+  });
+
+  document.querySelector("div[data-note='B'][data-octave='5']").scrollIntoView(false);
+
+  sineTerms = new Float32Array([0, 0, 1, 0, 1]);
+  cosineTerms = new Float32Array(sineTerms.length);
+  customWaveform = audioContext.createPeriodicWave(cosineTerms, sineTerms);
+
+  for (i=0; i<9; i++) {
+      oscList[i] = {};
+  }
+}
+
+setup();
+ +
    +
  1. A tabela que mapeia o nome e oitavas das notas para suas respectivas frequências é criado ao chamar createNoteTable().
  2. +
  3. Um manipulador de eventos é estabelecido ao chamar nosso velho amigo {{domxref("EventTarget.addEventListener", "addEventListener()")}} para cuidar dos eventos do {{event("change")}} no controle de ganho geral. Isso vai simplesmente atualizar o módulo de ganho de volume para o novo valor.
  4. +
  5. Em seguida, nós replicamos cada oitava na tabela de frequências das notas. Para cada oitava, usamos {{jsxref("Object.entries()")}} para conseguir uma lista de notas daquela oitava.
  6. +
  7. Criar um {{HTMLElement("div")}} para contar as notas daquela oitava (para ter um pouco de espaço entre as oitavas), e mudar o nome de classe para "octave".
  8. +
  9. Para cada tecla na oitava, checamos para ver se o nome daquela nota há mais de um caractere. Nós pulamos essas, pois estamos deixando notas sustenidas de fora deste exemplo. Do contrário, chamamos createKey(), especificando uma string, oitava, e frequência. O elemento retornado é anexado na elemento da oitava criada no passo 4.
  10. +
  11. Quando o elemento da oitava é construido, é então anexada ao teclado.
  12. +
  13. Uma vez que o teclado foi construido, nós rolamos para nota "B" na quinta oitava; isso tem o efeito de garantir que o C médio é visivel junto das notas ao redor.
  14. +
  15. Então uma forma de onda customizada é construida usando {{domxref("AudioContext.createPeriodicWave()")}}. Essa forma de onda será usada toda vez que o usuário selecionar "Custom" da seleção de formas de onda.
  16. +
  17. Enfim, a lista de osciladores é iniciada para garantir que está pronta para receber informação identificando quais osciladores estão associados com que teclas.
  18. +
+ +

Criando uma tecla

+ +

A função createKey()  é chamada toda vez que queremos que uma tecla seja apresentada no nosso teclado virtual. Ela cria elementos da tecla e seu rótulo, adiciona informação dos atributos ao elemento para uso posterior, e coloca modificadores de eventos para os eventos que nos importam.

+ +
function createKey(note, octave, freq) {
+  let keyElement = document.createElement("div");
+  let labelElement = document.createElement("div");
+
+  keyElement.className = "key";
+  keyElement.dataset["octave"] = octave;
+  keyElement.dataset["note"] = note;
+  keyElement.dataset["frequency"] = freq;
+
+  labelElement.innerHTML = note + "<sub>" + octave + "</sub>";
+  keyElement.appendChild(labelElement);
+
+  keyElement.addEventListener("mousedown", notePressed, false);
+  keyElement.addEventListener("mouseup", noteReleased, false);
+  keyElement.addEventListener("mouseover", notePressed, false);
+  keyElement.addEventListener("mouseleave", noteReleased, false);
+
+  return keyElement;
+}
+
+ +

Após criar  os elementos representando as teclas e seus rótulos, nós configuramos o elemento das teclas ao configurar sua classe para "key" (Que estabelece a aparência). Então adicionamos atributos {{htmlattrxref("data-*")}}  que contém a string da oitava da nota (attribute data-octave), representando a nota a ser tocada (attribute data-note), e frequência (attribute data-frequency) em Hertz. Isso irá nos permitir facilmente pegar informação conforme necessário ao cuidar de eventos.

+ +

Fazendo música

+ +

Tocando um tom

+ +

O trabalho da função playTone() é tocar um tom em uma dada frequência. Isso será usado pelo modificador para eventos acionados nas teclas do teclado, para que toquem as notas apropriadas.

+ +
function playTone(freq) {
+  let osc = audioContext.createOscillator();
+  osc.connect(masterGainNode);
+
+  let type = wavePicker.options[wavePicker.selectedIndex].value;
+
+  if (type == "custom") {
+    osc.setPeriodicWave(customWaveform);
+  } else {
+    osc.type = type;
+  }
+
+  osc.frequency.value = freq;
+  osc.start();
+
+  return osc;
+}
+
+ +

playTone() começa criando um novo {{domxref("OscillatorNode")}} ao chamar o método {{domxref("AudioContext.createOscillator()")}}. Então conectamos ele para o módulo de ganha geral ao chamar o novo método de osciladores {{domxref("OscillatorNode.connect()")}} method;, Que determina ao oscilador onde ele irá mandar seu output. Ao fazer isso, mudar o valor do ganho do módulo de ganho geral irá mudar o volume de todos os toms gerados.

+ +

Então conseguimos o tipo de forma de onda para usar ao checar o valor do controle de seleção de formas de onda na barra de opções. Se o usuário estiver colocado como "custom", chamamos {{domxref("OscillatorNode.setPeriodicWave()")}} para configurar os osciladores para usar nossa forma de onda customizada. Fazer isso automáticamente coloca o {{domxref("OscillatorNode.type", "type")}} do oscilador como custom. Se qualquer outro tipo de forma de onda é selecionado na seleção de formas de ondas, nós simplesmente colocamos os tipos de osciladores no valor da seleção, esse valor será um entre sine, square, triangle, e sawtooth.

+ +

A frequência do oscilador é colocada no valor especificado no paramêtro freq ao colocar o valor dos objetos {{domxref("Oscillator.frequency")}} {{domxref("AudioParam")}} . Então, enfim, o oscilador é iniciado e começa a produzir sons ao chamar o método {{domxref("AudioScheduledSourceNode.start()")}} .

+ +

Tocando um tom

+ +

Quando o evento {{event("mousedown")}} ou {{domxref("mouseover")}} ocorre em uma tecla, queremos que toque a nota correspondente. A função notePressed() é usada como o modificador de eventos para esses eventos.

+ +
function notePressed(event) {
+  if (event.buttons & 1) {
+    let dataset = event.target.dataset;
+
+    if (!dataset["pressed"]) {
+      let octave = +dataset["octave"];
+      oscList[octave][dataset["note"]] = playTone(dataset["frequency"]);
+      dataset["pressed"] = "yes";
+    }
+  }
+}
+
+ +

Começamos checando se o botão esquerdo do mouse é pressionado, por dois motivos. Primeiro, queremos que apenas o botão esquerdo acione as notas. Segundo, e mais importante, estamos usando isso para cuidar do {{event("mouseover")}} para casos onde o usuário arrasta de tecla a tecla, e só queremos tocar uma nota se o mouse estiver pressionado quando entrar no elemento.

+ +

Se o botão do mouse estiver de fato sendo pressionado, recebemos o atributo de tecla pressionada {{htmlattrxref("dataset")}} ; isso torna fácil o acesso das informações de atributo customizadas no elemento. Procuramos por um atributo data-pressed ; caso não haja um(o que indica que a nota não está tocando ainda), chamamos playTone() para começar a tocar a nota, passando no valor dos elementos do atributo data-frequency. O valor retornado do oscilador é guardado no oscList para refêrencia futura, e data-pressed é colocado como yes para indicar que a nota está tocando para que não iniciemos novamente na próxima vez que isso for chamado.

+ +

Parando um tom

+ +

A função noteReleased() é o modificador de eventos chamado quando o usuário solta o botão do mouse ou move o mouse para fora da tecla que ele está tocando.

+ +
function noteReleased(event) {
+  let dataset = event.target.dataset;
+
+  if (dataset && dataset["pressed"]) {
+    let octave = +dataset["octave"];
+    oscList[octave][dataset["note"]].stop();
+    delete oscList[octave][dataset["note"]];
+    delete dataset["pressed"];
+  }
+}
+
+ +

noteReleased() usa os atributos customizados data-octave and data-note  para procurar os osciladores das teclas, e então chama o método de oscilador {{domxref("AudioScheduledSourceNode.stop", "stop()")}} para parar de tocar a nota. Finalmente, a entrada oscList para nota é limpa e o atributo data-pressed é removido do elemento da tecla (como identificado pelo {{domxref("event.target")}}), para indicar que a nota não está tocando no momento.

+ +

Mudando o volume geral

+ +

A barra de rolagem do volume na barra de opções dá uma simples interface para mudar o valor do ganho no módulo de ganho geral, então mudando o volume de todas as notas sendo tocadas. O metódo changeVolume() é o modificador do evento {{event("change")}} na barra de rolagem.

+ +
function changeVolume(event) {
+  masterGainNode.gain.value = volumeControl.value
+}
+
+ +

Isso simplesmente coloca o valor do módulo de ganho geral gain {{domxref("AudioParam")}} para o novo valor na barra de rolagem.

+ +

Resultado

+ +

Coloque tudo junto, o resultado é um simples e funcional teclado virtual que funciona com o clique:

+ +

{{ EmbedLiveSample('The_video_keyboard', 680, 200) }}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/attr/index.html b/files/pt-br/web/api/attr/index.html new file mode 100644 index 0000000000..683dda4847 --- /dev/null +++ b/files/pt-br/web/api/attr/index.html @@ -0,0 +1,132 @@ +--- +title: Attr +slug: Web/API/Attr +tags: + - API + - DOM + - Gecko DOM + - JavaScript +translation_of: Web/API/Attr +--- +

{{APIRef("DOM")}}
+ Este tipo representa um atributo de elemento DOM como um objeto. Na maioria dos métodos DOM, você provavelmente irá retornar diretamente o atributo como uma string (e.g., {{domxref("Element.getAttribute()")}}, mas certas funções (e.g., {{domxref("Element.getAttributeNode()")}}) ou meios de iteração retornam tipos Attr.

+ +

{{InheritanceDiagram}}

+ +
Aviso: Começando no Gecko 7.0 {{geckoRelease("7.0")}}, os que serão removidos mostram mensagens de aviso no console. Você deve revisar seu código de acordo. Veja métodos e propriedades descontinuadas para uma lista completa.
+ +

Propriedades

+ +

 

+ +
+
{{domxref("Attr.name", "name")}} {{readOnlyInline}}
+
O nome do Atributo.
+
+ +

 

+ +

 

+ +
+
{{domxref("Attr.namespaceURI", "namespaceURI")}} {{readOnlyInline}}
+
Uma {{domxref("DOMString")}} representando o namespace URI do atributo, ou null se não há namespace
+
{{domxref("Attr.localName", "localName")}} {{readOnlyInline}}
+
Uma {{domxref("DOMString")}} representando a parte local do nome qualificado do atributo.
+
{{domxref("Attr.prefix", "prefix")}} {{readOnlyInline}}
+
Uma {{domxref("DOMString")}} representando o prefixo do namespace do atributo ou null se nenhum prefixo foi especificado.
+
{{domxref("Attr.ownerElement", "ownerElement")}} {{readOnlyInline}}
+
+

O elemento que possui o atributo.

+
+
+ +

 

+ +
+

Nota: DOM Level 4 removeu esta propriedade. Foi suposto que como você recebe um objeto Attr de um {{domxref("Element")}}, você já deve saber qual é o elemento associado.
+ Como isto não é sempre verdadeiro em casos como objetos Attr sendo retornados pelo {{domxref("Document.evaluate")}}, o DOM Living Standard reintroduziu a propriedade.

+ +

Gecko mostra uma mensagem de descontinuação começando no Gecko 7.0 {{geckoRelease("7.0")}}. Esta mensagem foi removida novamente no Gecko 49.0 {{geckoRelease("49.0")}}.

+
+ +

Propriedades e métodos descontinuados

+ +

As seguintes propriedades e métodos foram descontinuados. Quando disponíveis, são substituidas adequadamente.

+ +
+
attributes
+
Esta propriedade agora sempre retorna NULL.
+
childNodes
+
Esta propriedade agora sempre retorna NULL.
+
firstChild
+
Esta propriedade agora sempre retorna NULL.
+
lastChild
+
Esta propriedade agora sempre retorna NULL.
+
nextSibling
+
Esta propriedade agora sempre retorna NULL.
+
nodeName
+
Use {{domxref("Attr.name")}} no lugar.
+
nodeType
+
Esta propriedade agora sempre retorna 2 (ATTRIBUTE_NODE).
+
nodeValue
+
Use {{domxref("Attr.value")}} no lugar.
+
ownerDocument
+
Provavelmente você nunca utilizou isto, então você não se importa que isso vai desaparecer.
+
ownerElement
+
Desde que você obtenha o objeto Attr de um {{domxref("Element")}}, você já conhece os elementos associados.
+
parentNode
+
Esta propriedade agora sempre retorna NULL.
+
previousSibling
+
Esta propriedade agora sempre retorna NULL.
+
specified
+
Esta propriedade agora sempre retorna true.
+
textContent
+
Use {{domxref("Attr.value")}} no lugar.
+
+ +

Os seguintes métodos foram reprovados:

+ +
+
appendChild()
+
Modifique o valor de {{domxref("Attr.value")}} no lugar.
+
cloneNode()
+
Provavelmente você nunca utilizou isto, então você não se importa que isso vai desaparecer.
+
createAttribute()
+
Use {{domxref("Element.setAttribute()")}} no lugar.
+
createAttributeNS()
+
Use {{domxref("Element.setAttributeNS()")}} no lugar.
+
getAttributeNode()
+
Use {{domxref("Element.getAttribute()")}} no lugar.
+
getAttributeNodeNS()
+
Use {{domxref("Element.getAttributeNS()")}} no lugar.
+
hasAttributes() {{obsolete_inline("21.0")}}
+
Este método agora sempre retorna false.
+
hasChildNodes()
+
Este método agora sempre retorna false.
+
insertBefore()
+
Modifique o valor de  {{domxref("Attr.value")}} no lugar.
+
isSupported()
+
Provavelmente você nunca utilizou isto, então você não se importa que isso vai desaparecer.
+
isEqualNode()
+
Provavelmente você nunca utilizou isto, então você não se importa que isso vai desaparecer.
+
normalize()
+
Provavelmente você nunca utilizou isto, então você não se importa que isso vai desaparecer.
+
removeAttributeNode()
+
Use {{domxref("Element.removeAttribute()")}} no lugar.
+
removeChild()
+
Modifique o valor de {{domxref("Attr.value")}} no lugar.
+
replaceChild()
+
Modifique o valor de {{domxref("Attr.value")}} no lugar.
+
setAttributeNode()
+
Use {{domxref("Element.setAttribute()")}} no lugar.
+
setAttributeNodeNS()
+
Use {{domxref("Element.setAttributeNS()")}} no lugar.
+
+ +

Especificações

+ + diff --git a/files/pt-br/web/api/attr/localname/index.html b/files/pt-br/web/api/attr/localname/index.html new file mode 100644 index 0000000000..54b7bad202 --- /dev/null +++ b/files/pt-br/web/api/attr/localname/index.html @@ -0,0 +1,133 @@ +--- +title: Attr.localName +slug: Web/API/Attr/localName +tags: + - API + - DOM + - Propriedade + - Referencia +translation_of: Web/API/Attr/localName +--- +
{{APIRef("DOM")}}
+ +

A propriedade read-only Attr.localName retorna a parte do local de um nome qualificado de elemento.

+ +
+

Antes do DOM4 essa API foi definida dentro da interface {{domxref("Node")}}.

+
+ +

Sintaxe

+ +
name = attribute.localName
+
+ +

Valor de retorno

+ +

Uma {{domxref("DOMString")}} representando a parte local do nome qualificado do atributo.

+ +

Exemplo

+ +

O seguinte exemplo mostra "id" em um diálogo de alerta.

+ +

Conteúdo HTML

+ +
<button id="example">Click me</button>
+ +

Conteúdo JavaScript

+ +
const element = document.querySelector("#example");
+element.addEventListener("click", function() {
+  const attribute = element.attributes[0];
+  alert(attribute.localName);
+});
+
+ +

{{ EmbedLiveSample('Example','100%',30) }}

+ +

Notas

+ +

O nome local de um atributo é a parte do nome qualificado do atributo the vem depois da vírgula. Nome qualificados são tipicamente utilizados em XML como parte do namespace(s) de um documento XML em particular.

+ +
+

Nota: No {{Gecko("1.9.2")}} e anteriores, a propriedade retorna uma versão em letras maiúsculas do nome local para o atributo DOM do HTML (oposto a atributos XHTML no DOM do XML). Em versões posteriores, em conformidade com o HTML5, a propriedade retorna no caso de armazenamento interno do DOM, que é em letras minúsculas para ambos os atributos HTML no DOM do HTML  e XHTML no DOM do XML.

+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('DOM4', '#interface-attr', 'Attr.localName')}}{{Spec2('DOM4')}}Definição inicial
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico46.0[1]{{CompatGeckoDesktop("48.0")}}[1]{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("48.0")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Essa API foi disponibilizada anteriormente na API {{domxref("Node")}}.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/audiocontext/currenttime/index.html b/files/pt-br/web/api/audiocontext/currenttime/index.html new file mode 100644 index 0000000000..71f3c9c894 --- /dev/null +++ b/files/pt-br/web/api/audiocontext/currenttime/index.html @@ -0,0 +1,114 @@ +--- +title: AudioContext.currentTime +slug: Web/API/AudioContext/currentTime +tags: + - API + - AudioContext + - Propriedade + - Referencia + - Web Audio API + - currentTime +translation_of: Web/API/BaseAudioContext/currentTime +--- +

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

+ +
+

The currentTime read-only property of the {{ domxref("AudioContext") }} interface returns a double representing an ever-increasing hardware timestamp in seconds that can be used for scheduling audio playback, visualizing timelines, etc. It starts at 0.

+
+ +

Syntax

+ +
var audioCtx = new AudioContext();
+console.log(audioCtx.currentTime);
+
+ +

Exemplo:

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+// Older webkit/blink browsers require a prefix
+
+...
+
+console.log(audioCtx.currentTime);
+
+ +

Especificações:

+ + + + + + + + + + + + + + +
Especificações:StatusComentario
{{SpecName('Web Audio API', '#widl-AudioContext-currentTime', 'currentTime')}}{{Spec2('Web Audio API')}} 
+ +

Compatibilidade:

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+ +

 

+
+ +

Veja também:

+ + diff --git a/files/pt-br/web/api/audiocontext/index.html b/files/pt-br/web/api/audiocontext/index.html new file mode 100644 index 0000000000..12357d799c --- /dev/null +++ b/files/pt-br/web/api/audiocontext/index.html @@ -0,0 +1,258 @@ +--- +title: AudioContext +slug: Web/API/AudioContext +tags: + - API + - Audio + - Interface + - Referencia + - Som + - api de áudio +translation_of: Web/API/AudioContext +--- +

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

+ +
+

A interface AudioContext  representa um grafo de processamento de áudio construído a partir de nós de áudio conectados, cada um representado por um {{domxref("AudioNode")}} Um contexto de áudio controla a criação dos nós que contém e a execução do processamento de áudio, ou decodificação. Você precisa criar um AudioContext antes de fazer qualquer outra coisa, pois tudo acontece dentro de um contexto.

+
+ +

Um AudioContextpode ser um alvo de eventos, portanto, ele implementa a interface {{domxref("EventTarget")}}.

+ +

Construtor

+ +
+
{{domxref("AudioContext.AudioContext", "AudioContext()")}}
+
Cria e retorna um novo objeto AudioContext.
+
+ +

Propriedades

+ +
+
{{domxref("AudioContext.currentTime")}} {{readonlyInline}}
+
+

Retorna um double representando um tempo cada vez maior de hardware em segundos usados ​​para agendamento. Começa em 0.

+
+
{{domxref("AudioContext.destination")}} {{readonlyInline}}
+
Retorna um {{domxref("AudioDestinationNode")}} representando o destino final de todo o áudio no contexto. Pode ser pensado como o dispositivo de renderização de áudio.
+
{{domxref("AudioContext.listener")}} {{readonlyInline}}
+
Retorna o objeto  {{domxref("AudioListener")}}, usado para especialização 3D
+
{{domxref("AudioContext.sampleRate")}} {{readonlyInline}}
+
Retorna um float representando a taxa de amostragem (em amostras por segundo) usado por todos os nós neste contexto. A taxa de amostragem de um {{domxref("AudioContext")}} não pode ser alterada.
+
{{domxref("AudioContext.state")}} {{readonlyInline}}
+
Retorna o estado atual do AudioContext.
+
{{domxref("AudioContext.mozAudioChannelType")}} {{ non-standard_inline() }} {{readonlyInline}}
+
Usado para retornar o canal de áudio que o som toca em um {{domxref("AudioContext")}} irá tocar em um dispositivo do Firefox OS.
+
+ +

Manipuladores de eventos

+ +
+
{{domxref("AudioContext.onstatechange")}}
+
Um manipulador de evento que é executado quando um evento do tipo {{event("statechange")}} dispara. +

Isso ocorre quando o estado AudioContext muda, devido ao chamado de um dos métodos de mudança de estado ({{domxref("AudioContext.suspend")}}, {{domxref("AudioContext.resume")}}, or {{domxref("AudioContext.close")}}).

+
+
+ +

Métodos

+ +

Também implementa métodos a partir da interface {{domxref("EventTarget")}}.

+ +
+
{{domxref("AudioContext.close()")}}
+
+

Fecha o contexto de áudio, liberando todos os recursos de áudio do sistema que ele usa.

+
+
{{domxref("AudioContext.createBuffer()")}}
+
Cria um novo, objeto  {{ domxref("AudioBuffer") }} vázio, que pode ser preenchido por dados e reproduzido através de um {{ domxref("AudioBufferSourceNode") }}.
+
{{domxref("AudioContext.createBufferSource()")}}
+
Cria um {{domxref("AudioBufferSourceNode")}}, que pode ser usado para reproduzir e manipular dados de audio contidos dentro de um objeto {{ domxref("AudioBuffer") }}. {{ domxref("AudioBuffer") }} são criados usando {{domxref("AudioContext.createBuffer")}} ou retornado por {{domxref("AudioContext.decodeAudioData")}} quando decodifica com sucesso uma faixa de áudio.
+
{{domxref("AudioContext.createMediaElementSource()")}}
+
Cria um {{domxref("MediaElementAudioSourceNode")}} associado com um {{domxref("HTMLMediaElement")}}. Isso pode ser usado para reproduzir e manipular o audio This can be used to play and manipulate audio dos elementos  {{HTMLElement("video")}} ou {{HTMLElement("audio")}}.
+
{{domxref("AudioContext.createMediaStreamSource()")}}
+
Cria um {{domxref("MediaStreamAudioSourceNode")}} associado com um {{domxref("MediaStream")}} um fluxo (stream) de áudio que pode vir do microfone local do computador ou de outras fontes.
+
{{domxref("AudioContext.createMediaStreamDestination()")}}
+
Cria um {{domxref("MediaStreamAudioDestinationNode")}} associado com um {{domxref("MediaStream")}} representando um fluxo (stream) de audio que pode ser armazenado em um arquivo local ou enviados para outro computador.
+
{{domxref("AudioContext.createScriptProcessor()")}}
+
Cria um a {{domxref("ScriptProcessorNode")}}, que pode ser usado para processamento de áudio direto via JavaScript.
+
{{domxref("AudioContext.createStereoPanner()")}}
+
Cria um {{domxref("StereoPannerNode")}}, que pode ser usado para aplicar uma panorâmica estéreo para uma fonte de áudio.
+
{{domxref("AudioContext.createAnalyser()")}}
+
Creates an {{domxref("AnalyserNode")}}, which can be used to expose audio time and frequency data and for example to create data visualisations.
+
{{domxref("AudioContext.createBiquadFilter()")}}
+
Cria um {{domxref ("BiquadFilterNode")}}, que representa um filtro de segunda ordem configurável como vários tipos de filtros comuns diferentes: high-pass, low-pass, band-pass, etc.
+
{{domxref("AudioContext.createChannelMerger()")}}
+
Cria um {{domxref ("ChannelMergerNode")}}, que é usado para combinar canais de múltiplos fluxos de áudio em um único fluxo de áudio.
+
{{domxref("AudioContext.createChannelSplitter()")}}
+
Cria um {{domxref ("ChannelSplitterNode")}}, que é usado para acessar os canais individuais de um fluxo de áudio e processá-los separadamente.
+
{{domxref("AudioContext.createConvolver()")}}
+
Cria um {{domxref ("ConvolverNode")}}, que pode ser usado para aplicar efeitos de convolução ao seu gráfico de áudio, por exemplo, um efeito de reverberação.
+
{{domxref("AudioContext.createDelay()")}}
+
+

Cria um {{domxref ("DelayNode")}}, que é usado para atrasar o sinal de áudio recebido por uma certa quantia. Este nó também é útil para criar loops de feedback em um gráfico de API de Web Audio.

+
+
{{domxref("AudioContext.createDynamicsCompressor()")}}
+
Cria um {{domxref("DynamicsCompressorNode")}}, que pode ser usada para aplicar compressão acústica para um sínal de áudio.
+
{{domxref("AudioContext.createGain()")}}
+
Cria um {{domxref ("GainNode")}}, que pode ser usado para controlar o volume total do gráfico de áudio.
+
{{domxref("AudioContext.createIIRFilter()")}}
+
Cria um {{domxref ("IIRFilterNode")}}, que representa um filtro de segunda ordem configurável como vários tipos de filtros comuns diferentes.
+
{{domxref("AudioContext.createOscillator()")}}
+
Cria um {{domxref ("OscillatorNode")}}, uma fonte que representa uma forma de onda periódica. Isso basicamente gera um tom.
+
{{domxref("AudioContext.createPanner()")}}
+
Cria um {{domxref ("PannerNode")}}, que é usado para spatializar um fluxo de áudio recebido no espaço 3D.
+
{{domxref("AudioContext.createPeriodicWave()")}}
+
Cria um {{domxref ("PeriodicWave")}}, usado para definir uma forma de onda periódica que pode ser usada para determinar a saída de um {{domxref ("OscillatorNode")}}.
+
{{domxref("AudioContext.createWaveShaper()")}}
+
Cria um {{domxref ("WaveShaperNode")}}, que é usado para implementar efeitos de distorção não-lineares.
+
{{domxref("AudioContext.createAudioWorker()")}}
+
+

Cria um {{domxref ("AudioWorkerNode")}}, que pode interagir com um segmento de trabalho da Web para gerar, processar ou analisar o áudio diretamente. Isso foi adicionado à especificação em 29 de agosto de 2014, e ainda não foi implementado em nenhum navegador.

+
+
{{domxref("AudioContext.decodeAudioData()")}}
+
Decodifica assincronamente dados de arquivos de áudio contidos em {{domxref("ArrayBuffer")}}. Nesse caso, o ArrayBuffer geralmente é carregado a partir de um atributo de resposta {{domxref("XMLHttpRequest")}}'s definir o responseType para arraybuffer. Esse método funciona apenas em arquivos completos, não fragmentos de arquivos de áudio.
+
{{domxref("AudioContext.resume()")}}
+
Retoma a progressão do tempo em um contexto de áudio que anteriormente foi suspenso.
+
{{domxref("AudioContext.suspend()")}}
+
Suspende a progressão do tempo no contexto de áudio, interrompendo temporariamente o acesso ao hardware de áudio e reduzindo o uso da CPU / bateria no processo.
+
+ +

Métodos obsoletos

+ +
+
{{domxref("AudioContext.createJavaScriptNode()")}}
+
Cria um {{domxref("JavaScriptNode")}}, usado para para processamento de áudio direto via JavaScript. Este método é obsoleto e foi substituído por {{domxref("AudioContext.createScriptProcessor()")}}.
+
{{domxref("AudioContext.createWaveTable()")}}
+
Cria um {{domxref ("WaveTableNode")}}, usado para definir uma forma de onda periódica. Este método é obsoleto e foi substituído por {{domxref ("AudioContext.createPeriodicWave ()")}}.
+
+ +

Exemplos

+ +

Declaração básica de contexto de áudio:

+ +
var audioCtx = new AudioContext();
+ +

Cruzar a variante do navegador:

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+
+var oscillatorNode = audioCtx.createOscillator();
+var gainNode = audioCtx.createGain();
+var finish = audioCtx.destination;
+// etc.
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Web Audio API', '#the-audiocontext-interface', 'AudioContext')}}{{Spec2('Web Audio API')}}
+ +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}
+ 35
{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22
6.0{{property_prefix("webkit")}}
createStereoPanner(){{CompatChrome(42.0)}}{{CompatGeckoDesktop(37.0)}} {{CompatNo}}{{CompatNo}}{{CompatNo}}
onstatechange, state, suspend(), resume(){{CompatVersionUnknown}}{{CompatGeckoDesktop(40.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoDesktop(37.0)}} 2.2{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
createStereoPanner(){{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
onstatechange, state, suspend(), resume(){{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/audionode/index.html b/files/pt-br/web/api/audionode/index.html new file mode 100644 index 0000000000..8660afb978 --- /dev/null +++ b/files/pt-br/web/api/audionode/index.html @@ -0,0 +1,191 @@ +--- +title: AudioNode +slug: Web/API/AudioNode +translation_of: Web/API/AudioNode +--- +

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

+ +

A interface AudioNode é uma interface genérica para representar um módulo de processamento como uma fonte de áudio (ex. um elemento HTML {{HTMLElement("audio")}} ou {{HTMLElement("video")}} , um {{domxref("OscillatorNode")}}, etc.), um destino do áudio, um módulo intermediário de processamento (ex. um filtro como {{domxref("BiquadFilterNode")}} ou {{domxref("ConvolverNode")}}), ou um controle de volume (como o {{domxref("GainNode")}}).

+ +

AudioNodes participating in an AudioContext create a audio routing graph.

+ +

Um AudioNode tem entradas (inputs) e saídas (outputs), cada uma delas com uma determinada quantidade de canais. Um AudioNode sem nenhuma entrada e uma ou múltiplas saídas é chamado de 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(AudioNode)")}}
+
Allows us to connect one output of this node to one input of another node.
+
{{domxref("AudioNode.connect(AudioParam)")}}
+
Allows us to connect one output of this node to one input of an audio parameter.
+
{{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}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}}{{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
{{CompatVersionUnknown}}
channelCount channelCountMode{{CompatVersionUnknown}} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
connect(AudioParam){{CompatVersionUnknown}} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
channelCount
+ channelCountMode
{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
connect(AudioParam){{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/background_tasks_api/index.html b/files/pt-br/web/api/background_tasks_api/index.html new file mode 100644 index 0000000000..e5973e9400 --- /dev/null +++ b/files/pt-br/web/api/background_tasks_api/index.html @@ -0,0 +1,509 @@ +--- +title: Background Tasks API +slug: Web/API/Background_Tasks_API +translation_of: Web/API/Background_Tasks_API +--- +
{{DefaultAPISidebar("Tarefas em segundo plano")}}{{draft}}
+ +

The Cooperative Scheduling of Background Tasks API (also referred to as the Background Tasks API or simply the requestIdleCallback() API) provides the ability to queue tasks to be executed automatically by the user agent when it determines that there is free time to do so.

+ +

Conceitos e uso

+ +

The main thread of a Web browser is centered around its event loop. This code draws any pending updates to the {{domxref("Document")}} currently being displayed, runs any JavaScript code the page needs to run, accepts events from input devices, and dispatches those events to the elements that should receive them. In addition, the event loop handles interactions with the operating system, updates to the browser's own user interface, and so forth. It's an extremely busy chunk of code, and your main JavaScript code may run right inside this thread along with all of this. Certainly most if not all code that is capable of making changes to the DOM is running in the main thread, since it's common for user interface changes to only be available to the main thread.

+ +

Because event handling and screen updates are two of the most obvious ways users notice performance issues, it's important for your code to be a good citizen of the Web and help to prevent stalls in the execution of the event loop. In the past, there's been no way to do this reliably other than by writing code that's as efficient as possible and by offloading as much work as possible to workers. {{domxref("Window.requestIdleCallback()")}} makes it possible to become actively engaged in helping to ensure that the browser's event loop runs smoothly, by allowing the browser to tell your code how much time it can safely use without causing the system to lag. If you stay within the limit given, you can make the user's experience much better.

+ +

Getting the most out of idle callbacks

+ +

Because idle callbacks are intended to give your code a way to cooperate with the event loop to ensure that the system is utilized to its full potential without over-tasking it, resulting in lag or other performance problems, you should be thoughtful about how you go about using them.

+ + + +

Falling back to setTimeout

+ +

Because the Background Tasks API is fairly new, your code may need to be able to work on browsers that don't yet support it. You can do so with a simple shim that uses {{domxref("WindowTimers.setTimeout()", "setTimeout()")}} as a fallback option. This isn't a {{Glossary("polyfill")}}, since it's not functionally identical; setTimeout() doesn't let you make use of idle periods, but instead runs your code when possible, leaving us to do the best we can to avoid causing the user to experience performance lag.

+ +
window.requestIdleCallback = window.requestIdleCallback || function(handler) {
+  let startTime = Date.now();
+
+  return setTimeout(function() {
+    handler({
+      didTimeout: false,
+      timeRemaining: function() {
+        return Math.max(0, 50.0 - (Date.now() - startTime));
+      }
+    });
+  }, 1);
+}
+ +

If {{domxref("Window.requestIdleCallback", "window.requestIdleCallback")}} is undefined, we create it here. The function begins by recording the time at which our implementation was called. We'll be using that to compute the value returned by our shim for {{domxref("IdleDeadline.timeRemaining()", "timeRemaining()")}}.

+ +

Then we call {{domxref("WindowTimers.setTimeout", "setTimeout()")}}, passing into it a function which runs the callback passed into our implementation of requestIdleCallback(). The callback is passed an object which conforms to {{domxref("IdleDeadline")}}, with {{domxref("IdleDeadline.didTimeout", "didTimeout")}} set to false and a {{domxref("IdleDeadline.timeRemaining", "timeRemaining()")}} method which is implemented to give the callback 50 milliseconds of time to begin with. Each time timeRemaining() is called, it subtracts the elapsed time from the original 50 milliseconds to determine the amount of time left.

+ +

As a result, while our shim doesn't constrain itself to the amount of idle time left in the current event loop pass like the true requestIdleCallback(), it does at least limit the callback to no more than 50 milliseconds of run time per pass.

+ +

The implementation of our shim for {{domxref("Window.cancelIdleCallback", "cancelIdleCallback()")}} is much simpler:

+ +
window.cancelIdleCallback = window.cancelIdleCallback || function(id) {
+  clearTimeout(id);
+}
+ +

If cancelIdleCallback() isn't defined, this creates one which simply passes the specified callback ID through to {{domxref("WindowTimers.clearTimeout", "clearTimeout()")}}.

+ +

Now your code will work even on browsers that don't support the Background Tasks API, albeit not as efficiently.

+ +

Interfaces

+ +

The Background Tasks API adds only one new interface:

+ +
+
{{domxref("IdleDeadline")}}
+
An object of this type is passed to the idle callback to provide an estimate of how long the idle period is expected to last, as well as whether or not the callback is running because its timeout period has expired.
+
+ +

The {{domxref("Window")}} interface is also augmented by this API to offer the new {{domxref("window.requestIdleCallback", "requestIdleCallback()")}} and {{domxref("window.cancelIdleCallback", "cancelIdleCallback()")}} methods.

+ +

Example

+ +

In this example, we'll take a look at how you can use {{domxref("window.requestIdleCallback", "requestIdleCallback()")}} to run time-consuming, low-priority tasks during time the browser would otherwise be idle. In addition, this example demonstrates how to schedule updates to the document content using {{domxref("window.requestAnimationFrame", "requestAnimationFrame()")}}.

+ +

Below you'll find only the HTML and JavaScript for this example. The CSS is not shown, since it's not particularly crucial to understanding this functionality.

+ +

HTML content

+ +

In order to be oriented about what we're trying to accomplish, let's have a look at the HTML. This establishes a box (ID "Container") that's used to present the progress of an operation (because you never know how long decoding "quantum filament tachyon emissions" will take, after all) as well as a second main box (with the ID "logBox"), which is used to display textual output.

+ +
<p>
+  Demonstration of using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API">
+  cooperatively scheduled background tasks</a> using the <code>requestIdleCallback()</code>
+  method.
+</p>
+
+<div class="container">
+  <div class="label">Decoding quantum filament tachyon emissions...</div>
+  <progress id="progress" value="0"></progress>
+  <div class="button" id="startButton">
+    Start
+  </div>
+  <div class="label counter">
+    Task <span id="currentTaskNumber">0</span> of <span id="totalTaskCount">0</span>
+  </div>
+</div>
+
+<div class="logBox">
+  <div class="logHeader">
+    Log
+  </div>
+  <div id="log">
+  </div>
+</div>
+ +

The progress box uses a {{HTMLElement("progress")}} element to show the progress, along with a label with sections that are changed to present numeric information about the progress. In addition, there's a "Start" button (creatively given the ID "startButton"), which the user will use to start the data processing.

+ + + +

JavaScript content

+ +

Now that the document structure is defined, construct the JavaScript code that will do the work. The goal: to be able to add requests to call functions to a queue, with an idle callback that runs those functions whenever the system is idle for long enough a time to make progress.

+ +

Declaração de variáveis

+ +
let taskList = [];
+let totalTaskCount = 0;
+let currentTaskNumber = 0;
+let taskHandle = null;
+
+ +

These variables are used to manage the list of tasks that are waiting to be performed, as well as status information about the task queue and its execution:

+ + + +
let totalTaskCountElem = document.getElementById("totalTaskCount");
+let currentTaskNumberElem = document.getElementById("currentTaskNumber");
+let progressBarElem = document.getElementById("progress");
+let startButtonElem = document.getElementById("startButton");
+let logElem = document.getElementById("log");
+
+ +

Next we have variables which reference the DOM elements we need to interact with. These elements are:

+ + + +
let logFragment = null;
+let statusRefreshScheduled = false;
+
+ +

Finally, we set up a couple of variables for other items:

+ + + + + +

Gerenciando a lista de tarefas

+ +

Next, let's look at the way we manage the tasks that need to be performed. We're going to do this by creating a FIFO queue of tasks, which we'll run as time allows during the idle callback period.

+ +
Enqueueing tasks
+ +

First, we need a function that enqueues tasks for future execution. That function, enqueueTask(), looks like this:

+ +
function enqueueTask(taskHandler, taskData) {
+  taskList.push({
+    handler: taskHandler,
+    data: taskData
+  });
+
+  totalTaskCount++;
+
+  if (!taskHandle) {
+    taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000 });
+  }
+
+  scheduleStatusRefresh();
+}
+
+ +

enqueueTask() accepts as input two parameters:

+ + + +

To enqueue the task, we push an object onto the taskList array; the object contains the taskHandler and taskData values under the names handler and data, respectively, then increment totalTaskCount, which reflects the total number of tasks which have ever been enqueued (we don't decrement it when tasks are removed from the queue).

+ +

Next, we check to see if we already have an idle callback created; if taskHandle is 0, we know there isn't an idle callback yet, so we call {{domxref("Window.requestIdleCallback", "requestIdleCallback()")}} to create one. It's configured to call a function called runTaskQueue(), which we'll look at shortly, and with a timeout of 1 second, so that it will be run at least once per second even if there isn't any actual idle time available.

+ +
Running tasks
+ +

Our idle callback handler, runTaskQueue(), gets called when the browser determines there's enough idle time available to let us do some work or our timeout of one second expires. This function's job is to run our enqueued tasks.

+ +
function runTaskQueue(deadline) {
+  while ((deadline.timeRemaining() > 0 || deadline.didTimeout) && taskList.length) {
+    let task = taskList.shift();
+    currentTaskNumber++;
+
+    task.handler(task.data);
+    scheduleStatusRefresh();
+  }
+
+  if (taskList.length) {
+    taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000} );
+  } else {
+    taskHandle = 0;
+  }
+}
+
+ +

runTaskQueue()'s core is a loop which continues as long as there's time left (as determined by checking {{domxref("IdleDeadline.timeRemaining", "deadline.timeRemaining")}}) to be sure it's more than 0 or if the timeout limit was reached ({{domxref("IdleDeadline.didTimeout", "deadline.didTimeout")}} is true), and as long as there are tasks in the task list.

+ +

For each task in the queue that we have time to execute, we do the following:

+ +
    +
  1. We remove the task object from the queue.
  2. +
  3. We increment currentTaskNumber to track how many tasks we've executed.
  4. +
  5. We call the task's handler, task.handler, passing into it the task's data object (task.data).
  6. +
  7. We call a function, scheduleStatusRefresh(), to handle scheduling a screen update to reflect changes to our progress.
  8. +
+ +

When time runs out, if there are still tasks left in the list, we call {{domxref("Window.requestIdleCallback", "requestIdleCallback()")}} again so that we can continue to process the tasks the next time there's idle time available. If the queue is empty, we set taskHandle to 0 to indicate that we don't have a callback scheduled. That way, we'll know to request a callback next time enqueueTask() is called.

+ +

Updating the status display

+ +

One thing we want to be able to do is update our document with log output and progress information. However, you can't safely change the DOM from within an idle callback. Instead, we'll use {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}} to ask the browser to call us when it's safe to update the display.

+ +
Scheduling display updates
+ +

DOM changes are scheduled by calling the scheduleStatusRefresh() function.

+ +
function scheduleStatusRefresh() {
+    if (!statusRefreshScheduled) {
+      requestAnimationFrame(updateDisplay);
+      statusRefreshScheduled = true;
+  }
+}
+
+ +

This is a simple function. It checks to see if we've already scheduled a display refresh by checking the value of statusRefreshScheduled. If it's false, we call {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}} to schedule a refresh, providing the updateDisplay() function to be called to handle that work.

+ +
Updating the display
+ +

The updateDisplay() function is responsible for drawing the contents of the progress box and the log. It's called by the browser when the DOM is in a safe condition for us to apply changes during the process of rendering the next frame.

+ +
function updateDisplay() {
+  let scrolledToEnd = logElem.scrollHeight - logElem.clientHeight <= logElem.scrollTop + 1;
+
+  if (totalTaskCount) {
+    if (progressBarElem.max != totalTaskCount) {
+      totalTaskCountElem.textContent = totalTaskCount;
+      progressBarElem.max = totalTaskCount;
+    }
+
+    if (progressBarElem.value != currentTaskNumber) {
+      currentTaskNumberElem.textContent = currentTaskNumber;
+      progressBarElem.value = currentTaskNumber;
+    }
+  }
+
+  if (logFragment) {
+    logElem.appendChild(logFragment);
+    logFragment = null;
+  }
+
+  if (scrolledToEnd) {
+      logElem.scrollTop = logElem.scrollHeight - logElem.clientHeight;
+  }
+
+  statusRefreshScheduled = false;
+}
+ +

First, scrolledToEnd is set to true if the text in the log is scrolled to the bottom; otherwise it's set to false. We'll use that to determine if we should update the scroll position to ensure that the log stays at the end when we're done adding content to it.

+ +

Next, we update the progress and status information if any tasks have been enqueued.

+ +
    +
  1. If the current maximum value of the progress bar is different from the current total number of enqueued tasks (totalTaskCount), then we update the contents of the displayed total number of tasks (totalTaskCountElem) and the maximum value of the progress bar, so that it scales properly.
  2. +
  3. We do the same thing with the number of tasks processed so far; if progressBarElem.value is different from the task number currently being processed (currentTaskNumber), then we update the displayed value of the currently-being-processed task and the current value of the progress bar.
  4. +
+ +

Then, if there's text waiting to be added to the log (that is, if logFragment isn't null), we append it to the log element using {{domxref("Node.appendChild", "Element.appendChild()")}} and set logFragment to null so we don't add it again.

+ +

If the log was scrolled to the end when we started, we make sure it still is. Then we set statusRefreshScheduled to false to indicate that we've handled the refresh and that it's safe to request a new one.

+ +

Adding text to the log

+ +

The log() function adds the specified text to the log. Since we don't know at the time log() is called whether or not it's safe to immediately touch the DOM, we will cache the log text until it's safe to update. Above, in the code for updateDisplay(), you can find the code that actually adds the logged text to the log element when the animation frame is being updated.

+ +
function log(text) {
+  if (!logFragment) {
+      logFragment = document.createDocumentFragment();
+  }
+
+  let el = document.createElement("div");
+  el.innerHTML = text;
+  logFragment.appendChild(el);
+}
+
+ +

First, we create a {{domxref("DocumentFragment")}} object named logFragment if one doesn't currently exist. This element is a pseudo-DOM into which we can insert elements without immediately changing the main DOM itself.

+ +

We then create a new {{HTMLElement("div")}} element and set its contents to match the input text. Then we append the new element to the end of the pseudo-DOM in logFragment. logFragment will accumulate log entries until the next time updateDisplay() is called because the DOM for the changes.

+ +

Running tasks

+ +

Now that we've got the task management and display maintenance code done, we can actually start setting up code to run tasks that get work done.

+ +

The task handler

+ +

The function we'll be using as our task handler—that is, the function that will be used as the value of the task object's handler property—is logTaskHandler(). It's a simple function that outputs a bunch of stuff to the log for each task. In your own application, you'd replace this code with whatever task it is you wish to perform during idle time. Just remember that anything you want to do that changes the DOM needs to be handled through {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}}.

+ +
function logTaskHandler(data) {
+  log("<strong>Running task #" + currentTaskNumber + "</strong>");
+
+  for (i=0; i<data.count; i+=1) {
+    log((i+1).toString() + ". " + data.text);
+  }
+}
+
+ +

The main program

+ +

Everything is triggered when the user clicks the Start button, which causes the decodeTechnoStuff() function to be called.

+ + + +
function decodeTechnoStuff() {
+  totalTaskCount = 0;
+  currentTaskNumber = 0;
+  updateDisplay();
+
+  let n = getRandomIntInclusive(100, 200);
+
+  for (i=0; i<n; i++) {
+    let taskData = {
+      count: getRandomIntInclusive(75, 150),
+      text: "This text is from task number " + (i+1).toString() + " of " + n
+    };
+
+    enqueueTask(logTaskHandler, taskData);
+  }
+}
+
+document.getElementById("startButton").addEventListener("click", decodeTechnoStuff, false);
+ +

decodeTechnoStuff() starts by zeroing the values of totalTaskCount (the number of tasks added to the queue so far) and currentTaskNumber (the task currently being run), and then calls updateDisplay() to reset the display to its "nothing's happened yet" state.

+ +

This example will create a random number of tasks (between 100 and 200 of them). To do so, we use the getRandomIntInclusive() function that's provided as an example in the documentation for {{jsxref("Math.random()")}} to get the number of tasks to create.

+ +

Then we start a loop to create the actual tasks. For each task, we create an object, taskData, which includes two properties:

+ + + +

Each task is then enqueued by calling enqueueTask(), passing in logTaskHandler() as the handler function and the taskData object as the object to pass into the function when it's called.

+ +
+
+ +

Result

+ +

Below is the actual functioning result of the code above. Try it out, play with it in your browser's developer tools, and experiment with using it in your own code.

+ +

{{ EmbedLiveSample('Example', 600, 700) }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Background Tasks")}}{{Spec2("Background Tasks")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.Window.requestIdleCallback")}}

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/batterymanager/charging/index.html b/files/pt-br/web/api/batterymanager/charging/index.html new file mode 100644 index 0000000000..3a079ebc11 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/charging/index.html @@ -0,0 +1,33 @@ +--- +title: BatteryManager.charging +slug: Web/API/BatteryManager/charging +tags: + - API + - Battery API + - Propriedade +translation_of: Web/API/BatteryManager/charging +--- +

{{APIRef("Battery API")}}

+ +

Um valor Booleano que indica se a bateria está sendo ou não carregada no momento.

+ +

Sintaxe

+ +
var charging = navigator.battery.charging
+ +

No retorno, charging indica se a bateria está sendo carregada no momento; se a bateria está carregando (ou se não há bateria), este valor é  true. Caso contrário, o valor é false.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/chargingtime/index.html b/files/pt-br/web/api/batterymanager/chargingtime/index.html new file mode 100644 index 0000000000..3a02666207 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/chargingtime/index.html @@ -0,0 +1,34 @@ +--- +title: BatteryManager.chargingTime +slug: Web/API/BatteryManager/chargingTime +tags: + - API + - Battery API + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/chargingTime +--- +

{{APIRef("Battery API")}}

+ +

Indica a quantidade de tempo, em segundos, que resta até que a bateria esteja totalmente carregada.

+ +

Sintaxe

+ +
var time = navigator.battery.chargingTime
+ +

No retorno, time é o tempo restante em segundos até que a bateria esteja totalmente carregada, ou 0 se a bateria já estiver com sua carga completa. Se a bateria estiver descarregando (ou se o sistema não é capaz de derminar o tempo restante para o carregamento), este valor é Infinity.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/dischargingtime/index.html b/files/pt-br/web/api/batterymanager/dischargingtime/index.html new file mode 100644 index 0000000000..e5ca6b486c --- /dev/null +++ b/files/pt-br/web/api/batterymanager/dischargingtime/index.html @@ -0,0 +1,34 @@ +--- +title: BatteryManager.dischargingTime +slug: Web/API/BatteryManager/dischargingTime +tags: + - API + - Battery API + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/dischargingTime +--- +

{{APIRef("Battery API")}}

+ +

Indica a quantidade de tempo, em segundos, que restam até a bateria estar totalmente descarregada.

+ +

Sintaxe

+ +
var time = navigator.battery.dischargingTime
+ +

No retorno, time é o tempo restante em segundos até que a bateria esteja totamente descarregada e o sistema suspenda. Este valor é Infinity se a bateria estiver carregando, ao invés de descarregando, ou se o sistema não for capaz de determinar o tempo restante de carregamento (ou ainda se não existir uma bateria disponível).

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/index.html b/files/pt-br/web/api/batterymanager/index.html new file mode 100644 index 0000000000..1febd0d799 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/index.html @@ -0,0 +1,140 @@ +--- +title: BatteryManager +slug: Web/API/BatteryManager +tags: + - API + - Battery API + - Referencia +translation_of: Web/API/BatteryManager +--- +

{{APIRef("Battery API")}}

+ +

Resumo

+ +

A interface BatteryManager fornece maneiras de obter informações sobre o nível de carga da bateria do sistema.

+ +

A propriedade {{domxref("Navigator.battery","navigator.battery")}} retorna uma instância da interface BatteryManager que você pode utilizar para interajir com a API de status da bateria.

+ +

Propriedades

+ +
+
{{domxref("BatteryManager.charging")}} {{ReadOnlyInline}}
+
+

Um valor Booleano que indica se a bateria está sendo carregada no momento.

+
+
{{domxref("BatteryManager.chargingTime")}} {{ReadOnlyInline}}
+
+

Um número representando o tempo restante em segundos até a bateria estar completamente carregada, ou 0 se a carga já estiver completa.

+
+
{{domxref("BatteryManager.dischargingTime")}} {{ReadOnlyInline}}
+
Um número representando o tempo restante em segundos até a bateria estar completamente descarregada e o sistema ser suspenso.
+
{{domxref("BatteryManager.level")}} {{ReadOnlyInline}}
+
Um número representando o nível de carga da bateria do sistema em uma escala de valores entre 0.0 e 1.0.
+
+ +

Eventos

+ +
+
{{domxref("BatteryManager.onchargingchange")}}
+
Tratamento para o evento {{event("chargingchange")}}; Esse evento é enviado quando o status de carregamento da bateria é atualizado.
+
{{domxref("BatteryManager.onchargingtimechange")}}
+
Tratamento para o evento {{event("chargingtimechange")}}; Esse evento é enviado quando o tempo de carregamento da bateria é atualizado.
+
{{domxref("BatteryManager.ondischargingtimechange")}}
+
Tratamento para o evento {{event("dischargingtimechange")}}; Esse evento é enviado quando o tempo de descarregamento da bateria é atualizado.
+
{{domxref("BatteryManager.onlevelchange")}}
+
Tratamento para o evento {{event("levelchange")}}; Esse evento é enviado quando a nível da bateria é atualizado.
+
+ +

Métodos

+ +

Herdado de {{domxref("EventTarget")}}:

+ +

{{page("/pt-BR/docs/Web/API/EventTarget","Métodos")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Battery API')}}{{Spec2('Battery API')}}Especificação Inicial.
+ +

Compatibilidade entre navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatNo() }}
+ Chrome para Android: crbug.com/135863
+ Chrome OS: crbug.com/122593
{{CompatGeckoDesktop("10")}} {{ property_prefix("moz") }} [1]
+ {{CompatGeckoDesktop("16")}} (sem prefixo) [2]
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatNo() }}{{CompatGeckoMobile("10")}} {{ property_prefix("moz") }} [1]
+ {{CompatGeckoMobile("16")}} (sem prefixo) [2]
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

Notas para o Gecko

+ +

[1] Desabilitado por padrão no Firefox 10.0, mas pode ser habilitado alterando a preferência dom.battery.enabled para true. A partir do Firefox 11.0, mozBattery é habilitado por padrão.

+ +

[2] A Battery API é atualmente suportada no Android, Windows e Linux com UPower instalado. O suporte para MacOS está disponível a partir do Gecko 18.0 {{geckoRelease("18.0")}};

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/level/index.html b/files/pt-br/web/api/batterymanager/level/index.html new file mode 100644 index 0000000000..b8d58c68c6 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/level/index.html @@ -0,0 +1,34 @@ +--- +title: BatteryManager.level +slug: Web/API/BatteryManager/level +tags: + - API + - Battery API + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/level +--- +

{{APIRef("Battery API")}}

+ +

Indica o nível de carga atual da bateria como um valor entre 0.0 e 1.0.

+ +

Sintaxe

+ +
var level = navigator.battery.level
+ +

No retorno, level é um número representando o nível de carga da bateria do sistema em uma escala de valores entre 0.0 e 1.0. Um valor de 0.0 significa que a bateria está vazia e o sistema está prestes a ser suspenso. Um valor de 1.0 significa que a bateria está cheia. Um valor de 1.0 é também retornado se a implementação não é capaz de determinar o nível de carga ou se o sistema não é alimentado por bateria.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/onchargingchange/index.html b/files/pt-br/web/api/batterymanager/onchargingchange/index.html new file mode 100644 index 0000000000..2a2e687801 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/onchargingchange/index.html @@ -0,0 +1,35 @@ +--- +title: BatteryManager.onchargingchange +slug: Web/API/BatteryManager/onchargingchange +tags: + - API + - Battery API + - Event Handler + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/onchargingchange +--- +

{{APIRef("Battery API")}}

+ +

Especifica um event listener para receber eventos {{event("chargingchange")}}. Esses eventos ocorrem quando o estado {{domxref("BatteryManager.charging", "charging")}} (carregando) da bateria é atualizado.

+ +

Sintaxe

+ +
navigator.battery.onchargingchange = funcRef
+ +

Onde funcRef é uma função para ser chamada quando o evento {{event("chargingchange")}} ocorre.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/onchargingtimechange/index.html b/files/pt-br/web/api/batterymanager/onchargingtimechange/index.html new file mode 100644 index 0000000000..8c711d75d6 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/onchargingtimechange/index.html @@ -0,0 +1,35 @@ +--- +title: BatteryManager.onchargingtimechange +slug: Web/API/BatteryManager/onchargingtimechange +tags: + - API + - Battery API + - Event Handler + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/onchargingtimechange +--- +

{{APIRef("Battery API")}}

+ +

Especifica um event listener para receber eventos {{event("chargingtimechange")}}. Esses eventos ocorrem quando a propriedade {{domxref("BatteryManager.chargingTime","chargingTime")}} (tempo de carregamento) da bateria é atualizada.

+ +

Sintaxe

+ +
navigator.battery.onchargingtimechange = funcRef
+ +

Onde funcRef é uma função para ser chamada quando o evento {{event("chargingtimechange")}} ocorre.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/ondischargintimechange/index.html b/files/pt-br/web/api/batterymanager/ondischargintimechange/index.html new file mode 100644 index 0000000000..4f5c402588 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/ondischargintimechange/index.html @@ -0,0 +1,35 @@ +--- +title: BatteryManager.ondischargingtimechange +slug: Web/API/BatteryManager/ondischargintimechange +tags: + - API + - Battery API + - Event Handler + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/ondischargingtimechange +--- +

{{APIRef("Battery API")}}

+ +

Especifica um event listener para receber eventos {{event("dischargingtimechange")}}. Esses eventos ocorrem quando a propriedade {{domxref("BatteryManager.dischargingTime","dischargingTime")}} (tempo de descarregamento) da bateria é atualizada.

+ +

Sintaxe

+ +
navigator.battery.ondischargingtimechange = funcRef
+ +

Onde funcRef é uma função para ser chamada quando o evento {{event("dischargingtimechange")}} ocorre.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/onlevelchange/index.html b/files/pt-br/web/api/batterymanager/onlevelchange/index.html new file mode 100644 index 0000000000..911d760327 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/onlevelchange/index.html @@ -0,0 +1,35 @@ +--- +title: BatteryManager.onlevelchange +slug: Web/API/BatteryManager/onlevelchange +tags: + - API + - Battery API + - Event Handler + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/onlevelchange +--- +

{{APIRef("Battery API")}}

+ +

Especifica um event listener para receber eventos {{event("levelchange")}}. Esses eventos ocorrem quando o {{domxref("BatteryManager.level","level")}} (nível) da bateria é atualizado.

+ +

Sintaxe

+ +
navigator.battery.onlevelchange = funcRef
+ +

Onde funcRef é uma função para ser chamada quando o evento {{event("levelchange")}} ocorre.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/biquadfilternode/index.html b/files/pt-br/web/api/biquadfilternode/index.html new file mode 100644 index 0000000000..c23c1eff33 --- /dev/null +++ b/files/pt-br/web/api/biquadfilternode/index.html @@ -0,0 +1,186 @@ +--- +title: BiquadFilterNode +slug: Web/API/BiquadFilterNode +tags: + - API + - BiquadFilterNode + - CompatibilidadeNavegadorCelular + - Interface + - Referencia + - Web Audio API +translation_of: Web/API/BiquadFilterNode +--- +

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

+ +
+

A interface BiquadFilterNode representa um filtro simples de ordem baixa, e é criada utilizando o método {{ domxref("AudioContext.createBiquadFilter()") }} . É o {{domxref("AudioNode")}} que pode representar diferentes tipos de filtros, dispositivo de controle de timbre, e equalizadores gráficos. Um BiquadFilterNode sempre tem exatamente uma entrada e uma saída.

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
Número de entradas1
Número de saídas1
Modo de contagem de canal"max"
Contagem de canal2 (não utilizado no modo de contagem padrão)
Interpretação de canal"speakers"
+ +

Construtor

+ +
+
{{domxref("BiquadFilterNode.BiquadFilterNode", "BiquadFilterNode()")}}
+
Cria uma nova instância de um objeto do tipo BiquadFilterNode.
+
+ +

Propriedades

+ +

Herda as propriedades de seu pai, {{domxref("AudioNode")}}.

+ +
+
{{domxref("BiquadFilterNode.frequency")}}
+
É um a-rate {{domxref("AudioParam")}}, um double que representa a frequência no algoritmo de filtragem atual, medido em hertz (Hz).
+
{{domxref("BiquadFilterNode.detune")}}
+
É um  a-rate {{domxref("AudioParam")}} representando a dessintonização da frequência em cents.
+
{{domxref("BiquadFilterNode.Q")}}
+
É um a-rate {{domxref("AudioParam")}}, um double representando um Q factor, ou fator de qualidade.
+
{{domxref("BiquadFilterNode.gain")}} {{readonlyInline}}
+
É um a-rate {{domxref("AudioParam")}}, um double representando o gain utilizado no algoritmo de filtragem atual.
+
{{domxref("BiquadFilterNode.type")}}
+
É um valor string que define o tipo de algoritmo de filtragem que o nó está implementando.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
O significado dos diferentes parâmetros de acordo com o tipo de filtro (detune tem o mesmo significado, então não está listado abaixo)
tipoDescriçãofrequênciaQganho
lowpass +

Filtro de resonância lowpass padrão de segunda ordem com 12dB/octave rolloff. Frequências abaixo do ponto de corte passam; frequências acima são atenuadas.

+
A frequência de corte.Indica o quão perto a frequência chegou em relação ao ponto de corte. Quantomaior o valor, maior será a aproximação.Não utilizado
highpassFiltro de resonância highpass padrão de segunda ordem com 12dB/octave rolloff. Frequências abaixo do ponto de corte são atenuadas; frequências acima passam.A frequência de corte.Indica o quão perto a frequência chegou em relação ao ponto de corte. Quantomaior o valor, maior será a aproximação.Não utilizado
bandpassFiltro bandpass padrão de segunda ordem. Frequências fora do dado limite de frequências são atenuadas; frequências dentro do limite passam.O centro de alcance de frequências.Controla a largura da banda de frequência. Quanto maior o valor Q, menor a frequência de banda.Não utilizado
lowshelfFiltro lowshelf padrão de segunda ordem. Frequências menores que a frequência recebem um aumento, ou uma atenuação; frequências maiores não sofrem alterações.O limite superior das frequênicas recebe um aumento ou atenuação.Não utilizadoO aumento, em dB, para ser aplicado; se negativo, ele será uma atenuação.
highshelfFiltro highshelf padrão de segunda ordem. Frequências maiores que a frequência recebem aumento ou atenuação; frequências abaixo disso não sofrem alterações.O limite inferior de frequências recebe aumento ou uma atenuação.Não utilizado +

O aumento, em dB, para ser aplicado; se negativo, ele será uma atenuação.

+
peakingFrequências dentro da faixa de frequencias  recebem aumento ou atenuação; frequências fora da faixa não sofrem alterações.O meio da faixa de frequência recebe um aumento ou uma atenuação.Controla a largura da banda de frequência. Quanto maior o valor Q, menor a frequência de banda.O aumento, em dB, para ser aplicado; se negativo, ele será uma atenuação.
notchFiltro notch padrão, também chamado de filtro band-stop ou band-rejection. É o oposto do filtro de de bandpass: frequências fora da faixa de frequências atribuída passam; frequências de dentro da faixa são atenuadas.O centro de alcance de frequências.Controla a largura da banda de frequência. Quanto maior o valor Q, menor a frequência de banda.Não utilizado
allpassFiltro allpass padrão de segunda ordem. Permite que todas as frequências passem, porém altera a relação de fase entre as diversas frequências.A frequência com o máximo group delay, ou seja, a frequência onde o centro da fase de transição ocorre.Controla o quão apurada a transição é na frequência média. Quanto maior este parâmetro, mais apurada e ampla será a transiçãoNão utilizado
+
+
+ +

Métodos

+ +

Herda os métodos de seu pai, {{domxref("AudioNode")}}.

+ +
+
{{domxref("BiquadFilterNode.getFrequencyResponse()")}}
+
A partir dos parâmetros de configuração do filtro atual, este método calcula a frequência de resposta para frequências especificadas no array de frequências.
+
+ +

Exemplo

+ +

{{page("/en-US/docs/Web/API/AudioContext.createBiquadFilter","Example")}}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Audio API', '#the-biquadfilternode-interface', 'BiquadFilterNode')}}{{Spec2('Web Audio API')}} 
+ +

Compatibilidade dos navegadores

+ +
+ + +

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

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/blob/blob/index.html b/files/pt-br/web/api/blob/blob/index.html new file mode 100644 index 0000000000..fbb8b121c5 --- /dev/null +++ b/files/pt-br/web/api/blob/blob/index.html @@ -0,0 +1,65 @@ +--- +title: Blob +slug: Web/API/Blob/Blob +translation_of: Web/API/Blob/Blob +--- +

{{APIRef("File API")}}

+ +

Blob()

+ +

 

+ +

Retorna um novo objeto Blob criado, cujo o conteúdo consiste na concatenação de um array de valores estabelecidos no parâmetro da função.

+ +

Syntaxe

+ +
var aBlob = new Blob( array[, options]);
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; // an array consisting of a single DOMString
+var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('File API', '#constructorBlob', 'Blob()')}}{{Spec2('File API')}}Definição inicial.
+ +

Compatibilidade com navegadores

+ + + +

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

+ +

Veja também

+ + + +

 

diff --git a/files/pt-br/web/api/blob/index.html b/files/pt-br/web/api/blob/index.html new file mode 100644 index 0000000000..f976675a1a --- /dev/null +++ b/files/pt-br/web/api/blob/index.html @@ -0,0 +1,130 @@ +--- +title: Blob +slug: Web/API/Blob +translation_of: Web/API/Blob +--- +

{{ APIRef("File API") }}

+ +

Sumário

+ +

Um objeto Blob representa um objeto do tipo arquivo, com  dados brutos imutáveis. Blobs representam dados que não estão necessariamente em um formato JavaScript nativo. A interface {{ domxref("File") }} é baseada no Blob, herdando funcionalidade blob e expandindo-o para suportar arquivos no sistema do usuário.

+ +

Para construir um Blob a partir de outro objeto ou dado não-blob , utilize o construtor {{domxref("Blob.Blob","Blob()")}}. Para criar um blob que contém um subconjunto de dados de outro blob, use o método {{domxref("Blob.slice()", "slice()")}}. Para obter um objeto Blob de um arquivo no sistema de arquivos do usuário, veja a documentação {{domxref("File")}}.

+ +

The APIs accepting Blob objects are also listed on the {{domxref("File")}} documentation.

+ +
+

Nota: O método slice() usava inicialmente length como segundo argumento para indicar o numero de bytes a copiar no novo Blob.  Se você especificou valores de maneira que start + length excederam o tamanho do Blob de origem, o Blob retornado contém dados a partir do início do índice até o final do Blob de origem.

+
+ +
Nota:  Esteja ciente que o método slice() possui prefixos de fornecedores em alguns navegadores e versões: blob.mozSlice() para Firefox 12 e anteriores, e blob.webkitSlice() para Safari. Uma versão antiga do método slice(), sem prefixos de fornecedor, tem semântica diferente, e portanto é obsoleta. O suporta para blob.mozSlice() foi descontinuado a partir do Firefox 30.
+ +

Construtor

+ +
+
{{domxref("Blob.Blob", "Blob(blobParts[, opções])")}}
+
Retorna um novo Blob object cujo conteúdo consiste na concatenação do array de valores passados por parâmentro.
+
+ +

Propriedades

+ +
+
{{domxref("Blob.size")}} {{readonlyinline}}
+
Tamanho em bytes dos dados contidos no objeto Blob.
+
{{domxref("Blob.type")}} {{readonlyinline}}
+
Uma string que indica o MIME type dos dados no Blob. Se o tipo é desconhecido, então retorna uma string vazia.
+
+ +

Métodos

+ +
+
{{domxref("Blob.slice()", "Blob.slice([start[, end[, contentType]]])")}}
+
Retorna um novo  Blob object contendo dados em no intervalo de bytes especificado do Blob de origem.
+
+ +

Exemplos

+ +

Exemplos de uso do construtor Blob

+ +

O código a seguir:

+ +
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
+var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // o blob
+
+ +

equivale a:

+ +
var oBuilder = new BlobBuilder();
+var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
+oBuilder.append(aFileParts[0]);
+var oMyBlob = oBuilder.getBlob('text/xml'); // o blob
+
+ +
+

O {{ domxref("BlobBuilder") }} oferece outra maneira para criar Blobs, mas é depreciado e não deveria mais ser usado.

+
+ +

Exemplo para criar uma URL para uma array tipada usando blob

+ +

O código a seguir:

+ +
var typedArray = GetTheTypedArraySomehow();
+var blob = new Blob([typedArray], {type: 'application/octet-binary'}); // passe um MIME-type útil aqui
+var url = URL.createObjectURL(blob);
+// url será algo do tipo: blob:d3958f5c-0777-0845-9dcf-2cb28783acaf
+// agora você pode usar a URL em qualquer contexto em que URLs regulares podem ser usadas, por exemplo: img.src, etc.
+
+ +

Exemplo de Extração de Dados de Um Blob

+ +

O único jeito de ler o conteúdo de um Blob é usando {{domxref("FileReader")}}. O código a seguir lê o conteudo de um Blob como um Array.

+ +
var reader = new FileReader();
+reader.addEventListener("loadend", function() {
+   // reader.result contém o conteúdo do blob como uma array tipada
+});
+reader.readAsArrayBuffer(blob);
+ +

Ao usar outros métodos de {{domxref("FileReader")}}, é possível ler o conteúdo de um Blob como uma string ou como uma data URL.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('File API','#blob','Blob')}}{{Spec2('File API')}}Definição inicial.
+ +

Compatibilidade de Browser

+ + + +

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

+ +

Notas para Gecko

+ +

Anterior ao Gecko 12.0 {{ geckoRelease("12.0") }}, havia um bug que afetava o comportamento do {{ manch("slice") }}; que não funcionava para as posições start e end fora do intervalo de valores assinados como 64-bit; este bug foi corrigido para dar suporte a valores assinados como 64-bit.

+ +

Chrome Code - Disponibilidade de Escopo

+ +

No escopo JSM, Blob é disponivel sem a necessidade de nada especial.

+ +

No escopo Bootstrap, ele deve ser importado como tal:

+ +
const {Blob, Services} = Cu.import('resource://gre/modules/Services.jsm', {});
+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/blob/size/index.html b/files/pt-br/web/api/blob/size/index.html new file mode 100644 index 0000000000..f73f76dca2 --- /dev/null +++ b/files/pt-br/web/api/blob/size/index.html @@ -0,0 +1,60 @@ +--- +title: Blob.size +slug: Web/API/Blob/size +translation_of: Web/API/Blob/size +--- +
{{APIRef("File API")}}
+ +

A propriedade Blob.size retorna o tamanho em bytes de {{domxref("Blob")}} ou um {{domxref("File")}}.

+ +

Syntaxe

+ +
var sizeInBytes = blob.size
+
+ +

Valor

+ +

Um número.

+ +

Exempl0

+ +
// fileInput é um HTMLInputElement: <input type="file" multiple id="myfileinput">
+var fileInput = document.getElementById("myfileinput");
+
+// files é um objeto FileList (similiar ao 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çãoStatusComentário
{{SpecName('File API', '#dfn-size', 'size')}}{{Spec2('File API')}}Definição inicial.
+ +

Compatibilidade com navegadores

+ +
+ + +

{{Compat("api.Blob.size")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/blob/slice/index.html b/files/pt-br/web/api/blob/slice/index.html new file mode 100644 index 0000000000..a6f44cfebd --- /dev/null +++ b/files/pt-br/web/api/blob/slice/index.html @@ -0,0 +1,115 @@ +--- +title: Blob.slice() +slug: Web/API/Blob/slice +translation_of: Web/API/Blob/slice +--- +
{{APIRef("File API")}}
+ +

O método Blob.slice() é usado para criar um novo {{domxref("Blob")}} object  contendo os dados no intervalo especificado de bytes da fonte {{domxref("Blob")}}.

+ +
Nota: Esteja ciente de que o método slice () tem prefixos de fornecedores em alguns navegadores e versões: blob.mozSlice () para Firefox 12 e anteriores e blob.webkitSlice () no Safari. Uma versão antiga do método slice (), sem prefixos de fornecedor, tinha uma semântica diferente e é obsoleta
+ +

Sintaxe

+ +
let blob = instanceOfBlob.slice([start [, end [, contentType]]]);
+ +

Parâmetros

+ +
+
start {{optional_inline}}
+
An index into the {{domxref("Blob")}} indicating the first byte to include in the new {{domxref("Blob")}}. If you specify a negative value, it's treated as an offset from the end of the string toward the beginning. For example, -10 would be the 10th from last byte in the {{domxref("Blob")}}. The default value is 0. If you specify a value for start that is larger than the size of the source {{domxref("Blob")}}, the returned {{domxref("Blob")}} has size 0 and contains no data.
+
end {{optional_inline}}
+
An index into the {{domxref("Blob")}} indicating the first byte that will *not* be included in the new {{domxref("Blob")}} (i.e. the byte exactly at this index is not included). If you specify a negative value, it's treated as an offset from the end of the string toward the beginning. For example, -10 would be the 10th from last byte in the {{domxref("Blob")}}. The default value is size.
+
contentType {{optional_inline}}
+
The content type to assign to the new {{domxref("Blob")}}; this will be the value of its type property. The default value is an empty string.
+
+ +

Return value

+ +

A new {{domxref("Blob")}} object containing the specified data from the source {{domxref("Blob")}}.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("File API", "#dfn-slice", "Blob.slice()")}}{{Spec2("File API")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support10 {{property_prefix("webkit")}} [1]
+ 21
{{CompatVersionUnknown}}5 {{property_prefix("moz")}} [1]
+ 13 [2]
1012 [1]5.1 {{property_prefix("webkit")}} [3]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("13.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] The slice() method had initially taken length as the second argument to indicate the number of bytes to include in the new Blob. If you specified values such that start + length exceeded the size of the source Blob, the returned Blob contained data from the start index to the end of the source Blob. That version of the slice() was implemented in Firefox 4, WebKit, and Opera 11.10. However, since that syntax is differed from Array.slice() and String.slice(), Gecko and WebKit removed support and added support for the new syntax as Blob.slice()/Blob.webkitSlice.

+ +

[2] Prior to Gecko 12.0 {{geckoRelease("12.0")}}, there was a bug that affected the behavior of Blob.slice(); it did not work for start and end positions outside the range of signed 64-bit values; it has now been fixed to support unsigned 64-bit values.

+ +

[3] This was implemented in 534.29.

+ +

See also

+ + diff --git a/files/pt-br/web/api/blob/type/index.html b/files/pt-br/web/api/blob/type/index.html new file mode 100644 index 0000000000..789aa0c9c9 --- /dev/null +++ b/files/pt-br/web/api/blob/type/index.html @@ -0,0 +1,68 @@ +--- +title: Blob.type +slug: Web/API/Blob/type +translation_of: Web/API/Blob/type +--- +
{{APIRef("File API")}}
+ +

A propriedade type de um objeto Blob fornece MIME type do arquivo. Ela retorna uma string vazia se o tipo não puder ser determinado.

+ +

Syntaxe

+ +
var mimetype = instanceOfFile.type
+ +

Valor

+ +

Uma string

+ +

Exemplo

+ +
var i, fileInput, files, allowedFileTypes;
+
+// fileInput é um HTMLInputElement: <input type="file" multiple id="myfileinput">
+fileInput = document.getElementById("myfileinput");
+
+// files é um objeto FileList (similiar ao NodeList)
+files = fileInput.files;
+
+// nossa aplicação permite apenas imagens dos tipos *.png, *.jpeg and *.gif
+allowedFileTypes = ["image/png", "image/jpeg", "image/gif"];
+
+for (i = 0; i < files.length; i++) {
+  // Testa se file.type é um tipo de arquivo permitido.
+  if (allowedFileTypes.indexOf(files[i].type) > -1) {
+    // file type é um dos tipos permitidos. Código aqui.
+  }
+});
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('File API', '#dfn-type', 'type')}}{{Spec2('File API')}}Definição inicial.
+ +

Compatibilidade com navegadores

+ +
+ + +

{{Compat("api.Blob.type")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/body/index.html b/files/pt-br/web/api/body/index.html new file mode 100644 index 0000000000..121e93718b --- /dev/null +++ b/files/pt-br/web/api/body/index.html @@ -0,0 +1,97 @@ +--- +title: Body +slug: Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - request +translation_of: Web/API/Body +--- +
{{ APIRef("Fetch") }}
+ +

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

+ +

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

+ +

Properties

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
A {{jsxref("Boolean")}} that indicates whether the body has been read.
+
+ +

Methods

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{jsxref("ArrayBuffer")}}.
+
{{domxref("Body.blob()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
+
{{domxref("Body.formData()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
+
{{domxref("Body.json()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as {{jsxref("JSON")}}.
+
{{domxref("Body.text()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
+
+ +

Examples

+ +

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

+ +

HTML Content

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS Content

+ +
const myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
+	.then(res => res.blob())
+	.then(res => {
+		const objectURL = URL.createObjectURL(res);
+		myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Examples', '100%', '250px') }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}}
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/body/json/index.html b/files/pt-br/web/api/body/json/index.html new file mode 100644 index 0000000000..7ee4482fe5 --- /dev/null +++ b/files/pt-br/web/api/body/json/index.html @@ -0,0 +1,89 @@ +--- +title: Body.json() +slug: Web/API/Body/json +tags: + - API + - Experimental + - Fetch + - JSON + - Referencia +translation_of: Web/API/Body/json +--- +
{{APIRef("Fetch API")}}
+ +

O método json()  do mixin {{DOMxRef("Body")}} usa uma stream do objeto {{DOMxRef("Response")}} para tratar. O método json() retorna uma Promise como resultado do processamento da stream, retornando um objeto {{JSxRef("JSON")}} em caso de sucesso.

+ +

Syntaxe

+ +
response.json().then(data => {
+  // do something with your data
+});
+ +

Parâmetros

+ +

Nenhum.

+ +

Retorno

+ +

Uma {{jsxref("Promise")}} que retorna um objeto Javascript no método resolve(). Pode ser qualquer tipo que pode ser representado com JSON — objeto, array, string, numeral...

+ +

Exemplo

+ +

Em nosso exemplo de fetch em json (teste aqui a busca em json com fetch), nós criamos uma nova requisição usando o constructor de {{DOMxRef("Request.Request", "Request()")}}, e em seguimos a usamos para buscar um arquivo .json. Quando o fetch é bem-sucedido, nós lemos e tratamos a stream com o método json(), lê os valores em forma de objeto retornados como esperado e inserimos na lista para exibir os dados dos produtos.

+ +
const myList = document.querySelector('ul');
+const myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(response => response.json())
+  .then(data => {
+    for (const product of data.products) {
+      let listItem = document.createElement('li');
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = product.Name;
+      listItem.append(
+        ` can be found in ${
+          product.Location
+        }. Cost: `
+      );
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = `£${product.Price}`;
+      myList.appendChild(listItem);
+    }
+  })
+  .catch(console.error);
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificaçõesStatusComentários
{{SpecName("Fetch", "#dom-body-json", "Body.json()")}}{{Spec2("Fetch")}}Definição Inicial
+ +

Compatibilidade de Navegador

+ + + +

{{Compat("api.Body.json")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/broadcastchannel/index.html b/files/pt-br/web/api/broadcastchannel/index.html new file mode 100644 index 0000000000..e15c5f23a4 --- /dev/null +++ b/files/pt-br/web/api/broadcastchannel/index.html @@ -0,0 +1,81 @@ +--- +title: BroadcastChannel +slug: Web/API/BroadcastChannel +tags: + - API + - Broadcast Channel API + - Experimental + - HTML API + - Interface + - Reference +translation_of: Web/API/BroadcastChannel +--- +

{{APIRef("Broadcast Channel API")}}

+ +

A interface BroadcastChannel (canal de transmissão) representa um canal com um nome em que qualquer {{glossary("browsing context")}} (contexto de navegação) de uma determinada {{glossary("origin")}} (origem) pode assinar. Permite a comunicação entre diferentes documentos (em diferentes janelas, abas, frames ou iframes) da mesma origin. As mensagens são transmitidas através de um evento {{event("message")}} acionado em todos objetos do tipo BroadcastChannel que estão ouvindo o canal.

+ +

{{AvailableInWorkers}}

+ +

Construtor

+ +
+
{{domxref("BroadcastChannel.BroadcastChannel", "BroadcastChannel()")}}
+
Cria um objeto, no qual faz o vínculo com um canal nomeado.
+
+ +

Propriedades

+ +

Essa interface também herda propriedades de seu pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("BroadcastChannel.name")}}
+
Retorna um {{domxref("DOMString")}}, o nome do canal.
+
+

Event handlers

+
+
{{domxref("BroadcastChannel.onmessage")}}
+
Uma propriedade {{domxref("EventHandler")}} que específica a função a ser executada quando um evento {{event("message")}} é acionado a este objeto.
+
{{domxref("BroadcastChannel.onmessageerror")}}
+
Uma chamada {{domxref("EventHandler")}} quando um {{domxref("MessageEvent")}} do tipo {{domxref("MessageError")}} é disparado - isto é, quando recebe uma mensagem que não pode ser desserializada.
+
+ +

Métodos

+ +

Essa interface também herda métodos de seu pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("BroadcastChannel.postMessage()")}}
+
Envia a mensagem, de qualquer tipo de objeto, para cada objeto BroadcastChannel ouvindo o mesmo canal.
+
{{domxref("BroadcastChannel.close()")}}
+
Fecha o objeto do canal, indicando que ele não receberá novas mensagens e eventualmente será descartado.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "comms.html#broadcastchannel", "BroadcastChannel")}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ +

Compatibilidade entre Navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/cache/index.html b/files/pt-br/web/api/cache/index.html new file mode 100644 index 0000000000..9647fb506e --- /dev/null +++ b/files/pt-br/web/api/cache/index.html @@ -0,0 +1,282 @@ +--- +title: Cache +slug: Web/API/Cache +tags: + - API + - Armazenamento + - Cache + - Experimental + - Interface + - Offline + - Rascunho + - Referencia + - Service Workers +translation_of: Web/API/Cache +--- +

{{APIRef("Service Workers API")}}{{SeeCompatTable}}

+ +

A interface de Cache provê um mecanismo de pares de objeto Request / Response que estão cacheados, por exemplo, como parte do ciclo de vida de um {{domxref("ServiceWorker")}}. Note que a interface do Cache é exposta a escopos de janela como também aos workers. Você não precisa utiliza-la em conjunto com os service workers em si, mesmo que ela esteja definida na especificação dos mesmos.

+ +

Uma origem pode ter múltiplos objetos de cache nomeados. Você é o responsável por implementar como seu script (por exemplo, em um {{domxref("ServiceWorker")}}) trata uma atualização deste Cache. Itens em um Cache não são atualizados a não ser que explicitamente comandados para fazer tal coisa, também não expiram a não ser quando são deletados. Use {{domxref("CacheStorage.open", "CacheStorage.open(cacheName)")}} para abrir um Cache nomeado específico e depois chame qualquer um dos métodos presentes no Cache para manter os objetos cacheados.

+ +

Você é também o responsavel por, periódicamente, limpar as entradas de cache. Cada browser tem um limite fixo do tamanho de armazenamento de cache que cada origem pode utilizar. O browser faz o melhor que pode para gerenciar o espaço em disco, mas ele pode deletar um cache que não devia. Ele também vai, geralmente, deletar todos os dados de uma origem ou nenhum dado da mesma, nunca haverá uma ocasião não atômica onde o browser delete parcialmente os dados.

+ +

Certifique-se de versionar seus caches por nome e usar somente os caches nas versões do script que eles podem seguramente operar. Veja também o artigo sobre remoção de caches antigos para mais informações.

+ +
+

Nota: Implementações iniciais do Cache (tanto no Blink quando no Gecko) resolvem promises de {{domxref("Cache.add")}}, {{domxref("Cache.addAll")}}, e {{domxref("Cache.put")}} somente quando o corpo completo da resposta foi armazenado. Versões mais recentes desta especificação possuem uma melhora de linguagem informando que o browser pode resolver a promise assim que a entrada é registrada no banco de dados, mesmo que o corpo da resposta ainda esteja sendo enviado.

+
+ +
+

Nota: O algoritmo de comparação de chaves depende do cabeçalho VARY no valor. Então, comparar uma nova chave depende tanto de olhar para o valor e para a própria chave para novas entradas no cache.

+
+ +
+

Nota: A API de cache não segue os padrões HTTP de cabeçalhos de Cache.

+
+ +

Métodos

+ +
+
{{domxref("Cache.match", "Cache.match(request, options)")}}
+
Retorna uma {{jsxref("Promise")}} que resolve para a resposta associada com a primeira requisição encontrada no objeto {{domxref("Cache")}}.
+
{{domxref("Cache.matchAll", "Cache.matchAll(request, options)")}}
+
Retorna uma {{jsxref("Promise")}} que resolve para um array com todas as referências encontradas de requisições presentes no objeto {{domxref("Cache")}}.
+
{{domxref("Cache.add", "Cache.add(request)")}}
+
Pega a URL, obtém o resultado da resposta e adiciona o mesmo no cache informado. Esta funcionalidade é equivalente a chamar fetch(), e depois utilizar Cache.put() para adicionar o resultado no cache.
+
{{domxref("Cache.addAll", "Cache.addAll(requests)")}}
+
A partir de um array de URL's, obtém as respostas e adiciona todos os objetos resultantes no cache informado.
+
{{domxref("Cache.put", "Cache.put(request, response)")}}
+
Dado uma requisição e uma resposta, adiciona ambas ao cache informado.
+
{{domxref("Cache.delete", "Cache.delete(request, options)")}}
+
Encontra a entrada do {{domxref("Cache")}} na qual a chave é a requisição e, se encontrada, deleta a entrada do {{domxref("Cache")}} e retorna uma {{jsxref("Promise")}} que se resolve para true. Se nenhuma entrada do {{domxref("Cache")}} for encontrada, ela é resolvida para false.
+
{{domxref("Cache.keys", "Cache.keys(request, options)")}}
+
Retorna uma {{jsxref("Promise")}} que resolve em um array de chaves de {{domxref("Cache")}}.
+
+ +

Exemplos

+ +

Este trecho de código é da amostra de cache seletivo (veja seleção live de cache), ele utiliza {{domxref("CacheStorage.open", "CacheStorage.open(cacheName)")}} para abrir quaisquer objetos {{domxref("Cache")}} com um cabeçalho Content-Type que inicie com font/.

+ +

Então, utilizamos {{domxref("Cache.match", "Cache.match(request, options)")}} para verificar se já existe uma fonte encontrada no cache e, se existir, retorna-la. Caso contrário, o código busca a fonte da rede e utiliza {{domxref("Cache.put","Cache.put(request, response)")}} para adiciona-la ao cache.

+ +

O código gerencia as exceções disparadas pela operação {{domxref("Globalfetch.fetch","fetch()")}}. Note que uma resposta de erro HTTP (como o 404) não vai ativar uma exceção. Será retornado um objeto de resposta padrão que possui seu próprio código de erros.

+ +

O trecho também mostra as melhores práticas de versionamento de caches utilizadas pelo service worker. Mesmo que só estejamos utilizando um cache neste exemplo, a mesma aproximação pode ser utilizada para múltiplos caches. Mapeamos um identificador para um cache específico e versionado. Por fim, o código deleta todos os cache que não estão presentes em CURRENT_CACHES.

+ +

No exemplo, "Caches" é um atributo dos service workers no WorkerGlobalScope. Ele contém o CacheStorage, um objeto pelo qual podemos acessar a API de mesmo nome.

+ +
Nota: No Chrome, visite chrome://inspect/#service-workers e clique no link "inspect" abaixo do service worker registrado para analisar os logs das várias ações que o script "service-worker.js" está executando.
+ +
var CACHE_VERSION = 1;
+
+// Identificador menor para uma versão específica do cache
+var CURRENT_CACHES = {
+  font: 'font-cache-v' + CACHE_VERSION
+};
+
+self.addEventListener('activate', function(event) {
+  var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
+    return CURRENT_CACHES[key];
+  });
+
+  // O worker não vai ser tratado como ativo até que a Promise se resolva.
+  event.waitUntil(
+    caches.keys().then(function(cacheNames) {
+      return Promise.all(
+        cacheNames.map(function(cacheName) {
+          if (expectedCacheNames.indexOf(cacheName) == -1) {
+            console.log('Deletando cache expirado:', cacheName);
+
+            return caches.delete(cacheName);
+          }
+        })
+      );
+    })
+  );
+});
+
+self.addEventListener('fetch', function(event) {
+  console.log('Obtendo evento fetch para', event.request.url);
+
+  event.respondWith(
+
+    // Abre o objeto de cache que inicia com 'font'
+    caches.open(CURRENT_CACHES['font']).then(function(cache) {
+      return cache.match(event.request).then(function(response) {
+        if (response) {
+          console.log(' Encontrou resposta em cache:', response);
+
+          return response;
+        }
+      }).catch(function(error) {
+
+        // Trata exceções que vem de match() ou fetch().
+        console.error('  Erro na handler:', error);
+
+        throw error;
+      });
+    })
+  );
+});
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Definição inicial
+ +

Tabela de compatibilidade

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(40.0)}}{{CompatGeckoDesktop(39)}}[1]{{CompatNo}}24{{CompatNo}}
add(){{CompatChrome(44.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
addAll(){{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
matchAll(){{CompatChrome(47.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Requere HTTPS para add(), addAll(), e put(){{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Suporte básico{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(39)}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
add(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(44.0)}}
addAll(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
matchAll(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
Requere HTTPS para add(), addAll(), e put(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
+
+ +

[1] Service workers (e Push) foram desabilitados no Firefox 45 & 52 Extended Support Releases (ESR.)

+ +

Ver também

+ + diff --git a/files/pt-br/web/api/cameracontrol/autofocus/index.html b/files/pt-br/web/api/cameracontrol/autofocus/index.html new file mode 100644 index 0000000000..1ce3b547d3 --- /dev/null +++ b/files/pt-br/web/api/cameracontrol/autofocus/index.html @@ -0,0 +1,61 @@ +--- +title: CameraControl.autoFocus() +slug: Web/API/CameraControl/autoFocus +translation_of: Archive/B2G_OS/API/CameraControl/autoFocus +--- +

{{APIRef("Camera API")}}{{ non-standard_header() }}{{B2GOnlyHeader2('privileged')}}

+ +

Resumo

+ +

This method attempts to focus the camera. If the camera is able to attempt to focus, a success callback is issued, regardless of whether or not the focusing attempt succeeds. If unable to attempt to focus, an error callback is performed instead.

+ +

The success or failure of the focus operation is indicated by the value of a parameter passed into the callback function.

+ +

Sintaxe

+ +
CameraControl.autoFocus(onsuccess[, onerror]);
+ +

Parametros

+ +
+
onsuccess
+
A callback function called when a focus attempt is made
+
onerror {{optional_inline()}}
+
An optional callback function that accepts an error string as an input parameter; this is called if it's not possible to attempt to focus the camera.
+
+ +

Exemplo

+ +
function onFocusPossible( success ) {
+  if ( success ) {
+    console.log("The image has been focused");
+  } else {
+    console.log("The image has not been focused");
+  }
+}
+
+function onFocusNotPossible( error ) {
+  console.log("The camera is not able to focus anything");
+  console.log( error );
+}
+
+function onAccessCamera( camera ) {
+  camera.autoFocus(onFocusPossible, onFocusNotPossible);
+};
+
+var options = {
+  camera: navigator.mozCameras.getListOfCameras()[0]
+};
+
+navigator.mozCameras.getCamera(options, onAccessCamera)
+
+ +

Especificações

+ +

Not part of any specification; however, this API should be removed when the WebRTC Capture and Stream API has been implemented.

+ +

Leia mais

+ + diff --git a/files/pt-br/web/api/cameracontrol/index.html b/files/pt-br/web/api/cameracontrol/index.html new file mode 100644 index 0000000000..e0b5bdd2c0 --- /dev/null +++ b/files/pt-br/web/api/cameracontrol/index.html @@ -0,0 +1,108 @@ +--- +title: CameraControl +slug: Web/API/CameraControl +tags: + - API + - B2G + - DOM + - DOM Reference + - Firefox OS + - Graphics + - JavaScript + - NeedsTranslation + - Non-standard + - Reference + - TopicStub + - WebAPI + - camera +translation_of: Archive/B2G_OS/API/CameraControl +--- +

{{APIRef("Camera API")}}

+ +

{{ non-standard_header() }}

+ +

{{B2GOnlyHeader2('privileged')}}

+ +

When you use the {{domxref("CameraManager.getCamera()")}} method to get a reference to a camera, you specify a callback function to be invoked on success. That function receives as a parameter a CameraControl object. You can use its methods and properties to manage and make use of the camera.

+ +

Properties

+ +
+
{{domxref("CameraControl.capabilities")}} {{readonlyinline}}
+
A {{domxref("CameraCapabilities")}} object indicating all the capabilities for the given camera.
+
{{domxref("CameraControl.effect")}}
+
A string defining the effect to be used by the camera (none by default). Its value must be one of the values available in {{domxref("CameraCapabilities.effects")}}.
+
{{domxref("CameraControl.exposureCompensation")}} {{readonlyinline}}
+
A value used to compensate the camera exposure. This attribute is read-only; to change the exposure, you need to call the {{domxref("CameraControl.setExposureCompensation()")}} method.
+
{{domxref("CameraControl.flashMode")}}
+
A string that defines how the flash, if any, is to be used; this is auto by default if the device has a flash, none otherwise. When set, its value must be chosen from the list of options specified by  {{domxref("CameraCapabilities.flashModes")}}.
+
{{domxref("CameraControl.focalLength")}} {{readonlyinline}}
+
A number that express the camera's focal length in millimeters.
+
{{domxref("CameraControl.focusAreas")}}
+
An Array of one or more objects that define where the camera will perform auto-focusing.
+
{{domxref("CameraControl.focusDistanceFar")}} {{readonlyinline}}
+
This value is a distance in meter used with {{domxref("CameraControl.focusDistanceNear")}} to defined the image's depth of field. The value for this property may be Infinity.
+
{{domxref("CameraControl.focusDistanceNear")}} {{readonlyinline}}
+
This value is a distance in meter used with {{domxref("CameraControl.focusDistanceFar")}} to defined the image's depth of field.
+
{{domxref("CameraControl.focusDistanceOptimum")}} {{readonlyinline}}
+
This value is a distance in meter where the subject will appear sharpest.
+
{{domxref("CameraControl.focusMode")}}
+
A string that defines which kind of focus mode the camera should use (auto or fixed by default). Its value must be chosen from {{domxref("CameraCapabilities.focusModes")}}.
+
{{domxref("CameraControl.meteringAreas")}}
+
An Array of one or more objects that define where the camera will perform auto-focusing.
+
{{domxref("CameraControl.onShutter")}}
+
A handler for the camera's "shutter" event, to trigger a shutter sound and/or a visual shutter indicator.
+
{{domxref("CameraControl.onClosed")}}
+
A handler called when a new CameraControl object in the same app takes over the camera.
+
{{domxref("CameraControl.onRecorderStateChange")}}
+
A function to call when the recorder changes state, either because the recording process encountered an error, or because one of the recording limits (see {{domxref("CameraControl.startRecording()")}}) was reached.
+
{{domxref("CameraControl.sceneMode")}}
+
A string that defines which scene mode the camera is to use (auto by default). Its value must be chosen from {{domxref("CameraCapabilities.sceneModes")}}.
+
{{domxref("CameraControl.whiteBalanceMode")}}
+
A string that defines which white balance mode the camera is to use (auto by default). Its value must be chosen from {{domxref("CameraCapabilities.whiteBalanceModes")}}.
+
{{domxref("CameraControl.zoom")}}
+
A number that defines which kind of zoom factor mode the camera is to use (1 by default). Its value must be chosen from {{domxref("CameraCapabilities.zoomRatios")}}.
+
+ +

Methods

+ +
+
{{ domxref("CameraControl.autoFocus()") }}
+
Tells the camera to attempt to focus the image.
+
{{ domxref("CameraControl.getPreviewStream()") }}
+
Gets a video stream from the camera; you can use this in an arbitrary context.
+
{{ domxref("CameraControl.getPreviewStreamVideoMode()") }}
+
Gets a video stream from the camera based on a specific video mode.
+
{{ domxref("CameraControl.release()") }}
+
Releases the camera so that other applications can use it.
+
{{ domxref("CameraControl.resumePreview()") }}
+
Resumes the preview video stream after it's been paused by a call to {{domxref("CameraControl.takePicture()")}}.
+
{{ domxref("CameraControl.setExposureCompensation()") }}
+
Lets you specify the exposure compensation factor.
+
{{ domxref("CameraControl.startRecording()") }}
+
Lets you start recording a video stream.
+
{{ domxref("CameraControl.stopRecording()") }}
+
Lets you stop recording a video stream.
+
{{ domxref("CameraControl.pauseRecording()") }}
+
Pauses the recording of a video stream.
+
{{ domxref("CameraControl.resumeRecording()") }}
+
Resumes the recording of a video stream that has previously been paused.
+
{{ domxref("CameraControl.takePicture()") }}
+
Lets you capture a single image, receiving it as a {{domxref("Blob")}}.
+
+ +

Specification

+ +

{{page("/en-US/docs/Web/API/Navigator.MozCameras","Specification")}}

+ +

Permissions

+ +

{{page("/en-US/docs/Web/API/Navigator.MozCameras","Permissions")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/arc/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/arc/index.html new file mode 100644 index 0000000000..763831af7d --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/arc/index.html @@ -0,0 +1,138 @@ +--- +title: CanvasRenderingContext2D.arc() +slug: Web/API/CanvasRenderingContext2D/arc +tags: + - API + - Arco + - Canvas + - CanvasRenderingContext2D + - Circulo + - Method + - Reference +translation_of: Web/API/CanvasRenderingContext2D/arc +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.arc() da API Canvas 2D adiciona um arco circular para o atual sub-caminhoa (sub-path).

+ +

Sintaxe

+ +
void ctx.arc(x, y, raio, anguloInicial, anguloFinal [, antiHorario]);
+
+ +

O método arc() cria um arco circular centralizado em (x, y) com um raio. O caminho inicia-se no anguloInicial, e finaliza no anguloFinal, e é desenhado no sentido antiHoario (o padrão é no sentido horario).

+ +

Parâmetros

+ +
+
x
+
A coordenada horizontal do centro do arco.
+
y
+
A coordenada vertical do centro do arco.
+
raio
+
O raio do arco. Deve ser um valor positivo.
+
anguloInicial
+
O ângulo em radianos em que o arco começa medido a partir do eixo x positivo.
+
anguloFinal
+
O ângulo em que o arco finaliza medido a partir do eixo x positivo.
+
antiHorario {{optional_inline}}
+
Um {{jsxref("Boolean")}} opcional. Se verdadeiro, desenha o arco no sentido anti-horário entre os ângulos inicial e final. O padrão é falso (sentido horário).
+
+ +

Examplos

+ +

Desenhando um círculo completo

+ +

O exemplo desenha um círculo completo com o método arc().

+ +

HTML

+ +
<canvas></canvas>
+
+ +

JavaScript

+ +

O arco recebe 100 como uma coordenada x, e 75 como uma coordenada y e um raio de 50. para fazer um círculo completo, o arco inicia no ângulo 0 (0º) em radianos e finaliza em um ângulo de 2π radianos (360°).

+ +
const canvas = document.querySelector('canvas');
+const ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.arc(100, 75, 50, 0, 2 * Math.PI);
+ctx.stroke();
+
+ +

Resultado

+ +

{{ EmbedLiveSample('Drawing_a_full_circle', 700, 180) }}

+ +

Diferentes formas demonstradas

+ +

Este exemplo desenha diversas formas para mostrar o que é possível fazer com o método arc().

+ + + +
const canvas = document.querySelector('canvas');
+const ctx = canvas.getContext('2d');
+
+// Draw shapes
+for (let i = 0; i <= 3; i++) {
+  for (let j = 0; j <= 2; j++) {
+    ctx.beginPath();
+    let x             = 25 + j * 50;                 // coordenada x
+    let y             = 25 + i * 50;                 // coordenada y
+    let radius        = 20;                          // raio
+    let startAngle    = 0;                           // angulo inicial
+    let endAngle      = Math.PI + (Math.PI * j) / 2; // angulo final
+    let anticlockwise = i % 2 == 1;                  // sentido anti-horário
+
+    ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
+
+    if (i > 1) {
+      ctx.fill();
+    } else {
+      ctx.stroke();
+    }
+  }
+}
+ +

Resultado

+ +

{{ EmbedLiveSample('Different_shapes_demonstrated', 160, 210, "https://mdn.mozillademos.org/files/204/Canvas_arc.png") }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-arc", "CanvasRenderingContext2D.arc")}}{{Spec2('HTML WHATWG')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("api.CanvasRenderingContext2D.arc")}}

+ +

Veja mais

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/arcto/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/arcto/index.html new file mode 100644 index 0000000000..c4fcdc1e69 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/arcto/index.html @@ -0,0 +1,147 @@ +--- +title: CanvasRenderingContext2D.arcTo() +slug: Web/API/CanvasRenderingContext2D/arcTo +translation_of: Web/API/CanvasRenderingContext2D/arcTo +--- +
{{APIRef}}
+ +

 

+ +

O método CanvasRenderingContext2D.arcTo() da API 2D do Canvas adiciona um arco ao caminho quando fornecemos seus pontos de controle e raio.

+ +

O arco será parte de um círculo, nunca de uma elipse. Frequentemente é usado para fazer cantos arredoondados.

+ +

Pode-se imaginar o arco como dois segmentos de reta, partindo de um ponto inicial (ponto mais recente definido no caminho) até o primeiro ponto de controle e, em seguida, do primeiro ponto de controle até o segundo ponto de controle. Esses dois segmentos de reta formam um angulo, com o primeiro ponto de controle sendo a curva. Usando arcTo, o ângulo será formado de acordo com o raio fornecido.

+ +

O arco é tangencial ao dois segmentos de reta, e por vezes, pode produzir resultados inesperados se, por exemplo, o raio fornecido for maior que a distância entre o ponto inicial e o primeiro ponto de controle.

+ +

Se o raio fornecido não atingir o ponto inicial (ponto mais recente definido no caminho), o ponto inicial é conectado ao arco por um segmento de reta.

+ +

Sintaxe

+ +
void ctx.arcTo(x1, y1, x2, y2, radius);
+
+ +

Parâmetros

+ +
+
x1
+
coordenada do eixo x para o primeiro ponto de controle.
+
y1
+
coordenada do eixo y para o primeiro ponto de controle.
+
x2
+
coordenada do eixo x para o segundo ponto de controle.
+
y2
+
coordenada do eixo y para o segundo ponto de controle.
+
radius
+
O raio do arco.
+
+ +

Exemplos

+ +

Usando o método arcTo 

+ +

Esse é um trecho simples de código que desenha um arco. O ponto de partida é azul e os pontos de controls são vermelhos.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(150, 20);
+ctx.arcTo(150, 100, 50, 20, 30);
+ctx.lineTo(50, 20)
+ctx.stroke();
+
+ctx.fillStyle = 'blue';
+// starting point
+ctx.fillRect(150, 20, 10, 10);
+
+ctx.fillStyle = 'red';
+// control point one
+ctx.fillRect(150, 100, 10, 10);
+// control point two
+ctx.fillRect(50, 20, 10, 10);
+
+ +

{{ EmbedLiveSample('Using_the_arc_method', 315, 165) }}

+ +

Treinando os parâmetros do  arcTo 

+ +

Altere o código abaixo e veja suas alterações atualizadas na tela:

+ +
+
<canvas id="canvas" class="playable-canvas" height="200" width="400"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.moveTo(150, 20);
+ctx.arcTo(150,100,50,100,20);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Trying_the_arcTo_parameters', 700, 360) }}

+ +

Espeficicações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-arcto", "CanvasRenderingContext2D.arcTo")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade

+ + + +

{{Compat("api.CanvasRenderingContext2D.arcTo")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/beginpath/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/beginpath/index.html new file mode 100644 index 0000000000..b3ad87ff61 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/beginpath/index.html @@ -0,0 +1,184 @@ +--- +title: CanvasRenderingContext2D.beginPath() +slug: Web/API/CanvasRenderingContext2D/beginPath +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/beginPath +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.beginPath() da API Canvas 2D  inicia um novo caminho (path), esvaziando a lista de sub-caminhos (sub-paths). Use esse método quando você quiser criar um novo path.

+ +

Sintaxe

+ +
void ctx.beginPath();
+
+ +

Exemplos

+ +

Usando o método beginPath

+ +

Isto é só um simples trecho de código que usa o método fillRect.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+// Primeiro path
+ctx.beginPath();
+ctx.strokeStyle = 'blue';
+ctx.moveTo(20, 20);
+ctx.lineTo(200, 20);
+ctx.stroke();
+
+// Segundo path
+ctx.beginPath();
+ctx.strokeStyle = 'green';
+ctx.moveTo(20, 20);
+ctx.lineTo(120, 120);
+ctx.stroke();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code" style="height:200px">
+// First path
+ctx.beginPath();
+ctx.strokeStyle = 'blue';
+ctx.moveTo(20,20);
+ctx.lineTo(200,20);
+ctx.stroke();
+
+// Second path
+ctx.beginPath();
+ctx.strokeStyle = 'green';
+ctx.moveTo(20,20);
+ctx.lineTo(120, 120);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 460) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-beginpath", "CanvasRenderingContext2D.beginPath")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/clearrect/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/clearrect/index.html new file mode 100644 index 0000000000..ec1be69b57 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/clearrect/index.html @@ -0,0 +1,195 @@ +--- +title: CanvasRenderingContext2D.clearRect() +slug: Web/API/CanvasRenderingContext2D/clearRect +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/clearRect +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.clearRect() da API Canvas 2D limpa todos os pixels de um retângulo definido na posição (x, y) e tamanho (width (largura), height (altura)) para uma cor preta transparente, apagando algum conteúdo anterior.

+ +

Sintaxe

+ +
void ctx.clearRect(x, y, width, height);
+
+ +

Parâmetros

+ +
+
x
+
O valor da coordenada x para o ponto inicial do retângulo.
+
y
+
O valor da coordenada y para o ponto inicial do retângulo.
+
width
+
A largura do retângulo.
+
height
+
A altura do retângulo.
+
+ +

Notas de uso

+ +

Um problema comum com clearRect que pode acontecer, é que pode não funcionar corretamente, caso não seja usada alguma propriedade de path. Não esqueça de usar {{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}} antes de começar um novo frame depois de chamar clearRect.

+ +

Exemplos

+ +

Usando o método clearRect

+ +

Isto é só um simples trecho de código que usa o método clearRect.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(20, 20);
+ctx.lineTo(200, 20);
+ctx.lineTo(120, 120);
+ctx.closePath(); // draws last line of the triangle
+ctx.stroke();
+
+ctx.clearRect(10, 10, 100, 100);
+
+// clear the whole canvas
+// ctx.clearRect(0, 0, canvas.width, canvas.height);
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code" style="height:140px;">
+ctx.beginPath();
+ctx.moveTo(20,20);
+ctx.lineTo(200,20);
+ctx.lineTo(120,120);
+ctx.closePath(); // draws last line of the triangle
+ctx.stroke();
+
+ctx.clearRect(10, 10, 100, 100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 400) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-clearrect", "CanvasRenderingContext2D.clearRect")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/clip/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/clip/index.html new file mode 100644 index 0000000000..780ba3cd58 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/clip/index.html @@ -0,0 +1,195 @@ +--- +title: CanvasRenderingContext2D.clip() +slug: Web/API/CanvasRenderingContext2D/clip +translation_of: Web/API/CanvasRenderingContext2D/clip +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.clip() da API do Canvas 2D transforma o caminho atualmente construido em um caminho atual de recorte.

+ +

Sintaxe

+ +
void ctx.clip();
+void ctx.clip(fillRule);
+void ctx.clip(path, fillRule);
+
+ +

Parâmetros

+ +

+ +
+
fillRule
+
O algoritmo pelo qual determina se um ponto esta dentro de um caminho ou fora de um caminho.
+ Valores Possíveis: + +
+
path
+
Um {{domxref("Path2D")}} caminho para recorte.
+
+ +

Exemplos

+ +

Usando do método de corte

+ +

Isso é só um simples fragmento de código que usa o método de corte para criar uma região de recorte.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+// Cria uma região de recorte
+ctx.arc(100, 100, 75, 0, Math.PI*2, false);
+ctx.clip();
+
+ctx.fillRect(0, 0, 100,100);
+
+ +

Edite o código abaixo e veja suas mudanças atualizadas ao vivo no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.arc(100, 100, 75, 0, Math.PI*2, false);
+ctx.clip();
+ctx.fillRect(0, 0, 100,100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +
+

Nota: Tenha consciência de que o clip() só funciona com formas adicionadas ao caminho; ele não funciona com uma forma primitiva, como retângulos criados com {{domxref("CanvasRenderingContext2D.fillRect()","fillRect()")}}. Nesse caso você teria que usar {{domxref("CanvasRenderingContext2D.rect()","rect()")}} para desenhar um caminho de forma retângular para ser recortado.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-clip", "CanvasRenderingContext2D.clip")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade com os navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Parametro do Caminho{{CompatUnknown}}{{ CompatGeckoDesktop(31) }}{{ CompatNo }}{{CompatUnknown}}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Parametro do Caminho{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile(31) }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/closepath/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/closepath/index.html new file mode 100644 index 0000000000..62c72086f7 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/closepath/index.html @@ -0,0 +1,170 @@ +--- +title: CanvasRenderingContext2D.closePath() +slug: Web/API/CanvasRenderingContext2D/closePath +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/closePath +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.closePath() da API Canvas 2D faz o ponto da caneta (pen) mover-se de volta para o início do sub-caminho (sub-path) atual. Tenta adicionar uma nova linha (mas não a desenha realmente) que conecta o ponto atual até o ponto inicial. Se a região (shape) já estiver fechada, ou tem somente um ponto na tela, esta função não funciona.

+ +

Sintaxe

+ +
void ctx.closePath();
+
+ +

Exemplos

+ +

Usando o método beginPath

+ +

Isto é só um simples trecho de código que usa o método fillRect.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(20, 20);
+ctx.lineTo(200, 20);
+ctx.lineTo(120, 120);
+ctx.closePath(); // desenha a última linha do triângulo
+ctx.stroke();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code" style="height:140px;">
+ctx.beginPath();
+ctx.moveTo(20,20);
+ctx.lineTo(200,20);
+ctx.lineTo(120,120);
+ctx.closePath(); // draws last line of the triangle
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 400) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-closepath", "CanvasRenderingContext2D.closePath")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/fill/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/fill/index.html new file mode 100644 index 0000000000..0c0c1dd890 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/fill/index.html @@ -0,0 +1,196 @@ +--- +title: CanvasRenderingContext2D.fill() +slug: Web/API/CanvasRenderingContext2D/fill +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/fill +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.fill() da API Canvas 2D preenche um dado path ou o path atual com o estilo atual de preenchimento usando uma regra de controle diferente de zero, ou uma regra par-ímpar.

+ +

Syntax

+ +
void ctx.fill();
+void ctx.fill(fillRule);
+void ctx.fill(path, fillRule);
+
+ +

Parâmetros

+ +
+
fillRule
+
O algoritmo que determina se um ponto está do lado de dentro do path ou do lado fora do path.
+ Possíveis valores: + +
+
path
+
Um path de Path2D para preenchimento.
+
+ +

Exemplos

+ +

Usando o método fill

+ +

Isto é só um simples trecho de código que usa o métod fill para contornar um path.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+ctx.rect(10, 10, 100, 100);
+ctx.fill();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rect(10, 10, 100, 100);
+ctx.fill();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-fill", "CanvasRenderingContext2D.fill")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Suporte para o parâmetro path{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(31) }}{{ CompatNo }}{{ CompatVersionUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Suporte para o parâmetro path{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile(31) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/fillrect/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/fillrect/index.html new file mode 100644 index 0000000000..44b57ca77a --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/fillrect/index.html @@ -0,0 +1,179 @@ +--- +title: CanvasRenderingContext2D.fillRect() +slug: Web/API/CanvasRenderingContext2D/fillRect +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/fillRect +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.fillRect() da API Canvas 2D desenha um retângulo preenchido na posição (x, y), no qual o tamanho é determinado pela width (largura) e pela height (altura), e cujo o estilo é determinado pelo atributo fillStyle.

+ +

Sintaxe

+ +
void ctx.fillRect(x, y, width, height);
+
+ +

Parâmetros

+ +
+
x
+
O valor da coordenada x para o ponto inicial do retângulo.
+
y
+
O valor da coordenada y para o ponto inicial do retângulo.
+
width
+
A largura do retângulo.
+
height
+
A altura do retângulo.
+
+ +

Exemplos

+ +

Usando o método fillRect

+ +

Isto é só um simples trecho de código que usa o método fillRect.

+ +

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);
+
+// preenche todo o canvas
+// ctx.fillRect(0, 0, canvas.width, canvas.height);
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.fillStyle = "green";
+ctx.fillRect(10, 10, 100, 100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-fillrect", "CanvasRenderingContext2D.fillRect")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/fillstyle/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/fillstyle/index.html new file mode 100644 index 0000000000..37dd9ba936 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/fillstyle/index.html @@ -0,0 +1,213 @@ +--- +title: CanvasRenderingContext2D.fillStyle +slug: Web/API/CanvasRenderingContext2D/fillStyle +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Propriedade + - Referencia +translation_of: Web/API/CanvasRenderingContext2D/fillStyle +--- +
{{APIRef}}
+ +

A propriedade CanvasRenderingContext2D.fillStyle da API do Canvas 2D especifica a cor ou o estilo para usar regiões internas. O valor inicial é #000 (preto).

+ +

Veja também o capítulo Aplicando estilos e cores no Canvas Tutorial.

+ +

Sintaxe

+ +
ctx.fillStyle = color;
+ctx.fillStyle = gradient;
+ctx.fillStyle = pattern;
+
+ +

Opções

+ +
+
color
+
Um {{domxref("DOMString")}} passado como um valor de CSS {{cssxref("<color>")}}.
+
gradient
+
Um objeto {{domxref("CanvasGradient")}} (um gradiente linear ou radial).
+
pattern
+
Um objeto {{domxref("CanvasPattern")}} (uma imagem repetitiva).
+
+ +

Examples

+ +

Usando a propriedade fillStyle para definir uma cor diferente

+ +

Isto é apenas um trecho de código simples usando a propriedade fillStyle para definir uma cor diferente.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.fillStyle = 'blue';
+ctx.fillRect(10, 10, 100, 100);
+
+ +

Edite o código abaixo e veja as alterações atualizadas na tela:

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Um exemplo de fillStyle com laços for

+ +

Neste exemplo, nós usamos dois laços for para desenhar uma grade de retângulos, cada um com uma cor diferente. A imagem resultante deve parecer algo como uma captura de tela. Não há nada de espetacular acontecendo aqui. Usamos as duas variáveis i é j para gerar uma cor RGB exclusiva para cada quadrado, e apenas modificamos os valores vermelho e verde. O canal azul tem um valor fixo. Ao modificar os canais, você pode gerar todos os tipos de paletas. Ao aumentar os valores, você pode conseguir algo que pareça com as paletas de cores que o Photoshop usa.

+ + + +
var ctx = document.getElementById('canvas').getContext('2d');
+for (var i = 0; i < 6; i++){
+  for (var j = 0; j < 6; j++){
+    ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ',' +
+                     Math.floor(255 - 42.5 * j) + ',0)';
+    ctx.fillRect(j * 25, i * 25, 25, 25);
+  }
+}
+
+ +

O resultado fica assim:

+ +

{{EmbedLiveSample("Um_exemplo_de_fillStyle_com_laços_for", 160, 160, "https://mdn.mozillademos.org/files/5417/Canvas_fillstyle.png")}}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-fillstyle", "CanvasRenderingContext2D.fillStyle")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibibidade com o Navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ + + + + +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/index.html new file mode 100644 index 0000000000..38ec19a3e3 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/index.html @@ -0,0 +1,450 @@ +--- +title: 'Canvas: Contexto de Renderização em "2D"' +slug: Web/API/CanvasRenderingContext2D +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Games + - Graphics + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/CanvasRenderingContext2D +--- +
{{APIRef}}
+ +
A interface Canvas Renderização de Contexto de duas Dimensões ( CanvasRenderingContext2D) é usada para desenhar retangulos, textos, imagens e outros objetos na tag ou elemento canvas. Fornece o contexto de renderização em 2D para a superfície de desenho do elemento  {{ HTMLElement("canvas") }}.
+ +
+ +

Para obter um objeto desta interface, chama-se  {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} em um elemento <canvas>, adicionando "2d" como argumento, veja o exemplo abaixo:

+ +
var canvas = document.getElementById('meuCanvas'); // em seu HTML esse elemento se parece com <canvas id="meuCanvas"></canvas>
+var ctx = canvas.getContext('2d');
+
+ +

Agora que você possui o contexto de renderização 2D, você pode desenhar dentro deste canvas. Por exemplo:

+ +
ctx.fillStyle = "rgb(200,0,0)"; // define a cor de preenchimento do retângulo
+ctx.fillRect(10, 10, 55, 50);   // desenha o retângulo na posição 10, 10 com 55 pixels de largura e uma altura de 50
+
+ +

Veja as propriedades e métodos no menu lateral e abaixo. O tutorial canvas tem mais informações, exemplos e recursos.

+ +

Desenhando Retângulos

+ +

Existem três métodos que imediatamente desenham retângulos ao canvas.

+ +
+
{{domxref("CanvasRenderingContext2D.clearRect()")}}
+
Determina todos os pixels no retângulo definido, pelo ponto inicial (x, y) e tamanho (largura, altura) para preto transparente, apagando qualquer conteúdo desenhado anteriormente.
+
{{domxref("CanvasRenderingContext2D.fillRect()")}}
+
Desenha um retângulo preenchido na posição (x, y) com tamanho definido pela largura e altura
+
{{domxref("CanvasRenderingContext2D.strokeRect()")}}
+
Pinta um retângulo o qual possui um ponto inicial em (x, y) e possui um w width(largura) e um h height(altura) dentro da tela(canvas), usando o estilo de traçado(stroke) atual.
+
+ +

Desenhando Textos

+ +

Os métodos seguintes são fornecidos para desenhar texto. Veja também o objeto {{domxref("TextMetrics")}} para propriedades de texto.

+ +
+
{{domxref("CanvasRenderingContext2D.fillText()")}}
+
Desenha(preenche) um texto fornecido, em uma posição fornecida(x,y).
+
{{domxref("CanvasRenderingContext2D.strokeText()")}}
+
Desenha(traçados) um texto fornecido, em uma posição fornecida(x,y).
+
{{domxref("CanvasRenderingContext2D.measureText()")}}
+
Retorna um objeto {{domxref("TextMetrics")}} .
+
+ +

Estilos de linha

+ +

Os seguintes métodos e propriedades, controlam como as linhas são desenhadas.

+ +
+
{{domxref("CanvasRenderingContext2D.lineWidth")}}
+
Largura das linhas. Padrão: 1.0
+
{{domxref("CanvasRenderingContext2D.lineCap")}}
+
Tipos de pontas no final das linhas. Valores possíveis: butt (padrão), round, square.
+
{{domxref("CanvasRenderingContext2D.lineJoin")}}
+
Define o tipo de encontro entre duas linhas. Possíveis valores: round, bevel, miter (default).
+
{{domxref("CanvasRenderingContext2D.miterLimit")}}
+
Relação do limite de esquadria. Padrão: 10.
+
{{domxref("CanvasRenderingContext2D.getLineDash()")}}
+
Retorna a matriz de padrão de traço de linha atual contendo um número par de números não negativos.
+
{{domxref("CanvasRenderingContext2D.setLineDash()")}}
+
Define o padrão de traço de linha atual.
+
{{domxref("CanvasRenderingContext2D.lineDashOffset")}}
+
Especifica onde iniciar uma matriz de traços em uma linha.
+
+ +

Estilos de textos

+ +

As propriedades abaixo controlam a estilização do texto a ser apresentado:

+ +
+
{{domxref("CanvasRenderingContext2D.font")}}
+
Configuração da fonte. Valor padrão: 10px sans-serif.
+
{{domxref("CanvasRenderingContext2D.textAlign")}}
+
Alinhamento do texto. Possíveis valores: start (padrão), end, left, right or center.
+
{{domxref("CanvasRenderingContext2D.textBaseline")}}
+
Configuração de alinhamento da linha de base (Baseline). Possíveis valores: top, hanging, middle, alphabetic (padrão), ideographic, bottom.
+
{{domxref("CanvasRenderingContext2D.direction")}}
+
Direção do texto. Possívels valores: ltr, rtl, inherit (padrão).
+
+ +

Estilos de preenchimento e traço

+ +

O estilo de preenchimento é usado para cores e estilos dentro das formas e o estilo de traço é usado para as linhas ao redor das formas.

+ +
+
{{domxref("CanvasRenderingContext2D.fillStyle")}}
+
Cor ou estilo para usar formas internas. Padrão #000 (preto).
+
{{domxref("CanvasRenderingContext2D.strokeStyle")}}
+
Cor ou estilo a ser usado para as linhas em torno das formas. Padrão: #000 (preto).
+
+ +

Gradientes e padrões

+ +
+
{{domxref("CanvasRenderingContext2D.createLinearGradient()")}}
+
Cria um gradiente linear ao longo da linha fornecida pelas coordenadas representadas pelos parâmetros.
+
{{domxref("CanvasRenderingContext2D.createRadialGradient()")}}
+
Cria um gradiente radial dado pelas coordenadas dos dois círculos representados pelos parâmetros.
+
{{domxref("CanvasRenderingContext2D.createPattern()")}}
+
Cria um padrão usando a imagem especificada (uma {{domxref("CanvasImageSource")}}). Ele repete a fonte nas direções especificadas pelo argumento de repetição. Este método retorna um {{domxref("CanvasPattern")}}.
+
+ +

Sombras

+ +
+
{{domxref("CanvasRenderingContext2D.shadowBlur")}}.
+
Especifica o efeito de desfoque. Padrão: 0.
+
{{domxref("CanvasRenderingContext2D.shadowColor")}}
+
Cor da sombra. Padrão: fully-transparent black (preto totalmente transparente).
+
{{domxref("CanvasRenderingContext2D.shadowOffsetX")}}
+
Distância horizontal em que a sombra será deslocada. Padrão: 0.
+
{{domxref("CanvasRenderingContext2D.shadowOffsetY")}}
+
Distância vertical em que a sombra será deslocada. Padrão: 0.
+
+ +

Caminhos

+ +

Os seguintes métodos podem ser usados para manipular caminhos de desenhos.

+ +
+
{{domxref("CanvasRenderingContext2D.beginPath()")}}
+
Inicia um novo caminho esvaziando a lista de subcaminhos. Chame esse método quando você quiser criar um novo caminho.
+
{{domxref("CanvasRenderingContext2D.closePath()")}}
+
Faz com que a ponta da caneta se mova de volta para o início do subcaminho atual. Ele tenta traçar uma linha reta do ponto atual ao início. Se o desenho já foi fechado ou tem apenas um ponto, este método não faz nada.
+
{{domxref("CanvasRenderingContext2D.moveTo()")}}
+
Move o ponto inicial de um novo subcaminho para as coordenadas (x, y).
+
{{domxref("CanvasRenderingContext2D.lineTo()")}}
+
Conecta o último ponto do caminho atual com as coordenadas (x, y) com linha reta.
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo()")}}
+
Adiciona uma curva de Bézier ao caminho atual.
+
{{domxref("CanvasRenderingContext2D.quadraticCurveTo()")}}
+
Adiciona uma curva de Bézier quadrática ao caminho atual.
+
{{domxref("CanvasRenderingContext2D.arc()")}}
+
Adiciona um arco circular ao caminho atual.
+
{{domxref("CanvasRenderingContext2D.arcTo()")}}
+
Adiciona um arco no caminho atual com os pontos de controle e raio fornecidos, conectado ao ponto anterior por uma linha reta.
+
{{domxref("CanvasRenderingContext2D.ellipse()")}}
+
Adiciona um arco elíptico ao caminho atual.
+
{{domxref("CanvasRenderingContext2D.rect()")}}
+
Cria um caminho de retângulo na posição (x, y) com o tamanho determinado por width e height.
+
+ +

Drawing paths

+ +
+
{{domxref("CanvasRenderingContext2D.fill()")}}
+
Fills the subpaths with the current fill style.
+
{{domxref("CanvasRenderingContext2D.stroke()")}}
+
Strokes the subpaths with the current stroke style.
+
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}}
+
If a given element is focused, this method draws a focus ring around the current path.
+
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}}
+
Scrolls the current path or a given path into the view.
+
{{domxref("CanvasRenderingContext2D.clip()")}}
+
Creates a clipping path from the current sub-paths. Everything drawn after clip() is called appears inside the clipping path only. For an example, see Clipping paths in the Canvas tutorial.
+
{{domxref("CanvasRenderingContext2D.isPointInPath()")}}
+
Reports whether or not the specified point is contained in the current path.
+
{{domxref("CanvasRenderingContext2D.isPointInStroke()")}}
+
Reports whether or not the specified point is inside the area contained by the stroking of a path.
+
+ +

Transformações

+ +

Objects in the CanvasRenderingContext2D rendering context have a current transformation matrix and methods to manipulate it. The transformation matrix is applied when creating the current default path, painting text, shapes and {{domxref("Path2D")}} objects. The methods listed below remain for historical and compatibility reasons as {{domxref("SVGMatrix")}} objects are used in most parts of the API nowadays and will be used in the future instead.

+ +
+
{{domxref("CanvasRenderingContext2D.currentTransform")}}
+
Current transformation matrix ({{domxref("SVGMatrix")}} object).
+
{{domxref("CanvasRenderingContext2D.rotate()")}}
+
Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.
+
{{domxref("CanvasRenderingContext2D.scale()")}}
+
Adds a scaling transformation to the canvas units by x horizontally and by y vertically.
+
{{domxref("CanvasRenderingContext2D.translate()")}}
+
Adds a translation transformation by moving the canvas and its origin x horzontally and y vertically on the grid.
+
{{domxref("CanvasRenderingContext2D.transform()")}}
+
Multiplies the current transformation matrix with the matrix described by its arguments.
+
{{domxref("CanvasRenderingContext2D.setTransform()")}}
+
Resets the current transform to the identity matrix, and then invokes the transform() method with the same arguments.
+
{{domxref("CanvasRenderingContext2D.resetTransform()")}} {{experimental_inline}}
+
Resets the current transform by the identity matrix.
+
+ +

Compositing

+ +
+
{{domxref("CanvasRenderingContext2D.globalAlpha")}}
+
Alpha value that is applied to shapes and images before they are composited onto the canvas. Default 1.0 (opaque).
+
{{domxref("CanvasRenderingContext2D.globalCompositeOperation")}}
+
With globalAlpha applied this sets how shapes and images are drawn onto the existing bitmap.
+
+ +

Desenhando imagens

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage()")}}
+
Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.
+
+ +

Manipulação de pixels

+ +

See also the {{domxref("ImageData")}} object.

+ +
+
{{domxref("CanvasRenderingContext2D.createImageData()")}}
+
Creates a new, blank {{domxref("ImageData")}} object with the specified dimensions. All of the pixels in the new object are transparent black.
+
{{domxref("CanvasRenderingContext2D.getImageData()")}}
+
Returns an {{domxref("ImageData")}} object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at (sx, sy) and has an sw width and sh height.
+
{{domxref("CanvasRenderingContext2D.putImageData()")}}
+
Paints data from the given {{domxref("ImageData")}} object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.
+
+ +

Image smoothing

+ +
+
{{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} {{experimental_inline}}
+
Image smoothing mode; if disabled, images will not be smoothed if scaled.
+
+ +

The canvas state

+ +

The CanvasRenderingContext2D rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state:

+ +
+
{{domxref("CanvasRenderingContext2D.save()")}}
+
Saves the current drawing style state using a stack so you can revert any change you make to it using restore().
+
{{domxref("CanvasRenderingContext2D.restore()")}}
+
Restores the drawing style state to the last element on the 'state stack' saved by save().
+
{{domxref("CanvasRenderingContext2D.canvas")}}
+
A read-only back-reference to the {{domxref("HTMLCanvasElement")}}. Might be {{jsxref("null")}} if it is not associated with a {{HTMLElement("canvas")}} element.
+
+ +

Hit regions

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

Non-standard APIs

+ + + +

Most of these APIs are deprecated and will be removed in the future.

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.clearShadow()
+
Removes all shadow settings like {{domxref("CanvasRenderingContext2D.shadowColor")}} and {{domxref("CanvasRenderingContext2D.shadowBlur")}}.
+
{{non-standard_inline}} CanvasRenderingContext2D.drawImageFromRect()
+
This is redundant with an equivalent overload of drawImage.
+
{{non-standard_inline}} CanvasRenderingContext2D.setAlpha()
+
Use {{domxref("CanvasRenderingContext2D.globalAlpha")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setCompositeOperation()
+
Use {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setLineWidth()
+
Use {{domxref("CanvasRenderingContext2D.lineWidth")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setLineJoin()
+
Use {{domxref("CanvasRenderingContext2D.lineJoin")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setLineCap()
+
Use {{domxref("CanvasRenderingContext2D.lineCap")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setMiterLimit()
+
Use {{domxref("CanvasRenderingContext2D.miterLimit")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setStrokeColor()
+
Use {{domxref("CanvasRenderingContext2D.strokeStyle")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setFillColor()
+
Use {{domxref("CanvasRenderingContext2D.fillStyle")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setShadow()
+
Use {{domxref("CanvasRenderingContext2D.shadowColor")}} and {{domxref("CanvasRenderingContext2D.shadowBlur")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitLineDash
+
Use {{domxref("CanvasRenderingContext2D.getLineDash()")}} and {{domxref("CanvasRenderingContext2D.setLineDash()")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitLineDashOffset
+
Use {{domxref("CanvasRenderingContext2D.lineDashOffset")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitImageSmoothingEnabled
+
Use {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} instead.
+
+ + + +
+
{{non-standard_inline}} CanvasRenderingContext2D.getContextAttributes()
+
Inspired by the same WebGLRenderingContext method it returns an Canvas2DContextAttributes object that contains the attributes "storage" to indicate which storage is used ("persistent" by default) and the attribute "alpha" (true by default) to indicate that transparency is used in the canvas.
+
{{non-standard_inline}} CanvasRenderingContext2D.isContextLost()
+
Inspired by the same WebGLRenderingContext method it returns true if the Canvas context has been lost, or false if not.
+
+ +

WebKit only

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitBackingStorePixelRatio
+
The backing store size in relation to the canvas element. See High DPI Canvas.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitGetImageDataHD
+
Intended for HD backing stores, but removed from canvas specifications.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitPutImageDataHD
+
Intended for HD backing stores, but removed from canvas specifications.
+
+ +
+
+ +

Gecko only

+ +
+
{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.filter")}}
+
CSS and SVG filters as Canvas APIs. Likely to be standardized in a new version of the specification.
+
+ +

Prefixed APIs

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.mozCurrentTransform
+
Sets or gets the current transformation matrix, see {{domxref("CanvasRenderingContext2D.currentTransform")}}.  {{ gecko_minversion_inline("7.0") }}
+
{{non-standard_inline}} CanvasRenderingContext2D.mozCurrentTransformInverse
+
Sets or gets the current inversed transformation matrix.  {{ gecko_minversion_inline("7.0") }}
+
{{non-standard_inline}} CanvasRenderingContext2D.mozFillRule
+
The fill rule to use. This must be one of evenodd or nonzero (default).
+
{{non-standard_inline}} CanvasRenderingContext2D.mozImageSmoothingEnabled
+
See {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}}.
+
{{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozDash
+
An array which specifies the lengths of alternating dashes and gaps {{ gecko_minversion_inline("7.0") }}. Use {{domxref("CanvasRenderingContext2D.getLineDash()")}} and {{domxref("CanvasRenderingContext2D.setLineDash()")}} instead.
+
{{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozDashOffset
+
Specifies where to start a dash array on a line. {{ gecko_minversion_inline("7.0") }}. Use {{domxref("CanvasRenderingContext2D.lineDashOffset")}} instead.
+
{{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozTextStyle
+
Introduced in in Gecko 1.9, deprecated in favor of the {{domxref("CanvasRenderingContext2D.font")}} property.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozDrawText()
+
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0. Use {{domxref("CanvasRenderingContext2D.strokeText()")}} or {{domxref("CanvasRenderingContext2D.fillText()")}} instead.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozMeasureText()
+
This method was introduced in Gecko 1.9 and is unimplemented starting with Gecko 7.0. Use {{domxref("CanvasRenderingContext2D.measureText()")}} instead.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozPathText()
+
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozTextAlongPath()
+
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
+
+ +

Internal APIs (chrome-context only)

+ +
+
{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.asyncDrawXULElement()")}}
+
Renders a region of a XUL element into the canvas.
+
{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.drawWindow()")}}
+
Renders a region of a window into the canvas. The contents of the window's viewport are rendered, ignoring viewport clipping and scrolling.
+
{{non-standard_inline}} CanvasRenderingContext2D.demote()
+
This causes a context that is currently using a hardware-accelerated backend to fallback to a software one. All state should be preserved.
+
+ +

Internet Explorer

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.msFillRule
+
The fill rule to use. This must be one of evenodd or nonzero (default).
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#2dcontext:canvasrenderingcontext2d", "CanvasRenderingContext2D")}}{{Spec2('HTML WHATWG')}}
+ +

Compatibilidade do Navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1")}}{{CompatGeckoDesktop("1.8")}}{{CompatIE("9")}}{{CompatOpera("9")}}{{CompatSafari("2")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Compatibility notes

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/lineto/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/lineto/index.html new file mode 100644 index 0000000000..1876b469a8 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/lineto/index.html @@ -0,0 +1,176 @@ +--- +title: CanvasRenderingContext2D.lineTo() +slug: Web/API/CanvasRenderingContext2D/lineTo +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/lineTo +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.lineTo() da API Canvas 2D conecta o último ponto do sub-caminho (sub-path) para as coordenadas x, y, através de uma linha (mas na realidade não a desenha).

+ +

Sintaxe

+ +
void ctx.lineTo(x, y);
+
+ +

Parâmetros

+ +
+
x
+
O valor da coordenada x que indica o fim da linha.
+
y
+
O valor da coordenada y que indica o fim da linha.
+
+ +

Exemplos

+ +

Usando o método lineTo

+ +

sto é só um simples trecho de código que usa o método lineTo. Use o {{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}} para indicar o path onde será desenhada a linha, mova a caneta (pen) com {{domxref("CanvasRenderingContext.moveTo", "moveTo()")}} e use o método {{domxref("CanvasRenderingContext2D.stroke", "stroke()")}} para desenhar a linha.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(50, 50);
+ctx.lineTo(100, 100);
+ctx.stroke();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.moveTo(50,50);
+ctx.lineTo(100, 100);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-lineto", "CanvasRenderingContext2D.lineTo")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/moveto/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/moveto/index.html new file mode 100644 index 0000000000..137e4e2203 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/moveto/index.html @@ -0,0 +1,176 @@ +--- +title: CanvasRenderingContext2D.moveTo() +slug: Web/API/CanvasRenderingContext2D/moveTo +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/moveTo +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.moveTo() da API Canvas 2D move o ponto inicial de um novo sub-caminho (sub-path) para as coordenadas (x, y).

+ +

Sintaxe

+ +
void ctx.moveTo(x, y);
+
+ +

Parâmetros

+ +
+
x
+
O valor da coordenada x.
+
y
+
O valor da coordenada y.
+
+ +

Exemplos

+ +

Usando o método moveTo

+ +

Isto é só um simples trecho de código que usa o método moveTo para mover a caneta (pen) para um deteminado ponto onde vai iniciar o desenho.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(50, 50);
+ctx.lineTo(200, 50);
+ctx.stroke();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.moveTo(50,50);
+ctx.lineTo(200, 50);
+ctx.stroke()</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-moveto", "CanvasRenderingContext2D.moveTo")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/quadraticcurveto/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/quadraticcurveto/index.html new file mode 100644 index 0000000000..b60b7de07c --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/quadraticcurveto/index.html @@ -0,0 +1,182 @@ +--- +title: CanvasRenderingContext2D.quadraticCurveTo() +slug: Web/API/CanvasRenderingContext2D/quadraticCurveTo +translation_of: Web/API/CanvasRenderingContext2D/quadraticCurveTo +--- +
{{APIRef}}
+ +

o método CanvasRenderingContext2D.quadraticCurveTo() da API Canvas 2D adiciona uma Curva de Bézier quadrática ao caminho. São exigidos dois pontos. O primeiro ponto é um ponto de controle e o segundo é o ponto final. The starting point is the last point in the current path, which can be changed using moveTo() before creating the quadratic Bézier curve.

+ +

Sintaxe

+ +
void ctx.quadraticCurveTo(cpx, cpy, x, y);
+
+ +

Parâmetros

+ +
+
cpx
+
O eixo X da coordenada para o ponto de controle.
+
cpy
+
O eixo Y da coordenada para o ponto de controle.
+
x
+
O eixo X da coordenada para o ponto final.
+
y
+
O eixo Y da coordenada para o ponto final.
+
+ +

Exemplos

+ +

Usando o método quadraticCurveTo

+ +

This is just a simple code snippet drawing a quadratic bezier curve. The control point is red and the start and end points are blue.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(50,20);
+ctx.quadraticCurveTo(230, 30, 50, 100);
+ctx.stroke();
+
+ctx.fillStyle = 'blue';
+// start point
+ctx.fillRect(50, 20, 10, 10);
+// end point
+ctx.fillRect(50, 100, 10, 10);
+
+ctx.fillStyle = 'red';
+// control point
+ctx.fillRect(230, 30, 10, 10);
+ +

{{ EmbedLiveSample('Using_the_quadraticCurveTo_method', 315, 165) }}

+ +

Trying the quadraticCurveTo parameters

+ +

Edit the code below and see your changes update live in the canvas:

+ +
+
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.moveTo(50,20);
+ctx.quadraticCurveTo(230, 30, 50, 100);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Trying_the_quadraticCurveTo_parameters', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-quadraticcurveto", "CanvasRenderingContext2D.quadraticCurveTo")}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
{{CompatVersionUnknown}} + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
{{CompatVersionUnknown}} + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/rect/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/rect/index.html new file mode 100644 index 0000000000..6c19b38495 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/rect/index.html @@ -0,0 +1,177 @@ +--- +title: CanvasRenderingContext2D.rect() +slug: Web/API/CanvasRenderingContext2D/rect +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/rect +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.rect() da Canvas 2D API cria um path (trajeto) para um retângulo na posição (x, y), cujo tamanho é determinado pelo width (largura) e height (altura). Esses quatro pontos estão conectados por linhas retas e o sub-path (sub-trajeto) é marcado como fechado, para que você possa fill (preencher) ou stroke (contornar) o retângulo.

+ +

Sintaxe

+ +
void ctx.rect(x, y, width, height);
+
+ +

Parameters

+ +
+
x
+
O valor da coordenada x que indica ponto de início (superior esquerdo) do retângulo.
+
y
+
O valor da coordenada y que indica ponto de início (superior esquerdo) do retângulo.
+
width
+
A largura do retângulo.
+
height
+
A altura do retângulo.
+
+ +

Exemplos

+ +

Usando o método rect

+ +

Isto é somente um simples fragmentode código que usa o método rect para criar um path. Para verdadeiramente desenhar um path no canvas, você pode usar o método {{domxref("CanvasRenderingContext2D.fill", "fill()")}} ou o {{domxref("CanvasRenderingContext2D.stroke", "stroke()")}}. Veja também os métodos {{domxref("CanvasRenderingContext2D.fillRect", "fillRect()")}} e {{domxref("CanvasRenderingContext2D.strokeRect", "strokeRect()")}}, que podem fazer isto em um único passo.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+ctx.rect(10, 10, 100, 100);
+ctx.fill();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rect(10, 10, 100, 100);
+ctx.fill();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-rect", "CanvasRenderingContext2D.rect")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/stroke/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/stroke/index.html new file mode 100644 index 0000000000..866e317383 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/stroke/index.html @@ -0,0 +1,187 @@ +--- +title: CanvasRenderingContext2D.stroke() +slug: Web/API/CanvasRenderingContext2D/stroke +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/stroke +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.stroke() da API Canvas 2D contorna um dado path ou o path atual com o estilo atual de traçado usando uma regra de controle diferente de zero.

+ +

Sintaxe

+ +
void ctx.stroke();
+void ctx.stroke(path);
+
+ +

Parâmetros

+ +
+
path
+
Um path de {{domxref("Path2D")}} para contorno.
+
+ +

Exemplos

+ +

Usando o método stroke

+ +

Isto é só um simples trecho de código que usa o método stroke para contornar um path.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+ctx.rect(10, 10, 100, 100);
+ctx.stroke();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rect(10, 10, 100, 100);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-stroke", "CanvasRenderingContext2D.stroke")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Suporte para o parâmetro path{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(31) }}{{ CompatNo }}{{ CompatVersionUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Suporte para o parâmetro path{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile(31) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/strokerect/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/strokerect/index.html new file mode 100644 index 0000000000..e11812857f --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/strokerect/index.html @@ -0,0 +1,177 @@ +--- +title: CanvasRenderingContext2D.strokeRect() +slug: Web/API/CanvasRenderingContext2D/strokeRect +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/strokeRect +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.strokeRect() da API Canvas 2D desenha um retângulo na posição (x, y), que possui uma largura (width) w e uma altura (height) h, e não tem nenhum preenchimento (estilo stroke).

+ +

Sintaxe

+ +
void ctx.strokeRect(x, y, width, height);
+
+ +

Parâmetros

+ +
+
x
+
O valor da coordenada x para o ponto inicial do retângulo.
+
y
+
O valor da coordenada y para o ponto inicial do retângulo.
+
width
+
A largura do retângulo.
+
height
+
A altura do retângulo.
+
+ +

Exemplos

+ +

Usando o método strokeRect

+ +

Isto é só um simples trecho de código que usa o método strokeRect.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.strokeStyle = 'green';
+ctx.strokeRect(10, 10, 100, 100);
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.strokeStyle = "green";
+ctx.strokeRect(10, 10, 100, 100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-strokerect", "CanvasRenderingContext2D.strokeRect")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/characterdata/index.html b/files/pt-br/web/api/characterdata/index.html new file mode 100644 index 0000000000..8eb415f6e3 --- /dev/null +++ b/files/pt-br/web/api/characterdata/index.html @@ -0,0 +1,94 @@ +--- +title: CharacterData +slug: Web/API/CharacterData +translation_of: Web/API/CharacterData +--- +

{{APIRef("DOM")}}

+ +

A interface abstrata CharacterData  representa um objeto {{domxref("Node")}} que contém caracteres. Esta é uma interface abstrata, o que significa que não há nenhum objeto do tipo CharacterData: ela é implementada por outras interfaces, como {{domxref("Text")}}, {{domxref("Comment")}} ou {{domxref("ProcessingInstruction")}}, que não são abstratas.

+ +

{{InheritanceDiagram}}

+ +

Propriedades

+ +

Herda propriedades de seu pai, {{domxref("Node")}}, e implementa as interfaces {{domxref("ChildNode")}} e {{domxref("NonDocumentTypeChildNode")}}.

+ +
+
{{domxref("CharacterData.data")}}
+
É um {{domxref("DOMString")}} representando os dados textuais contidos neste objeto.
+
{{domxref("CharacterData.length")}} {{readonlyInline}}
+
Retorna um unsigned long representando o tamanho da string contida em CharacterData.data.
+
{{domxref("NonDocumentTypeChildNode.nextElementSibling")}} {{readonlyInline}}
+
Returns the {{domxref("Element")}} immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list.
+
{{domxref("NonDocumentTypeChildNode.previousElementSibling")}} {{readonlyInline}}
+
Returns the {{domxref("Element")}} immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list.
+
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("Node")}}, and implements the {{domxref("ChildNode")}} and {{domxref("NonDocumentTypeChildNode")}} interface.

+ +
+
{{domxref("CharacterData.appendData()")}}
+
Appends the given {{domxref("DOMString")}} to the CharacterData.data string; when this method returns, data contains the concatenated {{domxref("DOMString")}}.
+
{{domxref("CharacterData.deleteData()")}}
+
Removes the specified amount of characters, starting at the specified offset, from the CharacterData.data string; when this method returns, data contains the shortened {{domxref("DOMString")}}.
+
{{domxref("CharacterData.insertData()")}}
+
Inserts the specified characters, at the specified offset, in the CharacterData.data string; when this method returns, data contains the modified {{domxref("DOMString")}}.
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
Removes the object from its parent children list.
+
{{domxref("CharacterData.replaceData()")}}
+
Replaces the specified amount of characters, starting at the specified offset, with the specified {{domxref("DOMString")}}; when this method returns, data contains the modified {{domxref("DOMString")}}.
+
{{domxref("CharacterData.substringData()")}}
+
Returns a {{domxref("DOMString")}} containing the part of CharacterData.data of the specified length and starting at the specified offset.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#characterdata', 'CharacterData')}}{{Spec2('DOM WHATWG')}}Added implemention of the {{domxref("ChildNode")}} and {{domxref("NonDocumentTypeChildNode")}} interface.
{{SpecName('DOM3 Core', 'core.html#ID-FF21A306', 'CharacterData')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}.
{{SpecName('DOM2 Core', 'core.html#ID-FF21A306', 'CharacterData')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}.
{{SpecName('DOM1', 'level-one-core.html#ID-FF21A306', 'CharacterData')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ + + +

 

+ +

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

+ +

See also

+ +

 

+ + diff --git a/files/pt-br/web/api/childnode/after/index.html b/files/pt-br/web/api/childnode/after/index.html new file mode 100644 index 0000000000..8d8d40df47 --- /dev/null +++ b/files/pt-br/web/api/childnode/after/index.html @@ -0,0 +1,187 @@ +--- +title: ChildNode.after() +slug: Web/API/ChildNode/after +tags: + - API + - DOM + - Experimental + - Nó + - Referencia + - metodo +translation_of: Web/API/ChildNode/after +--- +
{{APIRef("DOM")}} {{SeeCompatTable}}
+ +

The ChildNode.after() method inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this ChildNode's parent, just after this ChildNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.

+ +

Sintaxe

+ +
[Throws, Unscopable]
+void ChildNode.after((Node or DOMString)... nodes);
+
+ +

Parâmetros

+ +
+
nós
+
A set of {{domxref("Node")}} or {{domxref("DOMString")}} objects to insert.
+
+ +

Exceções

+ + + +

Exemplos

+ +

Inserindo uum elemento

+ +
var parente = document.createElement("div");
+var filho = document.createElement("p");
+parente.appendChild(filho);
+var span = document.createElement("span");
+
+filho.after(span);
+
+console.log(parente.outerHTML);
+// "<div><p></p><span></span></div>"
+
+ +

Inserindo texto

+ +
var parente = document.createElement("div");
+var filho = document.createElement("p");
+parente.appendChild(filho);
+
+filho.after("Text");
+
+console.log(parente.outerHTML);
+// "<div><p></p>Text</div>"
+ +

Inserindo um elemento e um texto 

+ +
var parente = document.createElement("div");
+var filho = document.createElement("p");
+parente.appendChild(filho);
+var span = document.createElement("span");
+
+filho.after(span, "Text");
+
+console.log(parente.outerHTML);
+// "<div><p></p><span></span>Text</div>"
+ +

ChildNode.after() is unscopable

+ +

The after() method is not scoped into the with statement. Veja {{jsxref("Symbol.unscopables")}} para maior infomação.

+ +
with(node) {
+  after("foo");
+}
+// ReferenceError: after is not defined 
+ +

Polyfill

+ +

Você pode usar polyfill com  o método  after()  no Internet Explorer 9 e com o seguinte código:

+ +
//from: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/after()/after().md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('after')) {
+      return;
+    }
+    Object.defineProperty(item, 'after', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function after() {
+        var argArr = Array.prototype.slice.call(arguments),
+          docFrag = document.createDocumentFragment();
+
+        argArr.forEach(function (argItem) {
+          var isNode = argItem instanceof Node;
+          docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
+        });
+
+        this.parentNode.insertBefore(docFrag, this.nextSibling);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

 

+ +
//https://github.com/FabioVergani/js-Polyfill_Element.prototype.after/blob/master/after.js
+
+(function(x){
+ var o=x.prototype,p='after';
+ if(!o[p]){
+    o[p]=function(){
+     var e, m=arguments, l=m.length, i=0, t=this, p=t.parentNode, n=Node, s=String, d=document;
+     if(p!==null){
+        while(i<l){
+         e=m[i];
+         if(e instanceof n){
+            t=t.nextSibling;
+            if(t!==null){
+                p.insertBefore(e,t);
+            }else{
+                p.appendChild(e);
+            };
+         }else{
+            p.appendChild(d.createTextNode(s(e)));
+         };
+         ++i;
+        };
+     };
+    };
+ };
+})(Element);
+
+
+
+/*
+min:
+
+(function(x){
+ var o=x.prototype;
+ o.after||(o.after=function(){var e,m=arguments,l=m.length,i=0,t=this,p=t.parentNode,n=Node,s=String,d=document;if(p!==null){while(i<l){((e=m[i]) instanceof n)?(((t=t.nextSibling )!==null)?p.insertBefore(e,t):p.appendChild(e)):p.appendChild(d.createTextNode(s(e)));++i;}}});
+}(Element));
+
+*/
+
+ +

 

+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-childnode-after', 'ChildNode.after()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ + + + + +

{{Compat("api.ChildNode.after")}}

+ +

Veja mais

+ + diff --git a/files/pt-br/web/api/childnode/index.html b/files/pt-br/web/api/childnode/index.html new file mode 100644 index 0000000000..a5bb9c280c --- /dev/null +++ b/files/pt-br/web/api/childnode/index.html @@ -0,0 +1,78 @@ +--- +title: ChildNode +slug: Web/API/ChildNode +tags: + - API + - DOM + - Experimental + - Interface + - NeedsTranslation + - Node + - TopicStub +translation_of: Web/API/ChildNode +--- +
{{APIRef("DOM")}}
+ +
A interface ChildNode contém métodos que são particulares para os objetos
+ +

{{domxref("Node")}} que podem ter um pai.

+ +

ChildNode é uma interface bruta e nenhum objeto desse tipo pode ser criado; eles são implementados pelos objetos {{domxref("Element")}}, {{domxref("DocumentType")}}, e {{domxref("CharacterData")}}.

+ +

Propriedades

+ +

Não há propriedades herdadas nem específicas.

+ +

Métodos

+ +

Não há métodos herdados.

+ +
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
Removes this ChildNode from the children list of its parent.
+
{{domxref("ChildNode.before()")}} {{experimental_inline}}
+
Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this ChildNode's parent, just before this ChildNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
{{domxref("ChildNode.after()")}} {{experimental_inline}}
+
Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this ChildNode's parent, just after this ChildNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
{{domxref("ChildNode.replaceWith()")}} {{experimental_inline}}
+
Replaces this ChildNode in the children list of its parent with a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#interface-childnode', 'ChildNode')}}{{Spec2('DOM WHATWG')}}Split the ElementTraversal interface in {{domxref("ParentNode")}} and ChildNode. previousElementSibling and nextElementSibling are now defined on the latter. The {{domxref("CharacterData")}} and {{domxref("DocumentType")}} implemented the new interfaces. Added the remove(), before(), after() and replaceWith() methods.
{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}{{Spec2('Element Traversal')}}Added the initial definition of its properties to the ElementTraversal pure interface and use it on {{domxref("Element")}}.
+ +

Polyfill

+ +

External on github: childNode.js

+ +

Compatibilidade Com Navegadores

+ +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/childnode/remove/index.html b/files/pt-br/web/api/childnode/remove/index.html new file mode 100644 index 0000000000..98fba11b93 --- /dev/null +++ b/files/pt-br/web/api/childnode/remove/index.html @@ -0,0 +1,100 @@ +--- +title: ChildNode.remove() +slug: Web/API/ChildNode/remove +tags: + - API + - ChildNode + - DOM + - Experimental + - Método(2) + - remove +translation_of: Web/API/ChildNode/remove +--- +
{{APIRef("DOM")}}
+ +

O método ChildNode.remove() remove o objeto da árvore a que ele pertence.

+ +

Sintase

+ +
elementNodeReference.remove();
+
+ +

Exemplo

+ +

Usando remove()

+ +
<div id="div-01">Here is div-01</div>
+<div id="div-02">Here is div-02</div>
+<div id="div-03">Here is div-03</div>
+
+ +
var el = document.getElementById('div-01');
+el.nextElementSibling.remove(); // Remove o div com o id 'div-02'
+
+ +

ChildNode.remove() não tem escopo

+ +

O método remove() não tem escopo na função with. Veja {{jsxref("Symbol.unscopables")}} para mais informação.

+ +
with(node) {
+  remove();
+}
+// ReferenceError: remove is not defined 
+ +

Polyfill

+ +

Você pode evitar incompatibilidade ao usar o método remove() no Internet Explorer 9 em diante com o seguinte código:

+ +
// de: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('remove')) {
+      return;
+    }
+    Object.defineProperty(item, 'remove', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function remove() {
+        this.parentNode.removeChild(this);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName('DOM WHATWG', '#dom-childnode-remove', 'ChildNode.remove')}}{{Spec2('DOM WHATWG')}}Definição Inicial.
{{SpecName('DOM4', '#dom-childnode-remove', 'ChildNode.remove')}}{{Spec2('DOM4')}} 
+ +

Compatibilidade de navegadores

+ +
{{Compat("api.ChildNode.remove")}}
+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/clipboardevent/index.html b/files/pt-br/web/api/clipboardevent/index.html new file mode 100644 index 0000000000..ca14f4478f --- /dev/null +++ b/files/pt-br/web/api/clipboardevent/index.html @@ -0,0 +1,59 @@ +--- +title: ClipboardEvent +slug: Web/API/ClipboardEvent +translation_of: Web/API/ClipboardEvent +--- +

{{APIRef("Clipboard API")}} {{SeeCompatTable}}

+ +

A interface ClipboardEvent representa eventos correlatos à modificação da área de transferência, i. e., eventos de cortar ({{event("cut")}}), de copiar ({{event("copy")}}), e de colar ({{event("paste")}}).

+ +

Construtor

+ +
+
{{domxref("ClipboardEvent.ClipboardEvent", "ClipboardEvent()")}}
+
Cria um evento ClipboardEvent com os parâmetros fornecidos.
+
+ +

Propriedades

+ +

Ainda, propriedades herdadas de sua superclasse {{domxref("Event")}}.

+ +
+
{{domxref("ClipboardEvent.clipboardData")}} {{readonlyInline}}
+
é um objeto {{domxref("DataTransfer")}} contendo informação oriunda das operações de {{event("cut")}}, de {{event("copy")}}, ou de {{event("paste")}} iniciadas pelo usuário, juntamente com sua espécie/tipo MIME.
+
+ +

Methods

+ +

Não há método próprio; métodos herdados de {{domxref("Event")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Clipboard API', '#clipboard-event-interfaces', 'ClipboardEvent') }}{{ Spec2('Clipboard API') }}Definição inicial
+ + + + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/closeevent/closeevent/index.html b/files/pt-br/web/api/closeevent/closeevent/index.html new file mode 100644 index 0000000000..d5b7f088c0 --- /dev/null +++ b/files/pt-br/web/api/closeevent/closeevent/index.html @@ -0,0 +1,71 @@ +--- +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 uma nova instância {{domxref("CloseEvent")}}.

+ +

Sintaxe

+ +
var event = new CloseEvent(typeArg, closeEventInit);
+ +

Valores

+ +
+
typeArg
+
É uma {{domxref("DOMString")}} que representa o nome do evento.
+
closeEventInit {{optional_inline}}
+
+ +
+
É uma coleção CloseEventInit, que possui os seguintes campos: + +
    +
  • "wasClean", opcional e inicialmente de valor false, do tipo long, indica se uma conexão foi encerrada de forma limpa ou não.
  • +
  • "code", opcional e inicialmente de valor 0, do tipo unsigned short, este é o código de encerramento da conexão enviado pelo servidor.
  • +
  • "reason", opcional e inicialmente de valor '', do tipo {{domxref("DOMString")}}, esta é uma razão humanamente compreensível do porque o servidor encerrou a conexão.
  • +
+ +
+

A coleção CloseEventInit também aceita campos vindos da coleção {{domxref("Event.Event", "EventInit")}}.

+
+
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','comms.html#closeevent','CloseEvent()')}}{{Spec2('HTML WHATWG')}}Definição inicial
+ +

Compatibilidade de navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/closeevent/index.html b/files/pt-br/web/api/closeevent/index.html new file mode 100644 index 0000000000..94f718e8b2 --- /dev/null +++ b/files/pt-br/web/api/closeevent/index.html @@ -0,0 +1,239 @@ +--- +title: CloseEvent +slug: Web/API/CloseEvent +translation_of: Web/API/CloseEvent +--- +

{{APIRef("Websockets API")}}

+ +

Um CloseEvent é enviado aos clientes que usam {{Glossary("WebSockets")}} quando a conexão está fechada (closed). Ele é enviado ao ouvinte(listener) pelo atributo onclose do objeto WebSocket.

+ +

Construtor

+ +
+
{{domxref("CloseEvent.CloseEvent", "CloseEvent()")}}
+
Cria um CloseEvent novo.
+
+ +

Propriedades

+ +

Esta interface também herda as propriedades de seu objeto pai, {{domxref("Event")}}.

+ +
+
{{domxref("CloseEvent.code")}} {{readOnlyInline}}
+
Retorna um valor unsigned short contendo o código de encerramento enviado pelo servidor. Os seguintes valores são status de códigos permitidos. As definições seguintes são originadas da página da IANA [Ref]. Observe que os códigos 1xxx são exclusivamente Websockets internos e não para os mesmos propósitos dos dados enviados (como quando o protocolo da camada de aplicação é invalido). Os únicos códigos que permitem especificação no Firefox são o 1000 e do 3000 ao 4999 [Source, Bug]. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Código de StatusNomeDescrição
0999Reservado e não utilizado.
1000CLOSE_NORMALEncerramento normal. A conexão foi completada com sucesso sempre que o propósito para o qual ela foi criada tenha sido atingida.
1001CLOSE_GOING_AWAYO "endpoint" desapareceu, por causa de uma falha no servidor ou por que o navegador navegou para fora da página que abriu a conexão.
1002CLOSE_PROTOCOL_ERRORO "endpoint" finalizou a conexão devido a um erro de protocolo.
1003CLOSE_UNSUPPORTEDA conexão está sendo finalizada por causa de o dado do "endpoint" recebido ser de um tipo que não pode ser aceito (por exemplo, um "text-only endpoint" recebido como dado binário).
1004Reservado. Um significado pode ser definido futuramente.
1005CLOSE_NO_STATUSReservado.  Indica que um código "no status" foi fornecido mesmo que qualquer outro código seja esperado.
1006CLOSE_ABNORMALReservado. Usado para indicar que uma conexão foi fechada anormalmente (isto é, sem o "close frame" ter sido enviado) quando um "status code" é esperado.
1007Unsupported DataO "endpoint" está finalizando a conexão por causa da mensagem ter sido recebida com dados inconsistentes (por exemplo, dados que não estejam no padrão UTF-8, dentro de uma mensagem de texto).
1008Policy ViolationO "endpoint" está finalizando a conexão por causa dele ter recebido uma mensagem que viola sua política. Este é um código de status genérico, usado quando o código 1003 e o código 1009 não sejam adequados.
1009CLOSE_TOO_LARGEO "endpoint" está finalizando a conexão por causa de que o "data frame" recebido é muito grande.
1010Missing ExtensionO cliente está fechando a conexão por causa de que navegador espera o servidor negociar uma ou mais extensões esperadas, o servidor não responde corretamente.
1011Internal ErrorO servidor está finalizando uma conexão por causa de que ele encontrou uma condição inesperada que o impediu de cumprir a solicitação.
1012Service Restart +

O servidor está finalizando uma conexão por que ele está em processo de "restar". [Ref]

+
1013Try Again Later +

O servidor está finalizando a conexão devido a uma condição temporária, por exemplo, ele estar sobrecarregado e estar rejeitando alguns dos seus clientes. [Ref]

+
1014Reservado para o futuro uso de um padrão WebSocket.
1015TLS Handshake +

Reservado. Indica que a conexão foi fechada devido a uma falha para executar um " TLS handshake" (por exemplo, o certificado do servidor não pode ser verificado).

+
10161999Reservado para o futuro uso de um padrão WebSocket.
20002999Reservado para uso de "WebSocket extensions".
30003999 +

Disponível para uso de bibliotecas e frameworks. Não pode ser usado para aplicações. Disponível para registro em "IANA via first-come, first-serve".

+
40004999Disponível para uso em aplicações.
+
+
{{domxref("CloseEvent.reason")}} {{readOnlyInline}}
+
Retorna um {{domxref("DOMString")}} indicando a razão do porquê o servidor fechou uma conexão. Isto é especifico para um servidor e sub-protocolo particular.
+
{{domxref("CloseEvent.wasClean")}} {{readOnlyInline}}
+
Retorna um {{jsxref("Boolean")}} indicando se a conexão está ou não está claramente fechada.
+
+ +

Métodos

+ +

Esta interface também herda as propriedades de seu objeto pai, {{domxref("Event")}}.

+ +
+
{{domxref("CloseEvent.initCloseEvent()")}} {{Non-standard_inline}} {{Obsolete_inline}}
+
Inicializa o valor de um CloseEvent criado. Se o evento já tenha sido enviado, este método não realiza nada.  Não use este método mais, use o construtor {{domxref("CloseEvent.CloseEvent", "CloseEvent()")}} em vez disso.
+
+ +

Compatibilidade nos navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}[1]
+ {{CompatGeckoDesktop("12.0")}}[2]
10{{CompatUnknown}}{{CompatUnknown}}
initCloseEvent() {{Non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("8.0")}}
+ {{CompatNo}} 41.0
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("8.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
initCloseEvent() {{Non-standard_inline}}{{CompatNo}}{{CompatGeckoMobile("8.0")}}
+ {{CompatNo}} 41.0
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Anterior ao Gecko 8.0 {{geckoRelease("8.0")}}, o Gecko envia o evento WebSocket {{event("close")}}  ao ouvinte como um evento simples. O suporte para o CloseEvent foi implementado no Gecko 8.0.

+ +

[2] Anterior ao Gecko 12.0 {{geckoRelease("12.0")}}, o Gecko reportava o código de encerramento CLOSE_NORMAL quando o canal se fechava devido a um erro inesperado, ou se a condição de erro não era coberta pela especificação. Agora CLOSE_GOING_AWAY é reportado em seu lugar.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/console/assert/index.html b/files/pt-br/web/api/console/assert/index.html new file mode 100644 index 0000000000..571815d791 --- /dev/null +++ b/files/pt-br/web/api/console/assert/index.html @@ -0,0 +1,148 @@ +--- +title: Console.assert() +slug: Web/API/Console/assert +translation_of: Web/API/console/assert +--- +
{{APIRef("Console API")}}
+ +

Escreve uma mensagem de erro para o console se a afirmação é falsa. Se a firmação é verdadeira, nada acontece.

+ +

{{AvailableInWorkers}}

+ +
+

Note: O método console.assert() é implementado de forma diferente em Node.js.
+ Especificamente, em navegadores, chamando o método console.assert() com uma afirmação falsa fará com que a mensagem a ser impressa para o console não interrompa a execução do código subsequente. Em Node.js, no entanto, uma afirmação falsa causará um AssertionError.

+
+ +

Sintaxe

+ +
console.assert(afirmação, obj1 [, obj2, ..., objN]);
+console.assert(afirmação, msg [, subst1, ..., substN]); // c-mensagem de formatação
+
+ +

Parâmetros

+ +
+
afirmação
+
Qualquer expressão booleana. Se a afirmação é falsa, a mensagem é impressa no console.
+
obj1 ... objN
+
Uma lista de objetos JavaScript para escrever. As representações de strings de cada um desses objetos são acrescentados juntos na ordem dada e saída.
+
msg
+
Uma String que contém zero ou mais seguências de substituição.
+
subst1 ... substN
+
Objetos JavaScript com qual as strings de substituição msg serão substituidas. Isto dá um contriole adicional sobre a mensagem que será escrita.
+
+ +

Ver Outputting text to the console na documentação do {{domxref("console")}} para mais detalhes.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName("Console API", "#consoleassertexpression-object", "console.assert()")}}{{Spec2("Console API")}}Initial definition
+ +

Compatibilidade entre os navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+

Disponível para trabalhadores

+
{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
c-like message formatting{{CompatNo}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponível para trabalhadores{{CompatUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
c-like message formatting{{CompatUnknown}}{{CompatGeckoMobile("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/console/clear/index.html b/files/pt-br/web/api/console/clear/index.html new file mode 100644 index 0000000000..f7ae8df40f --- /dev/null +++ b/files/pt-br/web/api/console/clear/index.html @@ -0,0 +1,38 @@ +--- +title: console.clear() +slug: Web/API/Console/clear +translation_of: Web/API/Console/clear +--- +
{{APIRef("Console API")}}
+ +

O método console.clear() limpa o console, se o ambiente permitir.

+ +

Sintaxe

+ +
console.clear();
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#clear", "console.clear()")}}{{Spec2("Console API")}}Initial definition
+ +

Compatibilidade de Browser

+ + + +

{{Compat("api.Console.clear")}}

diff --git a/files/pt-br/web/api/console/count/index.html b/files/pt-br/web/api/console/count/index.html new file mode 100644 index 0000000000..b9328b5e91 --- /dev/null +++ b/files/pt-br/web/api/console/count/index.html @@ -0,0 +1,168 @@ +--- +title: Console.count() +slug: Web/API/Console/count +translation_of: Web/API/Console/count +--- +
{{APIRef("Console API")}}
+ +

Exibe o número de vezes em que a chamada count() em particular foi invocada. Essa função recebe um argumento opcional label.

+ +

{{AvailableInWorkers}}

+ +

Se label é fornecido, essa função exibe o número de vezes que a função count() foi chamada com a respectiva label.

+ +

Se label for omitido, a função exibe o número de vezes que a função count() foi chamada na respectiva linha.

+ +

Por exemplo, no código abaixo:

+ +
var usuario = "";
+
+function cumprimentar() {
+  console.count();
+  return "olá " + usuario;
+}
+
+usario = "bob";
+cumprimentar();
+usario = "alice";
+cumprimentar();
+cumprimentar();
+console.count();
+ +

A saída do console será algo como:

+ +
"<no label>: 1"
+"<no label>: 2"
+"<no label>: 3"
+"<no label>: 1"
+
+ +

Note a última linha da saída do console: a chamada individual de count() na linha 11 é tratada como um evento independente.

+ +

Se passarmos a variável usuario como o argumento label para a primeira invocação de count(), e a string "alice" para a segunda:

+ +
var usuario = "";
+
+function cumprimentar() {
+  console.count(usuario);
+  return "olá " + usuario;
+}
+
+usuario = "bob";
+cumprimentar();
+usuario = "alice";
+cumprimentar();
+cumprimentar();
+console.count("alice");
+ +

Teremos uma saída assim:

+ +
"bob: 1"
+"alice: 1"
+"alice: 2"
+"alice: 3"
+ +

Agora estamos mantendo contagens separadamente baseadas no valor de label. Como a label "alice" na linha 11 corresponde ao valor de usuario duas vezes, não é considerado um evento independente.

+ +

Sintaxe

+ +
console.count([label]);
+
+ +

Parâmetros

+ +
+
label
+
Uma string. Se for fornecida, exibe o número de vezes que  count() foi invocada com a mesma label.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Console API", "#count", "console.count()")}}{{Spec2("Console API")}}Definição inicial
+ +

Compatibilidade de browsers

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Disponível em workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponível em Workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/console/dir/index.html b/files/pt-br/web/api/console/dir/index.html new file mode 100644 index 0000000000..aa5c153903 --- /dev/null +++ b/files/pt-br/web/api/console/dir/index.html @@ -0,0 +1,108 @@ +--- +title: Console.dir() +slug: Web/API/Console/dir +tags: + - API + - console +translation_of: Web/API/Console/dir +--- +

{{ APIRef("Console API") }}{{Non-standard_header}}

+ +

Resumo

+ +

Exibe uma lista interativa das propriedades do objeto JavaScript especificado. A saída é apresentada como uma lista hierárquica com triângulos que permitem ver o conteúdo de objetos-filho.

+ +

{{AvailableInWorkers}}

+ +

console-dir.png

+ +

Sintaxe

+ +
console.dir(object);
+
+ +

Parâmetros

+ +
+
object
+
Um objeto JavaScript cujas propriedades devem ser emitidas.
+
+ +

Especificação

+ +

Console Object API

+ +

Compatibilidade do Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("8.0") }}9{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Disponível em trabalhos{{ CompatUnknown() }}{{ CompatGeckoDesktop("38.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("8.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Disponível em trabalhos{{ CompatUnknown() }}{{ CompatGeckoDesktop("38.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

 

+ +

Ver também

+ + diff --git a/files/pt-br/web/api/console/error/index.html b/files/pt-br/web/api/console/error/index.html new file mode 100644 index 0000000000..bf0ff45540 --- /dev/null +++ b/files/pt-br/web/api/console/error/index.html @@ -0,0 +1,160 @@ +--- +title: Console.error() +slug: Web/API/Console/error +translation_of: Web/API/Console/error +--- +
{{APIRef("Console API")}}{{Non-standard_header}}
+ +

'Escreve' uma mensagem de erro no  Web Console.

+ +

{{AvailableInWorkers}}

+ +

Sintaxe

+ +
console.error(obj1 [, obj2, ..., objN]);
+console.error(msg [, subst1, ..., substN]);
+console.exception(obj1 [, obj2, ..., objN]);
+console.exception(msg [, subst1, ..., substN]);
+
+ +
+

Nota: console.exception() é um alias para console.error(); as funcionalidades deles são identicas.

+
+ +

Parâmetros

+ +
+
obj1 ... objN
+
Uma lista de objetos Javascript para serem escritos. As representações String de cada um destes objetos é ligada junto na ordem listada e escrita.
+
msg
+
Uma String Javascript contendo zero ou mais Strings de substituição.
+
subst1 ... substN
+
Objetos JavaScript o qual substituirão as Strings no msg. Este parâmetro fornece controle adicional sobre o formato de output.
+
+ +

Veja Outputting text to the console na documentação de {{domxref("console")}} para mais detalhes.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Console API", "#consoleerrorobject--object-", "console.error()")}}{{Spec2("Console API")}}Initial definition
+ +

Compatibilidade com os navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Substituição de Strings{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
console.exception alias{{CompatNo}}{{CompatGeckoDesktop("28.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Disponível em workers{{CompatUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Substituição de Strings{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
console.exception alias{{CompatNo}}{{CompatGeckoMobile("28.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Disponível em workers{{CompatUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/console/index.html b/files/pt-br/web/api/console/index.html new file mode 100644 index 0000000000..c8d6331685 --- /dev/null +++ b/files/pt-br/web/api/console/index.html @@ -0,0 +1,242 @@ +--- +title: Console +slug: Web/API/Console +translation_of: Web/API/Console +--- +
+
{{APIRef("Console API")}}{{Non-standard_header}}
+
+ +

O objeto console fornece acesso ao console de debug do navegador (por exemplo, o Web Console do Firefox). O seu funcionamento específico varia de navegador para navegador, mas existe um conjunto de ferramentas que na prática são fornecidas normalmente.

+ +

Esta página documenta os {{anch("Métodos")}} disponíveis no objeto console e fornece alguns exemplos de {{anch("Uso")}}.

+ +

Métodos

+ +
+
{{domxref("console.assert()", "console.assert(expression, object[, object...])")}}
+
Emite uma mensagem e traça a sequência de operações até o primeiro argumento for falso.
+
{{domxref("console.count()", "console.count([label])")}}
+
Mostra o número de vezes que esta linha foi chamada com a label fornecida.
+
{{domxref("console.log()", "console.debug(object[, object...])")}} {{deprecated_inline("5.0")}}
+
Um atalho para log(); que foi adicionado para melhorar a compatibilidade de páginas já existentes que utilizavam debug(). Porém, ao invés destes comandos você deve utilizar {{domxref("console.log()")}}.
+
{{domxref("console.dir()", "console.dir(object)")}}
+
Exibe uma listagem interativa das propriedades de um objeto JavaScript especificado. Esta listagem permite a você expandir o objeto para visualizar o conteúdo de objetos filhos.
+
{{domxref("console.error()", "console.error(object[, object...])")}}
+
Emite uma mensagem de erro. Você pode usar substituição de string e outros argumentos adicionais com este método. Consulte {{anch("Uso de substituição de string")}}.
+
{{domxref("console.error()", "console.exception(object[, object...])")}}
+
Um atalho para error();
+
{{domxref("console.group()", "console.group(object[, object...])")}}
+
Cria um novo grupo em linha e recua todas as mensagens seguintes para um nível de indentação superior. Para voltar um nível, utilize groupEnd(). Consulte {{anch("Uso de grupos no console")}}.
+
{{domxref("console.groupCollapsed()", "console.groupCollapsed(object[, object...])")}}
+
Cria um novo grupo em linha e recua todas as mensagens seguintes para um nível de indentação superior; ao contrário de group(), o grupo em linha começa recolhido. Para revelar seu conteúdo, basta clicar no botão de revelação para expandí-lo. Para recuar um nível, utilize groupEnd(). Consulte {{anch("Uso de grupos no console")}}.
+
{{domxref("console.groupEnd()")}}
+
Sai do grupo em linha atual. Veja {{anch("Uso de grupos no console")}}.
+
{{domxref("console.info()", "console.info(object[, object...])")}}
+
Informações de registro. Você pode utilizar substituição de string e outros argumentos com este método. Consulte {{anch("Uso de substituição de string")}}.
+
{{domxref("console.log()", "console.log(object[, object...])")}}
+
Utilizado para a emissão de informações de registro em geral. Você pode utilizar substituição de string e outros argumentos com este método. Consulte {{anch("Uso de substituição de string")}}.
+
{{domxref("console.profile()", "console.profile( [profileLabel] )")}}
+
Inicia o JavaScript profiler. Você pode especificar qualquer label opcional para o perfil.
+
{{domxref("console.profileEnd()")}}
+
Interrompe o profiler. Você pode ver o profile resultante no JavaScript profiler.
+
+ +

 

+ +
+
{{domxref("Console.table()")}}
+
Exibe dados, como objeto e array, como uma tabela.
+
+ +

 

+ +
+
{{domxref("console.time()", "console.time(name)")}}
+
Inicia um contador de tempo com o nome especificado no parâmetro name. Até 10.000 contadores de tempo podem ser rodados por página.
+
{{domxref("console.timeEnd()", "console.timeEnd(name)")}}
+
Interrompe o contador de tempo especificado e emite o tempo e registros do contador de tempo em milisegundos desde o seu início. Veja {{anch("Contadores de Tempo")}}.
+
{{domxref("console.trace()")}}
+
Emite um traçado de pilha. See {{anch("Traçados de pilha")}}.
+
{{domxref("console.warn()", "console.warn(object[, object...])")}}
+
Emite uma mensagem de alerta. Você pode utilizar substituição de string e argumentos adicionais com este método. Veja {{anch("Uso de substituição de string")}}.
+
+ + +

Uso

+ +

Output de texto para o console

+ +

A utilização mais frequente do console é realizar o log de texto e de outros dados. Há quatro categorias de output que podem ser geradas, utilizando os métodos {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}} e o {{domxref("console.error()")}}. Cada um destes resultam em outputs que possuem estilos diferentes no log, e você pode utilizar os controles de filtragem fornecidos pelo navegador para ver apenas os outputs que lhe interessam.

+ +

Há duas maneiros da utilizar cada um dos métodos de outuput. Você pode simplemente passar uma lista dos objetos cuja representação em string será concatenadas em uma string e então realizar o output  para o console, ou você pode passar uma string contendo zero ou mais substituições de strings seguidas por uma lista de objetos para serem utilizados na substituição.

+ +

Output de um único objeto

+ +

A forma mais simples de utilizar os métodos de log é realizar o output de um único objeto:

+ +
var algumObjeto = { str: "Algum texto", id: 5 };
+console.log(algumObjeto);
+
+ +

O output vai se parecer como algo assim:

+ +
[09:27:13.475] ({str:"Algum texto", id:5})
+ +

Output de múltiplos objetos

+ +

Você também pode realizar o output de múltiplos objetos ao simplesmente listá-los ao chamar o método de log, desta forma:

+ +
var carro = "Fusca";
+var algumObjeto = {str:"Algum texto", id:5};
+console.info("Meu primeiro carro era um ", carro, ". O objeto é: ", algumObjeto);
+ +

O output será algo assim:

+ +
[09:28:22.711] Meu primeiro carro era um Fusca. O objeto é:  ({str:"Algum texto", id:5})
+
+ +

Uso de substituição de string

+ +

O Gecko 9.0 {{geckoRelease("9.0")}} introduziu o suporte à substituição de strings. Ao fornecer uma string para um dos métodos do console que aceitam uma string, você pode utilizar estas strings de substituição:

+ + + + + + + + + + + + + + + + + + + + + + + + +
String de substituiçãoDescrição
%oEmite um link para o objeto JavaScript. Clicar no link abre um inspetor.
%d ou %iEmite uma numero inteiro. A formatação ainda não possui suporte.
%sEmite uma string.
%fEmite um número de ponto flutuante. A formatação ainda não possui suporte.
+ +

Cada um destes puxam o próximo argumento na lista de parâmetros após a string fornecida inicialmente. Por exemplo:

+ +
for (var i=0; i<5; i++) {
+  console.log("Olá, %s. Você me chamou pela %dª vez.", "João", i+1);
+}
+
+ +

O output será algo assim:

+ +
[13:14:13.481] Olá, João. Você me chamou pela 1ª vez.
+[13:14:13.483] Olá, João. Você me chamou pela 2ª vez.
+[13:14:13.485] Olá, João. Você me chamou pela 3ª vez.
+[13:14:13.487] Olá, João. Você me chamou pela 4ª vez.
+[13:14:13.488] Olá, João. Você me chamou pela 5ª vez.
+
+ +

Estilizando o output no console

+ +

You can use the "%c" directive to apply a CSS style to console output:

+ +
console.log("%cMy stylish message", "color: red; font-style: italic");
+ +
+ +
{{h3_gecko_minversion("Using groups in the console", "9.0")}}
+ +

You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar, but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.

+ +
Note: Collapsed groups are not supported yet in Gecko; the groupCollapsed() method is the same as group() at this time.
+ +

To exit the current group, simply call console.groupEnd().

+ +

For example, given this code:

+ +
console.log("This is the outer level");
+console.group();
+console.log("Level 2");
+console.group();
+console.log("Level 3");
+console.warn("More of level 3");
+console.groupEnd();
+console.log("Back to level 2");
+console.groupEnd();
+console.debug("Back to the outer level");
+
+ +

The output looks like this:

+ +

nesting.png

+ +
{{h3_gecko_minversion("Timers", "10.0")}}
+ +

In order to calculate the duration of a specific operation, Gecko 10 introduced the support of timers in the console object. To start a timer, call the console.time() method, giving it a name as only parameter. To stop the timer, and to get the elapsed time in miliseconds, just call the console.timeEnd() method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.

+ +

For example, given this code:

+ +
console.time("answer time");
+alert("Click to continue");
+console.timeEnd("answer time");
+
+ +

will log the time needed by the user to discard the alert box:

+ +

timerresult.png

+ +

Notice that the timer's name is displayed both when the timer is started and when it's stopped.

+ +
Note: It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.
+ +

Stack traces

+ +

The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call {{domxref("console.trace()")}}. Given code like this:

+ +
foo();
+
+function foo() {
+  function bar() {
+    console.trace();
+  }
+  bar();
+}
+
+ +

The output in the console looks something like this:

+ +

+ +

Notes

+ + + +

See also

+ + + +

Other implementations

+ +

 

+ + diff --git a/files/pt-br/web/api/console/info/index.html b/files/pt-br/web/api/console/info/index.html new file mode 100644 index 0000000000..e4033e254d --- /dev/null +++ b/files/pt-br/web/api/console/info/index.html @@ -0,0 +1,154 @@ +--- +title: Console.info() +slug: Web/API/Console/info +translation_of: Web/API/Console/info +--- +
{{APIRef("Console API")}}{{Non-standard_header}}
+ +

Apresenta uma mensagem de saída no console do navegador . No Firefox e Chrome , um pequeno ícone "i" e apresentado próximo aos items do log do console .  

+ +

{{AvailableInWorkers}}

+ +

Sintaxe

+ +
console.info(obj1 [, obj2, ..., objN]);
+console.info(msg [, subst1, ..., substN]);
+
+ +

Parâmetros

+ +
+
obj1 ... objN
+
A lista de objetos javascript para saída . As representações de strings de cada um desses objetos são anexados juntos em ordem de listagem e saida . 
+
msg
+
Uma string javascript que contém zero ou mais strings para substituição.
+
subst1 ... substN
+
Objeto javascript o qual substitui strings com msg. Isso permite controle adicional sobre o formato da saída.
+
+ +

Veja Outputting text to the console na documentação {{domxref("console")}} para mais  detalhes.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentários
{{SpecName("Console API", "#consoleinfoobject--object-", "console.info()")}}{{Spec2("Console API")}}Definição inicial
+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Substituição de strings{{CompatUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Icones informação{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}
Disponível para trabalhadores{{CompatUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Substituição de  strings{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ + + + + + + +
Disponível para trabalhadores 
+
{{CompatUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja  também

+ + diff --git a/files/pt-br/web/api/console/log/index.html b/files/pt-br/web/api/console/log/index.html new file mode 100644 index 0000000000..b25a14a3fe --- /dev/null +++ b/files/pt-br/web/api/console/log/index.html @@ -0,0 +1,119 @@ +--- +title: Console.log() +slug: Web/API/Console/log +translation_of: Web/API/Console/log +--- +
{{APIRef("Console API")}}{{Non-standard_header}}
+ +

Sumário

+ +

Exibe uma mensagem na console do navegador.

+ +

Syntax

+ +
console.log(obj1[, obj2, ..., objN]);
+console.log(msg[, subst1, ..., substN]);
+
+ +

Parameters

+ +
+
obj1 ... objN
+
Uma lista de objetos JavaScript para exibir. A representação por escrito de cada um desses objetos é exibida na ordem com a qual foram inseridos na função.
+
msg
+
Uma string JavaScript com zero ou mais substituições.
+
subst1 ... substN
+
Strings ou objetos JavaScript para substituirem as marcações de substituição em msg. Estas substituições ocorrem de um para um e na ordem em que são passadas para a console.log.
+
+ +

Veja Exibindo texto na console na documentação do objeto {{domxref("console")}} para mais detalhes.

+ +

Especificação

+ +

Não faz parte de nenhuma especificação.

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Strings de substituição +

{{CompatVersionUnknown}}

+ +

{{CompatChrome(28)}}

+ +

%d - se um valor fracional negativo é passado, ele será arredondado para baixo, exemplo: -0,35 será arredondado para 1

+
{{CompatGeckoDesktop("9.0")}} +

10 - parcial

+ +

%c - não suportado
+ %d - irá renderizar como 0 quando NaN

+
{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Strings de substituição{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/console/table/index.html b/files/pt-br/web/api/console/table/index.html new file mode 100644 index 0000000000..946a642003 --- /dev/null +++ b/files/pt-br/web/api/console/table/index.html @@ -0,0 +1,143 @@ +--- +title: Console.table() +slug: Web/API/Console/table +translation_of: Web/API/Console/table +--- +
{{APIRef("Console API")}}
+ +

Exibe dados tabulares como uma tabela.

+ +

Essa função recebe um parâmetro obrigatório data, que deve ser um array ou um objeto, e um parametro opcional columns.

+ +

Registra data como uma tabela. Cada elemento no array (ou propriedade enumerável se data for um objeto) será uma linha na tabela.

+ +

A primeira coluna na tabela será rotulada (index). Se data for um array, seus valores serão os índices da matriz. Se data for um objeto, seus valores serão os nomes das propriedades. Observe que (no Firefox) o console.table está limitado a exibir 1000 linhas (a primeira linha é o índice rotulado).

+ +

{{AvailableInWorkers}}

+ +

Coleções de tipos primitivos

+ +

O argumento data pode ser um array ou um objeto.

+ +
// um array de strings
+
+console.table(["apples", "oranges", "bananas"]);
+ +

+ +
// um objeto cujas propriedades são strings
+
+function Person(firstName, lastName) {
+  this.firstName = firstName;
+  this.lastName = lastName;
+}
+
+var me = new Person("John", "Smith");
+
+console.table(me);
+ +

+ +

Coleções de tipos compostos

+ +

Se os elementos no array, ou propriedades no objeto, forem arrays ou objetos, seus elementos ou propriedades serão enumerados na linha, um por coluna:

+ +
// um array de arrays
+
+var people = [["John", "Smith"], ["Jane", "Doe"], ["Emily", "Jones"]]
+console.table(people);
+ +

Table displaying array of arrays

+ +
// um array de objetos
+
+function Person(firstName, lastName) {
+  this.firstName = firstName;
+  this.lastName = lastName;
+}
+
+var john = new Person("John", "Smith");
+var jane = new Person("Jane", "Doe");
+var emily = new Person("Emily", "Jones");
+
+console.table([john, jane, emily]);
+ +

Observe que, se a matriz contiver objetos, as colunas serão rotuladas com o nome da propriedade.

+ +

Table displaying array of objects

+ +
// um objeto cujas propriedades são objetos
+
+var family = {};
+
+family.mother = new Person("Jane", "Smith");
+family.father = new Person("John", "Smith");
+family.daughter = new Person("Emily", "Smith");
+
+console.table(family);
+ +

Table displaying object of objects

+ +

Restringindo as colunas exibidas

+ +

Por padrão, console.table() lista todos os elementos em cada linha. Você pode usar o parâmetro opcional columns para selecionar um subconjunto de colunas a serem exibidas:

+ +
// um array de objetos, registrando apenas firstName
+
+function Person(firstName, lastName) {
+  this.firstName = firstName;
+  this.lastName = lastName;
+}
+
+var john = new Person("John", "Smith");
+var jane = new Person("Jane", "Doe");
+var emily = new Person("Emily", "Jones");
+
+console.table([john, jane, emily], ["firstName"]);
+ +

Table displaying array of objects with filtered output

+ +

Classificando colunas

+ +

Você pode classificar a tabela por uma coluna específica clicando no rótulo dessa coluna.

+ +

Sintaxe

+ +
console.table(data [, columns]);
+
+ +

Parâmentros

+ +
+
data
+
Os dados a serem exibidos. Deve ser um array ou um objeto.
+
columns
+
Um array contendo os nomes das colunas para incluir na saída.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Console API", "#table", "console.table()")}}{{Spec2("Console API")}}Definição inicial
+ +

Compatibilidade de browsers

+ +
+ + +

{{Compat("api.Console.table")}}

+
diff --git a/files/pt-br/web/api/console/time/index.html b/files/pt-br/web/api/console/time/index.html new file mode 100644 index 0000000000..14b6f4a03c --- /dev/null +++ b/files/pt-br/web/api/console/time/index.html @@ -0,0 +1,103 @@ +--- +title: Console.time() +slug: Web/API/Console/time +translation_of: Web/API/Console/time +--- +

{{ APIRef("Console API") }}{{Non-standard_header}}

+ +

Sumário

+ +

Inicia um cronômetro que você pode usar para monitorar quanto tempo uma operação leva. Você dá para cada cronômetro um nome único, e deve ter no máximo 10.000 deles sendo executados na página. Quando você chama {{ domxref("console.timeEnd()") }} com o mesmo nome, o navegador mostrará o tempo, em milisegundos, que se passou desde que o cronômetro iniciou.

+ +

Veja Timers na documentação {{ domxref("console") }} para detalhes e exemplos.

+ +

{{AvailableInWorkers}}

+ +

Sintaxe

+ +
console.time(cronometroNome);
+
+ +

Parâmetros

+ +
+
cronometroNome
+
O nome para dar ao novo cronômetro. Ele identificará o cronômetro; use o mesmo quando chamar {{ domxref("console.timeEnd()") }} para parar o cronômetro e obter o tempo na saída do console.
+
+ +

Especificação

+ +

API do objeto Console

+ +

Compatibilidade com navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico2{{ CompatGeckoDesktop("10.0") }}11{{ CompatVersionUnknown() }}4.0
Disponível em Workers{{ CompatUnknown() }}{{ CompatGeckoDesktop("38.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("10.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Disponível em Workers{{ CompatUnknown() }}{{ CompatGeckoMobile("38.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/console/timeend/index.html b/files/pt-br/web/api/console/timeend/index.html new file mode 100644 index 0000000000..7ef63ea5bc --- /dev/null +++ b/files/pt-br/web/api/console/timeend/index.html @@ -0,0 +1,90 @@ +--- +title: Console.timeEnd() +slug: Web/API/Console/timeEnd +tags: + - Desenvolvimento Web + - metodo +translation_of: Web/API/Console/timeEnd +--- +
+
{{APIRef("Console API")}}{{Non-standard_header}}
+
+ +

Resumo

+ +

Interrompe um temporizador que foi anteriormente iniciado por uma chamada a {{domxref("console.time()")}}.

+ +

Veja Timers na documentação de {{domxref("console")}} para detalhes e exemplos.

+ +

Sintaxe

+ +
console.timeEnd(timerName);
+
+ +

Parametros

+ +
+
timerName
+
O nome do temporizador a ser interrompido. Uma vez interrompido, o tempo decorrido é automaticamente apresentado no Web Console.
+
+ +

Especificação

+ +

Não é parte de qualquer especificação.

+ +

Compatibilidade com navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support2{{CompatGeckoDesktop("10.0")}}11{{CompatVersionUnknown}}4.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("10.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/console/timestamp/index.html b/files/pt-br/web/api/console/timestamp/index.html new file mode 100644 index 0000000000..774ee4048b --- /dev/null +++ b/files/pt-br/web/api/console/timestamp/index.html @@ -0,0 +1,106 @@ +--- +title: Console.timeStamp() +slug: Web/API/Console/timeStamp +translation_of: Web/API/Console/timeStamp +--- +

{{ APIRef("Console API") }}{{Non-standard_header}}

+ +

Sumário

+ +

Adiciona um marcador simples para as ferramentas Timeline ou Waterfall do navegador. Ele deixa você relacionar um ponto no seu código com os outros eventos gravados na linha do tempo, como um evento de layout ou de pintura.

+ +

Opcionalmente, você pode fornecer um argumento como rótulo do carimbo de hora, e esse rótulo será então mostrado juntamente com a marcação.

+ +
+

Nota: essa funcionalidade está disponível em Web Workers.

+
+ +

Sintaxe

+ +
console.timeStamp(rotulo);
+
+ +

Parâmetros

+ +
+
rotulo
+
Rótulo para o carimbo de hora. Opcional.
+
+ +

Especificação

+ +

API do objeto Console

+ +

Compatibilidade com navegadores

+ +

{{ CompatibilityTable() }}

+ +
{{ CompatUnknown() }} + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Disponível em workers{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("38.0") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("10.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Disponível em workers{{ CompatUnknown() }}{{ CompatGeckoMobile("38.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/console/warn/index.html b/files/pt-br/web/api/console/warn/index.html new file mode 100644 index 0000000000..73eab6abee --- /dev/null +++ b/files/pt-br/web/api/console/warn/index.html @@ -0,0 +1,139 @@ +--- +title: Console.warn() +slug: Web/API/Console/warn +translation_of: Web/API/Console/warn +--- +
{{APIRef("Console API")}}{{non-standard_header}}
+ +

Escreve uma mensagem de alerta no Console Web.

+ +

{{AvailableInWorkers}}

+ +

{{Note("No Firefox, warnings têm um pequeno icone de ponto de exclamação perto deles no log do Console Web.")}}

+ +

Sintaxe

+ +
console.warn(obj1 [, obj2, ..., objN]);
+console.warn(msg [, subst1, ..., substN]);
+
+ +

Parâmetros

+ +
+
obj1 ... objN
+
Uma lista de objetos JavaScript para escrever. A representação String de cada um destes objetos é ligada junto na ordem listada e escrita.
+
msg
+
Uma string JavaScript contendo zero ou mais strings de substituição.
+
subst1 ... substN
+
Objetos JavaScript com qual as strings de substituição msg serão substituidas. Isto dá um contriole adicional sobre a mensagem que será escrita.
+
+ +

Ver Outputting text to the console na documentação do {{domxref("console")}} para mais detalhes.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Console API", "#consolewarnobject--object-", "console.warn()")}}{{Spec2("Console API")}}Definição inicial
+ +

Compatibilidade entre os navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Substituição strings{{CompatUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponível em workers{{CompatUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Substituição strings{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponível em workers{{CompatUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/console_api/index.html b/files/pt-br/web/api/console_api/index.html new file mode 100644 index 0000000000..560264eb23 --- /dev/null +++ b/files/pt-br/web/api/console_api/index.html @@ -0,0 +1,68 @@ +--- +title: Console API +slug: Web/API/Console_API +translation_of: Web/API/Console_API +--- +
{{DefaultAPISidebar("Console API")}}
+ +

O Console API  traz funcionalidades que permitem desenvolvedores realizar tarefas de debug, como registrar mensagens or os valores das variáveis em sertoes pontos do código, or cronometrar quanto tempo uma operação leva para concluir.

+ +

Conceitos e uso

+ +

O Console API começou como uma API proprietária, com diferentes navegadores a implementando.  A especificação do Console API foi criado para definir um comportamento consistente, e todos o navegadores atuais ventualmente foram implementando a funconalidade — Apsar de algumas implementações ainda terem funções adicionais proprietárias. Veja mais sobre isso em:

+ + + +

Uso é bastante simples — o objeto {{domxref("console")}} — disponível via {{domxref("window.console")}}, ou {{domxref("WorkerGlobalScope.console")}} em workers; acessível apenas usando console — contém vários métodos que você pode chamar para executar tarefas de depuração, geralmente focado no registro de vários valores no navegador Web Console.

+ +

De longe o método mais comum usado é o {{domxref("console.log")}}, que é usado para mostrar o valor atual contido em uma variável específica.

+ +

Interfaces

+ +
+
{{domxref("console")}}
+
Provides rudimentary debugging functionality, including logging, stack traces, timers, and counters.
+
+ +

Examples

+ +
let myString = 'Hello world';
+
+// Output "Hello world" to the console
+console.log(myString)
+ +

See the Console reference page for more examples.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/crypto/index.html b/files/pt-br/web/api/crypto/index.html new file mode 100644 index 0000000000..cc9a0214d1 --- /dev/null +++ b/files/pt-br/web/api/crypto/index.html @@ -0,0 +1,72 @@ +--- +title: Crypto +slug: Web/API/Crypto +tags: + - API + - Interface + - Referencia + - Web Crypto API +translation_of: Web/API/Crypto +--- +

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

+ +

A interface Crypto apresenta características de criptografia básica disponíveis no contexto atual. Isto permite acesso a um forte gerador criptográfico de números aleatórios e a criptografias primitivas.

+ +

Um objeto com essa interface está disponível no contexto web via propriedade {{domxref("Window.crypto")}} .

+ +

Propriedades

+ +

Esta interface implementa propriedades definidas em {{domxref("RandomSource")}}.

+ +
+
{{domxref("Crypto.subtle")}} {{experimental_inline}}{{readOnlyInline}}
+
Retorna um objeto {{domxref("SubtleCrypto")}} provendo acesso a criptografias primitivas comuns, como hashing, signing, encryption ou decryption.
+
+ +

Métodos

+ +

Esta interface implementa métodos definidos em {{domxref("RandomSource")}}.

+ +
+
{{domxref("RandomSource.getRandomValues()")}}
+
Preenche a {{ jsxref("TypedArray") }} com valores criptografados aleatórios.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Web Crypto API", "#crypto-interface", "Crypto")}}{{Spec2("Web Crypto API")}}Definição inicial.
+ +

Compatibilidade de Browser

+ + + +

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

+ +
 
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/crypto/subtle/index.html b/files/pt-br/web/api/crypto/subtle/index.html new file mode 100644 index 0000000000..caf7e0d4f0 --- /dev/null +++ b/files/pt-br/web/api/crypto/subtle/index.html @@ -0,0 +1,51 @@ +--- +title: Crypto.subtle +slug: Web/API/Crypto/subtle +tags: + - API + - Criptografía + - Propriedade + - Read-only + - Referencia + - Web Crypto API +translation_of: Web/API/Crypto/subtle +--- +

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

+ +

A prorpiedade Crypto.subtle de apenas leitura retorna como objeto {{domxref("SubtleCrypto")}} permitindo exercer operações de criptografia.

+ +

Sintaxe

+ +
var crypto = crypto.subtle;
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-Crypto', 'Crypto.subtle') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ + + +

{{Compat("api.Crypto.subtle")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/cryptokey/algorithm/index.html b/files/pt-br/web/api/cryptokey/algorithm/index.html new file mode 100644 index 0000000000..ab2440f6b6 --- /dev/null +++ b/files/pt-br/web/api/cryptokey/algorithm/index.html @@ -0,0 +1,112 @@ +--- +title: CryptoKey.algorithm +slug: Web/API/CryptoKey/algorithm +tags: + - API + - CryptoKey + - Propriedade + - Read-only + - Referencia + - Web Crypto API +translation_of: Web/API/CryptoKey +--- +

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

+ +

A propriedade CryptoKey.algorithm de apenas leitura é um valor opaco contendo todas as informações sobre o algoritmo relacionado à key.

+ +

Implementações diferentes tem diferentes tipos de valores opacos para os mesmos: tal objeto não pode ser compartilhado.

+ +

Sintaxe

+ +
result = key.algorithm
+
+ +

Valor de retorno

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-CryptoKey-algorithm', 'CryptoKey.algorithm') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}37{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +

Veja também

+ + + +

Dicionário

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/cryptokey/extractable/index.html b/files/pt-br/web/api/cryptokey/extractable/index.html new file mode 100644 index 0000000000..6ff8bde9c7 --- /dev/null +++ b/files/pt-br/web/api/cryptokey/extractable/index.html @@ -0,0 +1,110 @@ +--- +title: CryptoKey.extractable +slug: Web/API/CryptoKey/extractable +tags: + - API + - CryptoKey + - Propriedade + - Read-only + - Referencia + - Web Crypto API +translation_of: Web/API/CryptoKey +--- +

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

+ +

A propriedade de apenas leitura CryptoKey.extractable que indica se a key bruta do material pode ser extraída, para por exemplo arquivá-la.

+ +

Sintaxe

+ +
result = key.extractable
+
+ +

Valor de retorno

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-CryptoKey-extractable', 'CryptoKey.extractable') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}37{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +

Veja também

+ + + +

Dicionário

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/cryptokey/index.html b/files/pt-br/web/api/cryptokey/index.html new file mode 100644 index 0000000000..e532bba078 --- /dev/null +++ b/files/pt-br/web/api/cryptokey/index.html @@ -0,0 +1,120 @@ +--- +title: CryptoKey +slug: Web/API/CryptoKey +tags: + - API + - Chaves Criptografadas + - Interface + - Referencia + - Web Crypto API +translation_of: Web/API/CryptoKey +--- +

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

+ +

A interface CryptoKey representa uma {{glossary("key")}} criptografada derivada de uma key de algoritmo definido.

+ +

Um objeto CryptoKey pode ser obtido utilizando {{domxref("SubtleCrypto.generateKey()")}}, {{domxref("SubtleCrypto.deriveKey()")}} ou {{domxref("SubtleCrypto.importKey()")}}

+ +

Propriedades

+ +

Esta interface não herda nehunha propriedade.

+ +
+
{{domxref("CryptoKey.type")}}
+
Retorna um valor enumerado representando o tipo da key, uma key secreta (para algoritmos simétricos), uma key pública ou privada (para algoritmos assimétricos).
+
{{domxref("CryptoKey.extractable")}}
+
Retorna um {{jsxref("Boolean")}} indicando se a informação bruta pode ser exportada para a aplicação ou não.
+
{{domxref("CryptoKey.algorithm")}}
+
Retorna um objeto opaco representando uma cifra em particular que deve ser utilizada com a key.
+
{{domxref("CryptoKey.usages")}}
+
Retorna uma matriz de valores enumerados indicando onde a key pode ser utilizada.
+
+ +

Métodos

+ +

Esta interface não herda, nem implementa nenhum método.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-CryptoKey', 'CryptoKey') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade com o Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico.{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico.37{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+ +

 

+
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/cryptokey/type/index.html b/files/pt-br/web/api/cryptokey/type/index.html new file mode 100644 index 0000000000..6a1bc1703e --- /dev/null +++ b/files/pt-br/web/api/cryptokey/type/index.html @@ -0,0 +1,117 @@ +--- +title: CryptoKey.type +slug: Web/API/CryptoKey/type +tags: + - API + - Apenas Leitura + - CryptoKey + - Propriedades + - Referencia + - Web Crypto API +translation_of: Web/API/CryptoKey +--- +

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

+ +

CryptoKey.type é uma propriedade de apenas leitura que indica o tipo de key: se for uma key para um algoritmo simétrico ("secret") ou, para um algoritmo assimétrico, ("public" ou "private", dependendo do seu propósito).

+ +

Sintaxe

+ +
result = key.type
+
+ +

Valor de retorno

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{ SpecName('Web Crypto API', '#dfn-CryptoKey-type', 'CryptoKey.type') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}37{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/cryptokey/usages/index.html b/files/pt-br/web/api/cryptokey/usages/index.html new file mode 100644 index 0000000000..ba51dbaa0f --- /dev/null +++ b/files/pt-br/web/api/cryptokey/usages/index.html @@ -0,0 +1,123 @@ +--- +title: CryptoKey.usages +slug: Web/API/CryptoKey/usages +tags: + - API + - CryptoKey + - Propriedade + - Read-only + - Referencia + - Web Crypto API +translation_of: Web/API/CryptoKey +--- +

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

+ +

A propriedade de apenas leitura CryptoKey.usages é um conjunto enumerado que indica os propósitos da key.

+ +

Possíveis valores são:

+ + + +

Sintaxe

+ +
result = key.usages
+
+ +

Valor de retorno

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-CryptoKey-usages', 'CryptoKey.usages') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}37{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/css/index.html b/files/pt-br/web/api/css/index.html new file mode 100644 index 0000000000..9e7e83f1d2 --- /dev/null +++ b/files/pt-br/web/api/css/index.html @@ -0,0 +1,136 @@ +--- +title: CSS +slug: Web/API/CSS +tags: + - Apps + - CSSOM + - Referencia +translation_of: Web/API/CSS +--- +
{{APIRef("CSSOM")}}
+ +

A interface CSS carrega métodos CSS-relacionados úteis. Nenhum objeto com essa interface foi implementado: Aqui só contém métodos estáticos e futuramente uma interface útil.

+ +

Propriedades

+ +

A interface CSS é a interface utilizada e nenhum objeto desse tipo pode ser criado: só métodos estáticos são definidos aqui.

+ +

Métodos

+ +

A interface CSS é a interface utilizada e nenhum objeto desse tipo pode ser criado: só métodos estáticos são definidos aqui.

+ +

Métodos státicos

+ +

Nenhuma método estático herdado.

+ +
+
{{domxref("CSS.supports()")}}
+
Retorna um {{domxref("Boolean")}} indicando se o par property-value, ou a condição dada do parâmetro é suportada.
+
+ +
+
{{domxref("CSS.escape()")}} {{experimental_inline}}
+
Pode ser usado para escapar um string mais usado como parte de um seletor CSS.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesEstadoComentário
{{SpecName('CSSOM', '#the-css.escape%28%29-method', 'CSS')}}{{Spec2('CSSOM')}}Adicionado o   escape() método estático.
{{SpecName('CSS3 Conditional', '#the-css-interface', 'CSS')}}{{Spec2('CSS3 Conditional')}}Definição inicial.
+ +

Compatibilidade com os Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support28.0{{CompatGeckoDesktop("22.0")}} [1]6.012.1{{CompatNo}}
escape(){{experimental_inline}}46.0{{CompatGeckoDesktop("31.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("22.0")}}[1]{{CompatNo}}12.1{{CompatNo}}
escape(){{experimental_inline}}{{CompatNo}}{{CompatGeckoMobile("31.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Também disponível através do layout.css.supports-rule.enabled preferência desde Gecko 20.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/css_object_model/index.html b/files/pt-br/web/api/css_object_model/index.html new file mode 100644 index 0000000000..df8709c400 --- /dev/null +++ b/files/pt-br/web/api/css_object_model/index.html @@ -0,0 +1,133 @@ +--- +title: CSS Object Model +slug: Web/API/CSS_Object_Model +tags: + - API + - CSSOM + - Referencia +translation_of: Web/API/CSS_Object_Model +--- +

{{DefaultAPISidebar('CSSOM')}}

+ +

O CSS Object Model é um conjunto de APIs que permite manipular o CSS através do JavaScript. Isto depende do DOM e da HTML APIs. Com isto é permitido a leitura e a modificação dos estilos CSS dinamicamente.

+ +

Referências

+ +
+ +
+ +

Outras interfaces podem ser usadas com  CSSOM:

+ +

{{domxref("Document")}}, {{domxref("Window")}}, {{domxref("Element")}}, {{domxref("HTMLElement")}}, {{domxref("HTMLImageElement")}}, {{domxref("Range")}}, {{domxref("MouseEvent")}}, and {{domxref("SVGElement")}}.

+ +

Tutoriais

+ + + +

Especificações

+ +

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSSOM")}}{{Spec2("CSSOM")}} 
{{SpecName("CSSOM View")}}{{Spec2("CSSOM View")}} 
{{SpecName("Screen Orientation")}}{{Spec2("Screen Orientation")}} 
{{SpecName("CSS3 Fonts")}}{{Spec2("CSS3 Fonts")}} 
{{SpecName("CSS3 Animations")}}{{Spec2("CSS3 Animations")}} 
{{SpecName("CSS3 Transitions")}}{{Spec2("CSS3 Transitions")}} 
{{SpecName("CSS3 Variables")}}{{Spec2("CSS3 Variables")}} 
{{SpecName("CSS3 Conditional")}}{{Spec2("CSS3 Conditional")}} 
{{SpecName("CSS3 Device")}}{{Spec2("CSS3 Device")}} 
{{SpecName("CSS3 Counter Styles")}}{{Spec2("CSS3 Counter Styles")}} 
+ +

Notas de compatibilidade do navegador

+ +

Todos esses recursos foram adicionados pouco a pouco ao logo dos anos para os diferentes navegadores: Foi um processo bastante complexo que não podem ser sintetizados em uma simples tabela. Por favor, pesquise por uma interface específica e sua disponibilidade.

diff --git a/files/pt-br/web/api/customelementregistry/index.html b/files/pt-br/web/api/customelementregistry/index.html new file mode 100644 index 0000000000..b1e3be4458 --- /dev/null +++ b/files/pt-br/web/api/customelementregistry/index.html @@ -0,0 +1,93 @@ +--- +title: CustomElementRegistry +slug: Web/API/CustomElementRegistry +translation_of: Web/API/CustomElementRegistry +--- +

{{DefaultAPISidebar("Web Components")}}

+ +

A interface CustomElementRegistry provê métodos para registro de elementos customizados e busca de elementos registrados. Para instancia-lo, use a propriedade {{domxref("window.customElements")}}. 

+ +

Métodos

+ +
+
{{domxref("CustomElementRegistry.define()")}}
+
Define um novo elemento customizado.
+
{{domxref("CustomElementRegistry.get()")}}
+
Retorna o construtor do nome do elemento informado, ou undefined caso não tenha sido definido.
+
{{domxref("CustomElementRegistry.whenDefined()")}}
+
Retorna um {{jsxref("Promise", "promise")}} vazio que é resolvido quando o elemento customizado é inserido. Se o elemento já foi definido, o retorno ja é informado.
+
+ +

Exemplos

+ +

O código a seguir foi pego do nosso word-count-web-component exemplo (veja em ação). Perceba que usamos o método {{domxref("CustomElementRegistry.define()")}} para definir um elemento customizado.

+ +
// Cria uma classe para o elemento
+class WordCount extends HTMLParagraphElement {
+  constructor() {
+    // Sempre execute primeiro o método super
+    super();
+
+    // Conta as palavras no elemento pai
+    var wcParent = this.parentNode;
+
+    function countWords(node){
+      var text = node.innerText || node.textContent
+      return text.split(/\s+/g).length;
+    }
+
+    var count = 'Words: ' + countWords(wcParent);
+
+    // Cria um shadow root
+    var shadow = this.attachShadow({mode: 'open'});
+
+    // Cria um nó de texto e adiciona o contador de palavra nele
+    var text = document.createElement('span');
+    text.textContent = count;
+
+    // Acrescenta ao shadow root
+    shadow.appendChild(text);
+
+
+    // Atualiza o contador quando houver mudança
+    setInterval(function() {
+      var count = 'Words: ' + countWords(wcParent);
+      text.textContent = count;
+    }, 200)
+
+  }
+}
+
+// Define um novo elemento
+customElements.define('word-count', WordCount, { extends: 'p' });
+ +
+

Note: The CustomElementsRegistry is available through the {{domxref("Window.customElements")}} property.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "custom-elements.html#customelementregistry", "CustomElementRegistry")}}{{Spec2("HTML WHATWG")}}Definição inicial
+ +

Compatibilidade de navegadores

+ +

 

+ + + +

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

+ +

 

diff --git a/files/pt-br/web/api/datatransfer/index.html b/files/pt-br/web/api/datatransfer/index.html new file mode 100644 index 0000000000..96358c84d0 --- /dev/null +++ b/files/pt-br/web/api/datatransfer/index.html @@ -0,0 +1,383 @@ +--- +title: DataTransfer +slug: Web/API/DataTransfer +translation_of: Web/API/DataTransfer +--- +
{{APIRef("HTML DOM")}}
+ +

{{ gecko_minversion_header("1.9") }} O objeto DataTransfer é usado para guardar os dados que estão sendo arrastados durante uma operação de Drag e Drop (arrastar e soltar). Ele pode guardar um ou mais itens de dados, cada um de um ou mais tipos de dados. Para mais informações sobre drag e drop (arrastar e soltar), veja Drag and Drop.

+ +

Esse objeto está disponível pela propriedade dataTransfer de todos os eventos de drag. Ele não pode ser criado separadamente.

+ +

Visão geral das propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadesTipo
dropEffectString
effectAllowedString
files {{ gecko_minversion_inline("1.9.2") }}{{ domxref("FileList") }}
mozCursor {{ non-standard_inline() }} {{ gecko_minversion_inline("1.9.1") }}String
mozItemCount {{ non-standard_inline() }}unsigned long
mozSourceNode {{ non-standard_inline() }} {{ gecko_minversion_inline("2") }}{{ domxref("Node") }}
mozUserCancelledBoolean
typesDOMStringList
+ +

Visão geral dos métodos

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void addElement(in Element element)
void clearData([in String type])
String getData(in String type)
void setData(in String type, in String data)
void setDragImage(in nsIDOMElement image, in long x, in long y)
void mozClearDataAt([in String type, in unsigned long index])
nsIVariant mozGetDataAt(in String type, in unsigned long index)
void mozSetDataAt(in String type, in nsIVariant data, in unsigned long index)
StringList mozTypesAt([in unsigned long index])
+ +

Propriedades

+ +

dropEffect

+ +

O efeito atual que será usado, e deve sempre ser um dos possíveis valores de effectAllowed. Isso afetará qual cursor será exibido enquanto arrasta.

+ +

Para os eventos dragenter e dragover, o dropEffect será inicializado com base na ação que o usuário está solicitando. Como isso é determinado é específico da plataforma, mas, normalmente o usuário pode pressionar teclas de modificação, como a tecla alt, para ajustar qual ação é desejada. Com um manipulador de evento para os eventos dragenter e dragover, o dropEffect deverá ser modificado se a ação desejada é diferente da ação que o usuário está solicitando.

+ +

Para os eventos dragstart, drag, e dragleave, o dropEffect será inicializado como "none". Qualquer valor atribuído à dropEffect será definido, mas o valor não será usado para nada.

+ +

Para os eventos drop e dragend, o dropEffect será inicializado para a ação que foi desejada, que será o valor que o dropEffect tinha depois do último evento de dragenter ou dragover. Em um evento de dragend, por exemplo, se a o dropEffect desejado for "move", então os dados que estão sendo arrastados deverão ser removidos da origem.

+ +

Valores possíveis:

+ + + +

Atribuindo qualquer outro valor não terá efeito e o valor antigo será mantido.

+ +

effectAllowed

+ +

Especifica os efeitos que são permitidos para esse drag. Você pode definir isso no evento dragstart para definir os efeitos desejados para a origem. Com os eventos dragenter e dragover, o effectAllowed será definido para qualquer que seja o valor que foi atribuído durante o evento dragstart. Isso pode ser usado para determinar quais efeitos são permitidos. Atribuindo um valor para effectAllowed nos outros eventos, exceto dragstart, não terá efeito.

+ +

Valores possíveis:

+ + + +

Atribuindo qualquer outro valor não terá efeito e permanece o valor anterior.

+ +

files

+ +

{{ gecko_minversion_header("1.9.2") }}

+ +

Contains a list of all the local files available on the data transfer. If the drag operation doesn't involve dragging files, this property is an empty list. An invalid index access on the {{ domxref("FileList") }} specified by this property will return undefined.

+ +

Example

+ +

These examples dump the list of files dragged into the browser window.

+ + + +

types

+ +

Guarda uma lista dos tipos de formato dos dados que estão armazenados para o primeiro ítem, na mesma ordem que os dados foram adicionados. Uma lista vazia será retornada caso nenhum dado tenha sido adicionado.

+ +

{{ gecko_minversion_note("1.9.2", 'A string "Files" é incluída nessa lista se houverem arquivos sendo arrastados.') }}

+ +

{{ h3_gecko_minversion("mozCursor", "1.9.1", "mozCursor") }}

+ +

O estado do cursor de drag. Isto é usado principalmente para controlar o cursor durante a guia de drag.

+ +
Nota: Esse método está atualmente implementado somento no Windows.
+ +

Valores possíveis

+ +
+
auto
+
Utiliza o comportamento padrão do sistema.
+
default
+
Utiliza o comportamento padrão Gecko, que é definir o cursor para uma seta durante a operação de arrastar.
+
+ +
Nota: Se você especificar qualquer valor diferente de "default", "auto" é assumido.
+ +

mozItemCount

+ +

O número de ítens sendo arrastados.

+ +
Nota: Essa propriedade é específica Gecko.
+ +

mozSourceNode

+ +

{{ gecko_minversion_header("2") }}

+ +

O {{ domxref("Node") }} sobre o qual o cursor do mouse estava localizado quando o botão foi pressionado para iniciar a operação de arrastar. O valor é null para drags externos ou se o elmento não pode acessar o node.

+ +
Nota: Essa propriedade é específica Gecko.
+ +

mozUserCancelled

+ +

Essa propriedade é aplicada apenas no evento dragend, e é true se o usuário cancelar a operação de arrastar pressionando escape (esc). Será false em qualquer outro caso, incluindo se a operação de arrastar falhar por algum motivo, por exemplo devido a ação de soltar em um local inválido.

+ +
Nota: Essa propriedade é específica Gecko.
+ +

Methods

+ +

addElement()

+ +

Set the drag source. Usually you would not change this, but it will affect which node the drag and dragend events are fired at. The default target is the node that was dragged.

+ +
 void addElement(
+   in Element element
+ );
+
+ +
Parameters
+ +
+
element
+
The element to add.
+
+ +

clearData()

+ +

Remove the data associated with a given type. The type argument is optional. If the type is empty or not specified, the data associated with all types is removed. If data for the specified type does not exist, or the data transfer contains no data, this method will have no effect.

+ +
 void clearData(
+   [optional] in String type
+ );
+
+ +
Parameters
+ +
+
type
+
The type of data to remove.
+
+ +

getData()

+ +

Retrieves the data for a given type, or an empty string if data for that type does not exist or the data transfer contains no data.

+ +

A security error will occur if you attempt to retrieve data during a drag that was set from a different domain, or the caller would otherwise not have access to. This data will only be available once a drop occurs during the drop event.

+ +
 String getData(
+   in String type
+ );
+
+ +
Parameters
+ +
+
type
+
The type of data to retrieve.
+
+ +

setData()

+ +

Set the data for a given type. If data for the type does not exist, it is added at the end, such that the last item in the types list will be the new format. If data for the type already exists, the existing data is replaced in the same position. That is, the order of the types list is not changed when replacing data of the same type.

+ +
 void setData(
+   in String type,
+   in String data
+ );
+
+ +
Parameters
+ +
+
type
+
The type of data to add.
+
data
+
The data to add.
+
+ +

setDragImage()

+ +

Set the image to be used for dragging if a custom one is desired. Most of the time, this would not be set, as a default image is created from the node that was dragged.

+ +

If the node is an HTML img element, an HTML canvas element or a XUL image element, the image data is used. Otherwise, image should be a visible node and the drag image will be created from this. If image is null, any custom drag image is cleared and the default is used instead.

+ +

The coordinates specify the offset into the image where the mouse cursor should be. To center the image, for instance, use values that are half the width and height of the image.

+ +
 void setDragImage(
+   in Element image,
+   in long x,
+   in long y
+ );
+
+ +
Parameters
+ +
+
image
+
An element to use as the drag feedback image
+
x
+
Horizontal offset within the image.
+
y
+
Vertical offset within the image.
+
+ +

mozClearDataAt()

+ +

Removes the data associated with the given format for an item at the specified index. The index is in the range from zero to the number of items minus one.

+ +

If the last format for the item is removed, the entire item is removed, reducing mozItemCount by one.

+ +

If the format list is empty, then the data associated with all formats is removed. If the format is not found, then this method has no effect.

+ +
Note: This method is Gecko-specific.
+ +
 void mozClearDataAt(
+   [optional] in String type,
+   in unsigned long index
+ );
+
+ +
Parameters
+ +
+
type
+
The type of data to remove.
+
index
+
The index of the data to remove.
+
+ +

mozGetDataAt()

+ +

Retrieves the data associated with the given format for an item at the specified index, or null if it does not exist. The index should be in the range from zero to the number of items minus one.

+ +
Note: This method is Gecko-specific.
+ +
 nsIVariant mozGetDataAt(
+   [optional] in String type,
+   in unsigned long index
+ );
+
+ +
Parameters
+ +
+
type
+
The type of data to retrieve.
+
index
+
The index of the data to retrieve.
+
+ +

mozSetDataAt()

+ +

A data transfer may store multiple items, each at a given zero-based index. mozSetDataAt() may only be called with an index argument less than mozItemCount in which case an existing item is modified, or equal to mozItemCount in which case a new item is added, and the mozItemCount is incremented by one.

+ +

Data should be added in order of preference, with the most specific format added first and the least specific format added last. If data of the given format already exists, it is replaced in the same position as the old data.

+ +

The data should be either a string, a primitive boolean or number type (which will be converted into a string) or an {{ interface("nsISupports") }}.

+ +
Note: This method is Gecko-specific.
+ +
 void mozSetDataAt(
+   [optional] in String type,
+   in nsIVariant data,
+   in unsigned long index
+ );
+
+ +
Parameters
+ +
+
type
+
The type of data to add.
+
data
+
The data to add.
+
index
+
The index of the data to add.
+
+ +

mozTypesAt()

+ +

Holds a list of the format types of the data that is stored for an item at the specified index. If the index is not in the range from 0 to the number of items minus one, an empty string list is returned.

+ +
Note: This method is Gecko-specific.
+ +
 nsIVariant mozTypesAt(
+   in unsigned long index
+ );
+
+ +
Parameters
+ +
+
index
+
The index of the data for which to retrieve the types.
+
+ +

See also

+ +

Drag and Drop

+ +

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

diff --git a/files/pt-br/web/api/deviceacceleration/index.html b/files/pt-br/web/api/deviceacceleration/index.html new file mode 100644 index 0000000000..7f46e75436 --- /dev/null +++ b/files/pt-br/web/api/deviceacceleration/index.html @@ -0,0 +1,42 @@ +--- +title: DeviceAcceleration +slug: Web/API/DeviceAcceleration +tags: + - API + - Experimental + - Interface +translation_of: Web/API/DeviceMotionEventAcceleration +--- +
{{ ApiRef("Device Orientation Events") }}{{SeeCompatTable}}
+ +

Um objeto DeviceAcceleration fornece informações sobre a quantidade de aceleração que o dispositivo desempenha ao longo dos três eixos.

+ +

Propriedades

+ +
+
{{domxref("DeviceAcceleration.x")}} {{readonlyInline}}
+
A quantidade de aceleração ao longo do eixo X. Somente leitura.
+
{{domxref("DeviceAcceleration.y")}} {{readonlyInline}}
+
A quantidade de aceleração ao longo do eixo Y. Somente leitura.
+
{{domxref("DeviceAcceleration.z")}} {{readonlyInline}}
+
A quantidade de aceleração ao longo do eixo Z.Somente leitura.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentario
{{SpecName("Device Orientation", "#device_acceleration", "DeviceAcceleration")}}{{Spec2("Device Orientation")}}Definição inicial
diff --git a/files/pt-br/web/api/devicerotationrate/index.html b/files/pt-br/web/api/devicerotationrate/index.html new file mode 100644 index 0000000000..bce9a29495 --- /dev/null +++ b/files/pt-br/web/api/devicerotationrate/index.html @@ -0,0 +1,92 @@ +--- +title: DeviceRotationRate +slug: Web/API/DeviceRotationRate +translation_of: Web/API/DeviceMotionEventRotationRate +--- +

{{ ApiRef("Device Orientation Events") }} {{SeeCompatTable}}

+ +

Um objeto DeviceRotationRate fornece informações sobre a taxa na qual o dispositivo está girando em torno de todos os três eixos.

+ +

Properties

+ +
+
{{ domxref("DeviceRotationRate.alpha") }} {{readonlyInline}}
+
A quantidade de rotação em torno do eixo Z, em graus por segundo.
+
{{ domxref("DeviceRotationRate.beta") }} {{readonlyInline}}
+
A quantidade de rotação em torno do eixo Y, em graus por segundo
+
{{ domxref("DeviceRotationRate.gamma") }} {{readonlyInline}}
+
A quantidade de rotação em torno do eixo X, em graus por segundo
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificacõesStatusComentario
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Definição inicial.
+ + + +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/devicestorage.get/index.html b/files/pt-br/web/api/devicestorage.get/index.html new file mode 100644 index 0000000000..9258c4da29 --- /dev/null +++ b/files/pt-br/web/api/devicestorage.get/index.html @@ -0,0 +1,58 @@ +--- +title: DeviceStorage.get +slug: Web/API/DeviceStorage.get +tags: + - API + - B2G + - Device Storage + - Firefox OS + - Method + - Non Standard + - Non-standard + - Não Padrão + - Reference + - Referencia + - WebAPI + - metodo +translation_of: Archive/B2G_OS/API/DeviceStorage/get +--- +

{{ non-standard_header() }}

+

{{ B2GOnlyHeader2('privileged') }}

+

Sumário

+

O metodo get é usado para obter um arquivo somente-leitura de uma dada área de armazenamento.

+

Caso o pedido seja bem-sucedido, o resultado do pedido result é um objeto {{domxref("File")}} contendo os dados do arquivo original do dispositivo.

+

Sintaxe

+
var instanciaDeDOMRequest = instanciaDeDeviceStorage.get(nomeDoArquivo);
+

Parametros

+
+
+ nomeDoArquivo
+
+ Uma string representando o nome completo (caminho + nome do arquivo) do arquivo a ser obtido.
+
+

Retorno

+

Retorna um objeto {{domxref("DOMRequest")}} para manipular o sucesso ou o erro da operação.

+

Exemplo

+
var sdcard = navigator.getDeviceStorage("sdcard");
+
+var pedido = sdcard.get("meuArquivo.txt");
+
+pedido.onsuccess = function () {
+  var name = this.result.name;
+  console.log('O arquivo "' + name + '" foi obtido com sucesso da área de armazenamento do sdcard');
+}
+
+request.onerror = function () {
+  console.warn('Nao foi possivel obter o arquivo: ' + this.error);
+}
+
+

Especificação

+

Não é parte de nenhuma especificação.

+

Veja também

+ diff --git a/files/pt-br/web/api/devicestorage.onchange/index.html b/files/pt-br/web/api/devicestorage.onchange/index.html new file mode 100644 index 0000000000..1b1b1db375 --- /dev/null +++ b/files/pt-br/web/api/devicestorage.onchange/index.html @@ -0,0 +1,30 @@ +--- +title: DeviceStorage.onchange +slug: Web/API/DeviceStorage.onchange +translation_of: Archive/B2G_OS/API/DeviceStorage/onchange +--- +

{{ ApiRef() }}

+

{{ non-standard_header() }}

+

{{ B2GOnlyHeader2('privileged') }}

+

Resumo

+

A propriedade onchange é usado para especificar um manuseador de eventos para receber eventos {{event("change")}}. Estes eventos são disparados cada vez que um arquivo é criado, modificado ou excluído na area de armazenamento.

+

Sintaxe

+
instanceOfDeviceStorage.onchange = funcRef
+

Onde funcRef é uma função para ser chamada quando o evento {{event("change")}} ocorre. Estes eventos são do tipo {{domxref("DeviceStorageChangeEvent")}}.

+

Exemplo

+
var sdcard = navigator.getDeviceStorage('sdcard');
+
+sdcard.onchange = function (change) {
+  var reason = change.reason;
+  var path   = change.path;
+
+  console.log('O arquivo "' + path + '" foi ' + reason);
+}
+

Especificação

+

Não faz parte de qualquer especificação.

+

Veja também

+ diff --git a/files/pt-br/web/api/document/activeelement/index.html b/files/pt-br/web/api/document/activeelement/index.html new file mode 100644 index 0000000000..c29692eaf3 --- /dev/null +++ b/files/pt-br/web/api/document/activeelement/index.html @@ -0,0 +1,164 @@ +--- +title: Document.activeElement +slug: Web/API/Document/activeElement +tags: + - API + - Document + - HTML DOM + - Property + - Reference +translation_of: Web/API/DocumentOrShadowRoot/activeElement +--- +

{{APIRef("DOM")}}

+ +

Retorna o {{ domxref("Element", "elemento") }} atualmente em foco, ou seja, o elemento que receberá os eventos do teclado caso o usuário digite algo. Esse atributo é somente-leitura.

+ +

Geralmente retorna um {{ HTMLElement("input") }} ou {{ HTMLElement("textarea") }}, caso esteja com uma seleção de texto ativa. Caso esteja, pode obter mais informações sobre a seleção utilizando as propriedades selectionStartselectionEnd. Caso o elemento em foco seja um {{ HTMLElement("select") }}(menu) ou {{ HTMLElement("input") }} do tipo button, checkbox ou radio.

+ +
Note: No Mac, elementos que nao sejam campos de texto geralmente não recebem foco.
+ +

Normalmente o usuário pode navegar entre os elementos que pode receber foco na página com o uso da tecla tab e ativar estes elementos com a tecla espaço (apertar um botão ou selecionar uma opção).

+ +

Não confunda foco com uma seleção de texto no documento, que consiste em sua maioria de nódos de texto estáticos. Veja {{ domxref("window.getSelection()") }}.

+ +

Quando não há nada selecionado, o activeElement da página é o {{ HTMLElement("body") }} ou null

+ +
+

Este atributo é parte da seção "Em desenvolvimento" da especificação do HTML 5.

+
+ +

Sintaxe

+ +
var curElement = document.activeElement;
+
+ +

Exemplo

+ +
<!DOCTYPE HTML>
+<html>
+<head>
+    <script type="text/javascript" charset="utf-8">
+    function init() {
+
+        function onMouseUp(e) {
+            console.log(e);
+            var outputElement = document.getElementById('output-element');
+            var outputText = document.getElementById('output-text');
+            var selectedTextArea = document.activeElement;
+            var selection = selectedTextArea.value.substring(
+            selectedTextArea.selectionStart, selectedTextArea.selectionEnd);
+            outputElement.innerHTML = selectedTextArea.id;
+            outputText.innerHTML = selection;
+        }
+
+        document.getElementById("ta-example-one").addEventListener("mouseup", onMouseUp, false);
+        document.getElementById("ta-example-two").addEventListener("mouseup", onMouseUp, false);
+    }
+    </script>
+</head>
+<body onload="init()">
+<div>
+    Select some text from one of the Textareas below:
+</div>
+<form id="frm-example" action="#" accept-charset="utf-8">
+<textarea name="ta-example-one" id="ta-example-one" rows="8" cols="40">
+This is Textarea Example One:
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui.
+</textarea>
+<textarea name="ta-example-two" id="ta-example-two" rows="8" cols="40">
+This is Textarea Example Two:
+Fusce ullamcorper, nisl ac porttitor adipiscing, urna orci egestas libero, ut accumsan orci lacus laoreet diam. Morbi sed euismod diam.
+</textarea>
+</form>
+Active Element Id: <span id="output-element"></span><br/>
+Selected Text: <span id="output-text"></span>
+
+</body>
+</html>
+
+ +

View on JSFiddle

+ +

Notas

+ +

Originalmente apresentada como extensão DOM proprietária no Internet Explorer 4, esta propriedade também é suportada no Opera e Safari (versão 4 ou maior)

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#dom-document-activeelement', 'activeElement')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade nos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23.04 [1]9.64.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1]: O IE9 tem um bug que ao tentar acessar o activeElement do {{domxref("window.parent")}} {{domxref("Document")}} de um {{HTMLElement("iframe")}}(i.e. parent.document.activeElement) é lançado um erro

+ +

Eventos relacionados

+ + diff --git a/files/pt-br/web/api/document/alinkcolor/index.html b/files/pt-br/web/api/document/alinkcolor/index.html new file mode 100644 index 0000000000..85d2bfaa77 --- /dev/null +++ b/files/pt-br/web/api/document/alinkcolor/index.html @@ -0,0 +1,36 @@ +--- +title: Document.alinkColor +slug: Web/API/Document/alinkColor +tags: + - Depreciado + - Propriedade + - Referencia +translation_of: Web/API/Document/alinkColor +--- +
{{APIRef("DOM")}}{{Deprecated_header}}
+ +

Retorna ou define a cor de um link ativo no corpo do documento. Um link está ativo durante o tempo entre os eventos mousedown e mouseup.

+ +

Sintaxe

+ +
var color = document.alinkColor;
+document.alinkColor = color;
+
+ +

color é uma string que contém o nome da cor (e.g., blue, darkblue, etc.) ou o valor hexadecimal da cor (e.g., #0000FF)

+ +

Notas

+ +

O valor padrão para esta propriedade no Mozilla Firefox é vermelho (#ee0000 em hexadecimal).

+ +

document.alinkColor está obsoleto em DOM Level 2 HTML. Uma alternativa é o seletor de CSS {{Cssxref(":active")}}.

+ +

Outra alternativa é document.body.aLink, embora tenha sido depreciado no HTML 4.01 a favor da alternativa CSS.

+ +

Gecko suporta ambos alinkColor/:active e {{Cssxref(":focus")}}. Suporte para Internet Explorer 6 e 7 alinkColor/:active apenas para HTML anchor (<a>) links e o comportamento é o mesmo que :focus sob Gecko. Não há suporte para :focus no IE.

+ +

Compatibilidade do navegador

+ + + +

{{Compat("api.Document.alinkColor")}}

diff --git a/files/pt-br/web/api/document/anchors/index.html b/files/pt-br/web/api/document/anchors/index.html new file mode 100644 index 0000000000..624c955b0e --- /dev/null +++ b/files/pt-br/web/api/document/anchors/index.html @@ -0,0 +1,107 @@ +--- +title: Document.anchors +slug: Web/API/Document/anchors +tags: + - API + - Deprecated + - HTML DOM + - NeedsCompatTable + - Property + - Reference +translation_of: Web/API/Document/anchors +--- +
{{APIRef("DOM")}}
+ +

{{deprecated_header("HTML5")}}

+ +

anchors retorna uma lista de todas as âncoras no documento.

+ +

Sintaxe

+ +
nodeList = document.anchors;
+
+ +

Exemplo

+ +
if ( document.anchors.length >= 5 ) {
+  dump("dump found too many anchors");
+  window.location = "http://www.google.com";
+}
+
+ +

O código a seguir é um exemplo que popula automaticamente um índice de conteúdo com cada âncora encontrada na página:

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8" />
+<title>Test</title>
+<script>
+function init() {
+  var toc = document.getElementById("toc");
+  var i, li, newAnchor;
+  for (i = 0; i < document.anchors.length; i++) {
+    li = document.createElement("li");
+    newAnchor = document.createElement('a');
+    newAnchor.href = "#" + document.anchors[i].name;
+    newAnchor.innerHTML = document.anchors[i].text;
+    li.appendChild(newAnchor);
+    toc.appendChild(li);
+  }
+}
+</script>
+
+</head>
+<body onload="init()">
+
+<h1>Title</h1>
+<h2><a name="contents">Contents</a></h2>
+<ul id="toc"></ul>
+
+<h2><a name="plants">Plants</a></h2>
+<ol>
+    <li>Apples</li>
+    <li>Oranges</li>
+    <li>Pears</li>
+</ol>
+
+<h2><a name="veggies">Veggies</a></h2>
+<ol>
+    <li>Carrots</li>
+    <li>Celery</li>
+    <li>Beats</li>
+</ol>
+
+</body>
+</html>
+
+ +

View on JSFiddle

+ +

Notas

+ +

Por motivos de compatibilidade, o conjunto de âncoras retornadas por anchors contém apenas as âncoras criadas com o atributo name, não incluindo as âncoras criadas com o atributo {{ htmlattrxref("id") }}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-anchors', 'Document.anchors')}}{{ Spec2('HTML WHATWG') }}Obsoleted.
{{SpecName('DOM2 HTML', 'html.html#ID-7577272', 'Document.anchors')}}{{ Spec2('DOM2 Events') }}Initial definition.
diff --git a/files/pt-br/web/api/document/bgcolor/index.html b/files/pt-br/web/api/document/bgcolor/index.html new file mode 100644 index 0000000000..66ec8d48ca --- /dev/null +++ b/files/pt-br/web/api/document/bgcolor/index.html @@ -0,0 +1,35 @@ +--- +title: Document.bgColor +slug: Web/API/Document/bgColor +tags: + - Obsoleto + - Propriedade + - Referencia +translation_of: Web/API/Document/bgColor +--- +

{{APIRef("DOM")}} {{ Deprecated_header() }}

+ +

A propriedade obsoleta bgColor obtém ou atribue a cor de fundo do documento atual.

+ +

Sintaxe

+ +
color = document.bgColor
+document.bgColor = color
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
document.bgColor = "darkblue";
+
+ +

Notas

+ +

O valor padrão para esta propriedade no Firefox é branco (#ffffff em hexadecimal).

+ +

document.bgColor está obsoleto no DOM Level 2 HTML. A alternativa recomendada é fazer uso do atributo CSS {{Cssxref("background-color")}} que pode ser acessado através do DOM com document.body.style.backgroundColor. Uma outra alternativa é o document.body.bgColor, apesar dessa também estar obsoleta no HTML 4.01 em funcão da alternativa do CSS.

diff --git a/files/pt-br/web/api/document/body/index.html b/files/pt-br/web/api/document/body/index.html new file mode 100644 index 0000000000..cb21522c4f --- /dev/null +++ b/files/pt-br/web/api/document/body/index.html @@ -0,0 +1,44 @@ +--- +title: Document.body +slug: Web/API/Document/body +translation_of: Web/API/Document/body +--- +
{{APIRef("DOM")}}
+ +

Retorna o elemento {{HTMLElement("body")}} ou o {{HTMLElement("frameset")}} do documento atual, ou null se nenhum destes elementos existir.

+ +

Sintaxe

+ +
var objRef = document.body;
+document.body = objRef;
+ +

Exemplo

+ +
// No HTML: <body id="oldBodyElement"></body>
+alert(document.body.id); // "oldBodyElement"
+
+var aNewBodyElement = document.createElement("body");
+
+aNewBodyElement.id = "newBodyElement";
+document.body = aNewBodyElement;
+alert(document.body.id); // "newBodyElement"
+
+ +

Notas

+ +

document.body é o elemento que envolve o conteúdo do documento. Em documentos com conteúdo no <body>, retorna o elemento <body>, e em documentos que usam frameset, retorna o elemento <frameset> mais periférico.

+ +

Apesar do body ser configurável, definir um novo body em um documento irá remover todos os elementos contidos no elemento <body> existente.

+ +

Especificação

+ + + +

Veja Também

+ + diff --git a/files/pt-br/web/api/document/characterset/index.html b/files/pt-br/web/api/document/characterset/index.html new file mode 100644 index 0000000000..30ec060745 --- /dev/null +++ b/files/pt-br/web/api/document/characterset/index.html @@ -0,0 +1,65 @@ +--- +title: Document.characterSet +slug: Web/API/Document/characterSet +tags: + - Documento + - Propriedade + - Referencia +translation_of: Web/API/Document/characterSet +--- +
{{ ApiRef("DOM") }}
+ +
A propriedade somente leitura Document.characterSet retorna a character encoding(codificação de caracteres) do documento com o qual ele é renderizado atualmente. (Uma codificação de caracteres é um conjunto de caracteres e como interpretar bytes nesses caracteres.)
+ +
+ +
+

Um “character set”(conjunto de caracteres) e “character encoding”(codificação de caracteres) estão relacionados, mas diferentes. Apesar do nome dessa propriedade, ela retorna a codificação.

+
+ +

Usuários podem sobrepor a codificação especificada pelo desenvolvedor dentro do cabeçalho Content-Type (tipo de conteúdo) ou embutida como <meta charset = "utf-8">, como no menu Exibir → Codificacao de Texto Essa substituição é fornecida para corrigir codificações especificadas pelo desenvolvedor incorretas que resultam em texto ilegivel.

+ +
+

As propriedades document.charset e document.inputEncoding são aliases legados para document.characterSet. Não use mais eles.

+
+ +

Sintaxe

+ +
var string = document.characterSet;
+ +

Exemplos

+ +
<button onclick="console.log(document.characterSet);">
+  Registro de Codificacao de Caracteres
+</button>
+<!-- mostra a codificacao de caracteres do documento no console do desevolvedor, como "ISO-8859-1" ou "UTF-8" -->
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-document-characterset', 'characterSet')}}{{Spec2('DOM WHATWG')}} +

Definição Inicial.

+
+ +

Compatibilidade do navegador

+ + + +

{{Compat("api.Document.characterSet")}}

diff --git a/files/pt-br/web/api/document/close/index.html b/files/pt-br/web/api/document/close/index.html new file mode 100644 index 0000000000..7c9b110edd --- /dev/null +++ b/files/pt-br/web/api/document/close/index.html @@ -0,0 +1,27 @@ +--- +title: Document.close() +slug: Web/API/Document/close +translation_of: Web/API/Document/close +--- +

{{APIRef("DOM")}}

+ +

O metodo document.close() termina a gravação em um documento, aberto com  document.open().

+ +

Sintaxe

+ +
document.close();
+
+ +

Exemplo

+ +
// abre um documento e escreve nele.
+// escreve o conteúdo no documento.
+// fecha o documento.
+document.open();
+document.write("<p>O primeiro e unico conteúdo.</p>");
+document.close();
+
+ +

Especificação

+ +

DOM Level 2 HTML: close() Method

diff --git a/files/pt-br/web/api/document/compatmode/index.html b/files/pt-br/web/api/document/compatmode/index.html new file mode 100644 index 0000000000..1ca33ff573 --- /dev/null +++ b/files/pt-br/web/api/document/compatmode/index.html @@ -0,0 +1,42 @@ +--- +title: Document.compatMode +slug: Web/API/Document/compatMode +translation_of: Web/API/Document/compatMode +--- +

{{ ApiRef("DOM") }}

+ +

Indica se o documento está renderizado no Quirks mode ou no modo dos Padrões.

+ +

Sintaxe

+ +
modo = document.compatMode
+
+ +

Valores

+ + + +
+
modo
+
É um valor enumerado que pode ser:
+
+ +
+

Nota: todos estes modos agora são definidos em padrões, então os antigos nomes "standards" e "almost standards" são sem sentido, e portanto não são mais usados nos padrões.

+
+ +

Exemplo

+ +
if (document.compatMode == "BackCompat") {
+  // in Quirks mode
+}
+
+ +

Especificações

+ + diff --git a/files/pt-br/web/api/document/contenttype/index.html b/files/pt-br/web/api/document/contenttype/index.html new file mode 100644 index 0000000000..5d29907089 --- /dev/null +++ b/files/pt-br/web/api/document/contenttype/index.html @@ -0,0 +1,46 @@ +--- +title: Document.contentType +slug: Web/API/Document/contentType +translation_of: Web/API/Document/contentType +--- +
{{APIRef}}
+ +

Document.contentType é uma propriedade somente de leitura, que retorna o tipo MIME do documento que esta sendo rendenrizado.Isso pode vir de cabeçalhos HTPP ou de outras fontes de informações MIME, e pode se afetado por conversões realizadas pelo navegador ou pelas extenções.

+ +
+

Note: Esta proiedade não é afetada pelos elementos {{HTMLElement("meta")}}.

+
+ +

Sintaxe

+ +
contentType = document.contentType;
+
+ +

Value

+ +

contentType é uma propriedade somente de leitura.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-document-contenttype', 'Document.contentType')}}{{Spec2('DOM WHATWG')}}Definição inicial
+ +

Compatibilidade com os navegadores

+ + + +
{{Compat("api.Document.contentType")}}
diff --git a/files/pt-br/web/api/document/createelement/index.html b/files/pt-br/web/api/document/createelement/index.html new file mode 100644 index 0000000000..3cb88ecb37 --- /dev/null +++ b/files/pt-br/web/api/document/createelement/index.html @@ -0,0 +1,82 @@ +--- +title: Document.createElement() +slug: Web/API/Document/createElement +tags: + - Documento + - Referencia + - Referência(2) + - metodo +translation_of: Web/API/Document/createElement +--- +
{{APIRef("DOM")}}
+ +
 
+ +

Em um documento HTML, o método Document.createElement() cria o elemento HTML especificado ou um {{domxref("HTMLUnknownElement")}} se o nome do elemento dado não for conhecido.

+ +

Em um documento XUL, o elemento XUL especificado é criado.

+ +

Em outros documentos, ele cria um elemento com um namespace URI null.

+ +

Sintaxe

+ +
var elemento = document.createElement(nomeDaTag);
+
+ + + +

Exemplo

+ +

Este código cria uma nova <div> e a insere antes do elemento com ID "div1".

+ +

HTML

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>||Trabalhando com elementos||</title>
+</head>
+<body>
+  <div id="div1">O texto acima foi criado dinamicamente.</div>
+</body>
+</html>
+
+ +

JavaScript

+ +
document.body.onload = adcElemento;
+
+function adcElemento () {
+  // cria um novo elemento div
+  // e dá à ele conteúdo
+  var divNova = document.createElement("div");
+  var conteudoNovo = document.createTextNode("Olá, cumprimentos!");
+  divNova.appendChild(conteudoNovo); //adiciona o nó de texto à nova div criada
+
+  // adiciona o novo elemento criado e seu conteúdo ao DOM
+  var divAtual = document.getElementById("div1");
+  document.body.insertBefore(divNova, divAtual);
+}
+ +

{{EmbedLiveSample("Exemplo", 500, 50)}}

+ +

Notas

+ + + +

Especificações

+ + diff --git a/files/pt-br/web/api/document/createelementns/index.html b/files/pt-br/web/api/document/createelementns/index.html new file mode 100644 index 0000000000..ece55f592e --- /dev/null +++ b/files/pt-br/web/api/document/createelementns/index.html @@ -0,0 +1,90 @@ +--- +title: Document.createElementNS() +slug: Web/API/Document/createElementNS +tags: + - API + - DOM + - Referencia + - metodo +translation_of: Web/API/Document/createElementNS +--- +
{{ApiRef("DOM")}}
+ +

Creates an element with the specified namespace URI and qualified name.

+ +

Cria um elemento com Namespace URI e nome qualificado, como especificado.

+ +

Syntax

+ +
element = document.createElementNS(namespaceURI, qualifiedName);
+
+ + + +

Namespace URI's válidos

+ + + +

Exemplo

+ +

Isso cria um novo elemento <div> no namespace XHTML e anexa ele ao elemento vbox. Embora isso não seja um documento XUL extremamente útil, pode demonstrar o uso de elementos de dois namespaces diferentes em apenas um documento:

+ +
<?xml version="1.0"?>
+<page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+      xmlns:html="http://www.w3.org/1999/xhtml"
+      title="||Working with elements||"
+      onload="init()">
+
+<script type="text/javascript"><![CDATA[
+ var container;
+ var newdiv;
+ var txtnode;
+
+ function init(){
+   container = document.getElementById("ContainerBox");
+   newdiv = document.createElementNS("http://www.w3.org/1999/xhtml","div");
+   txtnode = document.createTextNode("Este é o texto construído dinâmicamente com createElementNS e createTextNode então é inserido no documento usando appendChild.");
+   newdiv.appendChild(txtnode);
+   container.appendChild(newdiv);
+ }
+
+]]></script>
+
+ <vbox id='ContainerBox' flex='1'>
+  <html:div>
+   O script desta página irá colocar conteúdo dinâmico abaixo:
+  </html:div>
+ </vbox>
+
+</page>
+
+ +

Notas

+ +

O exemplo dado anteriormente usa script inline que não é recomendado em documentos XHTML. Este exemplo particular é atualmente um documento  XUL com XHTML incorporado, contudo, a recomendação ainda se aplica. scripts Inline  não causam nenhum problema neste pequeno exemplo, contudo, para qualquer trabalho sério você precisa ler sobre Uso correto de CSS e JavaScript en documentos XHTML.

+ +

Para criar um elemento sem especificar seu namespace URI, use o método createElement.

+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/currentscript/index.html b/files/pt-br/web/api/document/currentscript/index.html new file mode 100644 index 0000000000..179c950916 --- /dev/null +++ b/files/pt-br/web/api/document/currentscript/index.html @@ -0,0 +1,99 @@ +--- +title: Document.currentScript +slug: Web/API/Document/currentScript +translation_of: Web/API/Document/currentScript +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

Retorna o elemento que está sendo processado atualmente.

+ +

Sintaxe

+ +
var curScriptElement = document.currentScript;
+
+ +

Exemplo

+ +

O exemplo abaixo verifica se o script está sendo executado de forma assíncrona:

+ +
if (document.currentScript.async) {
+  console.log("Execução assíncrona");
+} else {
+  console.log("Execução síncrona");
+}
+ +

View Live Examples

+ +

Nota

+ +

Se o código estiver sendo chamado como um callback ou manipulador de eventos, ele não irá referenciar o  elemento; a referência ao elemento só acontece quando ele está sendo processado inicialmente.

+ +

Compatibilidade nos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico29{{ CompatGeckoDesktop("2.0") }}{{ CompatNo() }} (as of IE11)16 +

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico4.4{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}iOS 8
+
+ +

Especificações

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/defaultview/index.html b/files/pt-br/web/api/document/defaultview/index.html new file mode 100644 index 0000000000..77ed7a4c72 --- /dev/null +++ b/files/pt-br/web/api/document/defaultview/index.html @@ -0,0 +1,28 @@ +--- +title: Document.defaultView +slug: Web/API/Document/defaultView +translation_of: Web/API/Document/defaultView +--- +
{{ ApiRef() }}
+ +

Sumário

+ +

Em navegadores, retorna o objeto window associado ao documento ou null se não houver.

+ +

Sintaxe

+ +
var win = document.defaultView;
+ +

Esta propriedade é de somente-leitura.

+ +

Notas

+ +

De acordo com o quirksmode, defaultView não é suportado no IE até o IE 9.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/designmode/index.html b/files/pt-br/web/api/document/designmode/index.html new file mode 100644 index 0000000000..b2c070008b --- /dev/null +++ b/files/pt-br/web/api/document/designmode/index.html @@ -0,0 +1,104 @@ +--- +title: Document.designMode +slug: Web/API/Document/designMode +translation_of: Web/API/Document/designMode +--- +
{{ ApiRef() }}
+ +
 
+ +

Sumário

+ +

document.designMode controla se o documento todo é editável. Valores validos são "on" e "off". De acordo com a especificação, esta propriedade é por padrão "off". Firefox segue este padrão. Nas versões anteriores do Chrome e IE o padrão é "inherit". No IE6-10, o valor é capitalizado.

+ +

Sintaxe

+ +
var mode = document.designMode;
+document.designMode = "on";
+document.designMode = "off";
+ +

Exemplo

+ +

Cria um documento {{HTMLElement("iframe")}} editável:

+ +
iframe_node.contentDocument.designMode = "on";
+
+ +

Especificação

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#making-entire-documents-editable:-the-designmode-idl-attribute', 'designMode')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Compatibilidade nos Browsers

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

 

+ +

Veja também:

+ + diff --git a/files/pt-br/web/api/document/doctype/index.html b/files/pt-br/web/api/document/doctype/index.html new file mode 100644 index 0000000000..72a731c314 --- /dev/null +++ b/files/pt-br/web/api/document/doctype/index.html @@ -0,0 +1,59 @@ +--- +title: Document.doctype +slug: Web/API/Document/doctype +translation_of: Web/API/Document/doctype +--- +
{{ApiRef("DOM")}}
+ +

Retorna a declaração do tipo de documento(Document Type Declaration (DTD)) associado ao documento atual. O objeto retornado implementa a interface {{domxref("DocumentType")}}. Use {{domxref("DOMImplementation.createDocumentType()")}} para criar um DocumentType.

+ +

Sintaxe

+ +
doctype = document.doctype;
+
+ + + +

Exemplo

+ +
var doctypeObj = document.doctype;
+
+console.log(
+  "doctypeObj.name: "           + doctypeObj.name            + "\n" +
+  "doctypeObj.internalSubset: " + doctypeObj.internalSubset  + "\n" +
+  "doctypeObj.publicId: "       + doctypeObj.publicId        + "\n" +
+  "doctypeObj.systemId: "       + doctypeObj.systemId
+);
+ +

Notas

+ +

A propriedade retornará null se não houvernehum  DTD associado ao documento atual.

+ +

O nível 2 do DOM não suporta a edição da declaração do tipo de documento.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-document-doctype', 'Document: doctype')}}{{Spec2('DOM WHATWG')}}
+ +

 Compatibilidade com os navegadores

+ + + +

{{Compat("api.Document.doctype")}}

diff --git a/files/pt-br/web/api/document/document/index.html b/files/pt-br/web/api/document/document/index.html new file mode 100644 index 0000000000..3152137704 --- /dev/null +++ b/files/pt-br/web/api/document/document/index.html @@ -0,0 +1,87 @@ +--- +title: Document() +slug: Web/API/Document/Document +translation_of: Web/API/Document/Document +--- +

{{APIRef}}{{Non-standard_header}}

+ +

O construtor Document cria um novo objeto {{domxref("Document")}},  o qual trata de uma página carregada no navegador servindo como porta de entrada para o conteúdo da página.

+ +

Sintaxe

+ +
var document = new Document()
+ +

Parâmetros

+ +

Nenhum.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG','#interface-document','Document')}}{{Spec2('DOM WHATWG')}}Definição inicial
+ +

Compatibilidade com Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
NavegadorChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
NavegadorAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Suporte{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(47)}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/document/documentelement/index.html b/files/pt-br/web/api/document/documentelement/index.html new file mode 100644 index 0000000000..869cd7a75d --- /dev/null +++ b/files/pt-br/web/api/document/documentelement/index.html @@ -0,0 +1,43 @@ +--- +title: Document.documentElement +slug: Web/API/Document/documentElement +tags: + - Propriedade + - Referencia + - raiz +translation_of: Web/API/Document/documentElement +--- +

{{ ApiRef("DOM") }}

+ +

O  document.documentElement  retorna o Elemento que é o elemento raiz do documento (por exemplo, o elemento <html> para documentos HTML).

+ +

Sintaxe

+ +
var element = document.documentElement;
+
+ +

Exemplo

+ +
var rootElement = document.documentElement;
+var primeiroNivel = rootElement.childNodes;
+
+// primeiroNivel é a NodeList do filho direto do elemento raíz
+for (var i = 0; i < primeiroNivel.length; i++) {
+   // faça algo com cada filho direto do elemento raiz
+   // como primeiroNivel[i]
+
+}
+ +

Notas

+ +

Esta propriedade é uma conveniência somente leitura para obter o elemento raiz associado com qualquer documento.

+ +

Documentos HTML tipicamente contém somente um único nó filho, <html>, talvez com uma declaração DOCTYPE antes dele. Documentos XML, frequentemete contêm múltiplos nós filhos: o elemento de raiz, a declaração DOCTYPE, e as instruções de processamento.

+ +

É por isso que você deve usar document.documentElement em vez de {{Domxref ("document.firstChild")}} para obter o elemento raiz.

+ +

Especificações

+ + diff --git a/files/pt-br/web/api/document/documenturi/index.html b/files/pt-br/web/api/document/documenturi/index.html new file mode 100644 index 0000000000..52609f2bd5 --- /dev/null +++ b/files/pt-br/web/api/document/documenturi/index.html @@ -0,0 +1,53 @@ +--- +title: Document.documentURI +slug: Web/API/Document/documentURI +translation_of: Web/API/Document/documentURI +--- +
{{ApiRef("DOM")}}
+ +
A propiedade documentURI da interface {{domxref("Document")}} retorna uma string com a localização de um documento.
+ +
+ +
Na definição original DOM3 documentURI é um atributo de leitura/escrita.No padrão mais recente DOM4 é somente de leitura.
+ +

Sintaxe

+ +
var string = document.documentURI;
+
+ +

Notas

+ +

Os Documentos HTML tem uma propriedade {{domxref("document.URL")}} que retorna o mesmo valor (localização do documento).

+ +

A diferençã é que document.URL só pode ser usado em documentos HTML, enquanto documentURI está disponivel para todos os documentos web.

+ +

Specificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-document-documenturi','documentURI')}}{{Spec2('DOM WHATWG')}}
{{SpecName('DOM3 Core', '#Document3-documentURI', 'documentURI')}}{{Spec2('DOM3 Core')}}Initial definition
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.Document.documentURI")}}

diff --git a/files/pt-br/web/api/document/elementfrompoint/index.html b/files/pt-br/web/api/document/elementfrompoint/index.html new file mode 100644 index 0000000000..ce447f2830 --- /dev/null +++ b/files/pt-br/web/api/document/elementfrompoint/index.html @@ -0,0 +1,132 @@ +--- +title: Document.elementFromPoint() +slug: Web/API/Document/elementFromPoint +tags: + - API + - CSSOM View + - Method + - NeedsMarkupWork + - NeedsMobileBrowserCompatibility + - Reference +translation_of: Web/API/DocumentOrShadowRoot/elementFromPoint +--- +
{{APIRef("DOM")}}
+ +

O método elementFromPoint() da interface {{domxref("Document")}} retorna o elemento de maior nível nas coordenadas especificadas.

+ +

Se o elemento no ponto especificado pertencer à outro documento (por exemplo, um subdocumento em um iframe), será retornado o pai do subdocumento (o próprio iframe). Se o elemento em determinado ponto for anônimo ou for um conteudo gerado por XBL, como por exemplo barras de scroll de caixas de texto, então será retornado o primeiro elemento pai, não-anônimo (por exemplo, a própria caixa de texto).

+ +

Se o ponto especificado estiver fora dos limites visíveis do documento ou tiver uma coordenada negativa, o resultado é null.

+ +

Se você precisa encontrar uma posição específica dentro do elemento, use {{domxref("Document.caretPositionFromPoint()")}}.

+ +

{{Note("Chamados por documentos XUL devem esperar até o evento onload ser acionado antes de chamar este método.")}}

+ +

Sintaxe

+ +
var element = document.elementFromPoint(x, y);
+ +

Parâmetros

+ +
+
x
+
Uma posição horizontal dentro do viewport atual.
+
y
+
Uma position vertical dentro do viewport atual.
+
+ +

Valor retornado

+ +

O objeto de nível mais alto {{domxref("Element")}} dentro das coordenadas declaradas.

+ +

Exemplo

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>exemplo de elementFromPoint</title>
+
+<script>
+function changeColor(newColor) {
+  elem = document.elementFromPoint(2, 2);
+  elem.style.color = newColor;
+}
+</script>
+</head>
+
+<body>
+<p id="para1">Algum texto aqui</p>
+<button onclick="changeColor('blue');">azul</button>
+<button onclick="changeColor('red');">vermelho</button>
+</body>
+</html>
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('CSSOM View', '#dom-document-elementfrompoint', 'elementFromPoint')}}{{Spec2('CSSOM View')}}Definição Inicial.
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support {{CompatChrome(4.0)}}35.510.50{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/document/elementoregistrado/index.html b/files/pt-br/web/api/document/elementoregistrado/index.html new file mode 100644 index 0000000000..bff318b3a9 --- /dev/null +++ b/files/pt-br/web/api/document/elementoregistrado/index.html @@ -0,0 +1,132 @@ +--- +title: Document.registerElement() +slug: Web/API/Document/ElementoRegistrado +tags: + - DOM + - Document.registerElement() + - ELEMENTO DOM + - Web Components + - registerElement +translation_of: Web/API/Document/registerElement +--- +

{{APIRef("DOM")}}

+ +
+

Note:document.registerElement() está depreciado em favor do customElements.define().

+
+ +

O método document.registerElement() registra um novo elemento personalizado no browser e returna um construtor para o novo elemento.

+ +
+

Nota: Esta é uma tecnologia experimental. O browser você precisa usar suporte à componentes web. Veja Habilitando componentes web no Firefox.

+
+ +

Sintaxe

+ +
var constructor = document.registerElement(tag-name, options);
+ +

Parâmetros

+ +
+
tag-name
+
O nome do elemento personalizado. O nome precisa conter um dash (-), por exemplo minha-tag.
+
Opções{{optional_inline}}
+
+

Um projeto com propriedades protótipo como base para o elememento personalizado, e extends, uma existente tag para estender. Ambos são opcionais.

+
+
+ +

Exemplo

+ +

Aqui é um exemplo muito simples:

+ +
var Mytag = document.registerElement('my-tag');
+
+ +

Agora as novas tags são registradas no browser.

+ +

Uma variável Mytag tem um construtor que você pode usar para criar um elemento my-tag nos documentos como seguem:

+ +
document.body.appendChild(new Mytag());
+ +

Isto insere um elemento vazio my-tag que será visível se você usar o browser para desenvolvedores. Isto não será visível se você usar a ferramenta visão da capacidade do código fonte do browser. E isto não será visível no browser a menos que você adicione alguns conteúdos para a tag. Aqui está um caminho para adicionar conteúdo a nova tag:

+ +
var mytag = document.getElementsByTagName("my-tag")[0];
+mytag.textContent = "I am a my-tag element.";
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Custom Elements')}}{{Spec2('Custom Elements')}} +

definição inicial

+
+ +

Compatibilidade do Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico3531[1]{{CompatNo}}25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico4.4.431[1]{{CompatNo}}25{{CompatNo}}
+
+ +

[1] Esta API é implementada uma preferência

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/execcommand/index.html b/files/pt-br/web/api/document/execcommand/index.html new file mode 100644 index 0000000000..cc5e3d3da8 --- /dev/null +++ b/files/pt-br/web/api/document/execcommand/index.html @@ -0,0 +1,174 @@ +--- +title: Document.execCommand() +slug: Web/API/Document/execCommand +translation_of: Web/API/Document/execCommand +--- +
{{ApiRef("DOM")}}{{Obsolete_header}}
+ +

Quando um documento HTML está em designMode, seu objeto document  expõe um metodo execCommand para editar a região editável corrente, algo como elementos form inputs ou contentEditable.

+ +

A maioria dos comandos afetam apaenas uma área selecionada [seleção] (negrito, itálico, etc.), enquantos outros adicionam novos elementos (adicionar um link por exemplo), ou afetam uma linha toda (identação). Quando usando contentEditable, o metódo execCommand() afeta o elemento editável ativo.

+ +

Síntaxe

+ +
document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
+
+ +

Valor de Retorno

+ +

Um {{jsxref('Boolean')}} que tem valor false se o comando não é válido ou está desabilitado.

+ +
+

Nota: Retorna true se for parte da interação do usuário. Não tente utilizar o retorno para verificar o suporte do browser antes de chamar o comando.

+
+ +

Parâmetros

+ +
+
aCommandName
+
Uma {{domxref("DOMString")}} especificando o nome do comando a ser executado. Veja {{anch("Comandos")}} para um lista dos possíveis comandos.
+
aShowDefaultUI
+
Um {{jsxref("Boolean")}} indicando se a interface padrão do usuário deve ser mostrada. Isso não é implementado no Mozilla.
+
aValueArgument
+
Para comandos que requerem um argumento de entrada. É uma {{domxref("DOMString")}} provendo a informação. Por exemplo, insertImage requer uma URL da imagem a ser inserida. Use null se nenhum argumento é necessário.
+
+ +

Comandos

+ +
+
backColor
+
Muda a cor de fundo do documento. No modo styleWithCss, ele afeta a cor de fundo do bloco que contém. Isso requer um valor de {{cssxref("<color>")}} passado como argumento. Observe que o Internet Explorer usa isso para definir a cor do plano de fundo do texto.
+
bold
+
Ativa / desativa negrito na seleção ou no ponto de inserção. O Internet Explorer usa a tag {{HTMLElement("strong")}} no lugar de {{HTMLElement("b")}}.
+
ClearAuthenticationCache
+
Limpa todas as credenciais de autenticação do cache.
+
contentReadOnly
+
Torna o documento de conteúdo somente leitura ou editável. Isso requer um valor booleano true / false como argumento. (Não é suportado pelo Internet Explorer.)
+
copy
+
Copia a seleção atual para a área de transferência. As condições para ativar esse comportamento variam de um navegador para outro e evoluíram com o tempo. Verifique a Tabela de {{anch("Compatibilidade entre Browsers")}} para determinar se você pode usar no seu caso.
+
createLink
+
Cria um hiperlink a partir da seleção, mas apenas se houver uma seleção. Requer uma string URI como argumento para o href do link.  O URI deve conter pelo menos um único caractere, que pode ser um espaço em branco. (O Internet Explorer criará um link com um valor nulo.)
+
cut
+
Remove a seleção atual e a copia para a área de transferência. Quando esse comportamento é ativado, varia entre os navegadores e suas condições evoluíram com o tempo. Verifique a Tabela de {{anch("Compatibilidade entre Browsers")}} para mais detalhes.
+
decreaseFontSize
+
Adiciona a tag {{HTMLElement("small")}} ao redor da seleção ou no ponto de inserção. (Não é suportado pelo Internet Explorer.)
+
defaultParagraphSeparator
+
Altera o separador de parágrafos usado quando novos parágrafos são criados em regiões de texto editáveis. Veja Diferenças na geração de marcação para mais detalhes.
+
delete
+
Exclui o conteúdo da seleção atual.
+
enableAbsolutePositionEditor
+
Habilita ou desabilita a garra que permite mover elementos absolutamente posicionados. Está desabilitado por padrão no Firefox 63 Beta / Dev Edition ({{bug(1449564)}})
+
enableInlineTableEditing
+
Ativa ou desativa os controles de inserção e exclusão de linhas / colunas da tabela. Está desabilitado por padrão no Firefox 63 Beta / Dev Edition ({{bug(1449564)}}).
+
enableObjectResizing
+
Ativa ou desativa as alças de redimensionamento em imagens, tabelas e elementos absolutamente posicionados e outros objetos redimensionáveis. Está desabilitado por padrão no Firefox 63 Beta / Dev Edition ({{bug(1449564)}}).
+
fontName
+
Altera o nome da fonte para a seleção ou no ponto de inserção. Isso requer uma string com o nome da fonte (como "Arial") como argumento.
+
fontSize
+
Altera o tamanho da fonte para a seleção ou no ponto de inserção. Isso requer um número inteiro de 1-7 como argumento.
+
foreColor
+
Altera a cor da fonte para a seleção ou no ponto de inserção. Isso requer uma string de cor (hexadecimal) como argumento.
+
formatBlock
+
Adiciona um elemento de nível de bloco HTML ao redor da linha que contém a seleção atual, substituindo o elemento de bloco que contém a linha, se houver (no Firefox,  {{HTMLElement("blockquote")}} é a exceção - envolverá qualquer elemento de bloco que contenha). Requer uma sequência de nome de tag como argumento de valor. Praticamente todos os elementos em nível de bloco podem ser usados. (Internet Explorer e Edge suportam apenas tags de cabeçalho  H1H6, ADDRESS, e PRE, que devem estar entre colchetes angulares, como "<H1>".)
+
forwardDelete
+
Exclui o caractere depois da posição do cursor, idêntico a pressionar a tecla Delete em um teclado do Windows.
+
heading
+
Adiciona um elemento de cabeçalho ao redor de uma linha de seleção ou ponto de inserção. Requer uma string com o nome da tag como argumento (ex. "H1", "H6"). (Não suportado pelo Internet Explorer e Safari.)
+
hiliteColor
+
Altera a cor do plano de fundo para a seleção ou no ponto de inserção. Requer uma sequência de valores de cores como argumento. useCSS tem de ser true para essa função. (Não é suportado pelo Internet Explorer.)
+
increaseFontSize
+
Adiciona uma tag {{HTMLElement("big")}} ao redor da seleção ou no ponto de inserção. (Não é suportado pelo Internet Explorer.)
+
indent
+
Recua a linha que contém o ponto de seleção ou inserção. No Firefox, se a seleção abranger várias linhas em diferentes níveis de recuo, apenas as linhas menos recuadas na seleção serão recuadas.
+
insertBrOnReturn
+
Controla se a tecla Enter insere um elemento {{HTMLElement("br")}}, ou divide o elemento do bloco atual em dois. (Não é suportado pelo Internet Explorer.)
+
insertHorizontalRule
+
Insere um elemento {{HTMLElement("hr")}} no ponto de inserção ou substitui a seleção por ele.
+
insertHTML
+
Insere uma string HTML no ponto de inserção (exclui a seleção). Requer uma string HTML válida como argumento. (Não é suportado pelo Internet Explorer.)
+
insertImage
+
Insere uma imagem no ponto de inserção (exclui a seleção). Requer uma string de URL para o src da imagem como argumento. Os requisitos para essa string são os mesmos que createLink.
+
insertOrderedList
+
Cria uma lista ordenada e numerada para a seleção ou no ponto de inserção.
+
insertUnorderedList
+
Cria uma lista não ordenada para a seleção ou no ponto de inserção.
+
insertParagraph
+
Insere um parágrafo ao redor da seleção ou da linha atual. (O Internet Explorer insere um parágrafo no ponto de inserção e exclui a seleção.)
+
insertText
+
Insere o texto fornecido no ponto de inserção (exclui a seleção).
+
italic
+
Ativa / desativa o itálico para a seleção ou no ponto de inserção. (O Internet Explorer usa o elemento {{HTMLElement("em")}} no lugar de {{HTMLElement("i")}}.)
+
justifyCenter
+
Centraliza o ponto de seleção ou inserção.
+
justifyFull
+
Justifica o ponto de seleção ou inserção.
+
justifyLeft
+
Justifica o ponto de seleção ou inserção à esquerda.
+
justifyRight
+
Justifica à direita a seleção ou o ponto de inserção.
+
outdent
+
Supera a linha que contém o ponto de seleção ou inserção.
+
paste
+
Cola o conteúdo da área de transferência no ponto de inserção (substitui a seleção atual). Desativado para conteúdo da web. Veja [1].
+
redo
+
Refaz o comando desfazer anterior.
+
removeFormat
+
Remove toda a formatação da seleção atual.
+
selectAll
+
Seleciona todo o conteúdo da região editável.
+
strikeThrough
+
Ativa / desativa o strikethrough(linha riscada) para a seleção ou no ponto de inserção.
+
subscript
+
Ativa / desativa o subscrito para a seleção ou no ponto de inserção.
+
superscript
+
Ativa / desativa o superscript para a seleção ou no ponto de inserção.
+
underline
+
Ativa / desativa o underline para a seleção ou no ponto de inserção.
+
undo
+
Desfaz o último comando executado.
+
unlink
+
Remove o elemento âncora de um hiperlink selecionado.
+
useCSS {{Deprecated_inline}}
+
Alterna o uso de tags HTML ou CSS para a marcação gerada. Requer um booleano true / false como argumento.
+

+ NOTA: Este argumento é logicamente reverso (ou seja, use false para usar CSS, true para usar HTML) e não é suportado pelo Internet Explorer. Isso foi preterido em favor do styleWithCSS.
+
styleWithCSS
+
Substitui o comando useCSS. true modifica / gera atributos de style na marcação, false gera elementos de apresentação(html).
+
+
+ +

Exemplo

+ +

Um exemplo de como usar a funcionalidade no CodePen.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
execCommand
+ +

Compatibilidade entre Browsers

+ + + +

{{Compat("api.Document.execCommand")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/fullscreen/index.html b/files/pt-br/web/api/document/fullscreen/index.html new file mode 100644 index 0000000000..6ad6fc604f --- /dev/null +++ b/files/pt-br/web/api/document/fullscreen/index.html @@ -0,0 +1,83 @@ +--- +title: Document.fullscreen +slug: Web/API/Document/fullscreen +tags: + - API + - Documento + - Javascript tela cheia + - Propriedade + - Referencia + - Somente Leitura + - Tela + - Tela Cheia + - display +translation_of: Web/API/Document/fullscreen +--- +
{{APIRef("Fullscreen API")}}{{Deprecated_Header}}
+ +

A propriedade de somente leitura da interface fullscreen retorna se o documento correspondente está mostrando conteúdo em modo de tela cheia (full-screen). 

+ +

Apesar dessa propriedade ser de somente leitura, ela não será executa se for modificada (mesmo em modo estrito); o setter não é um operador e não será modificado.

+ +
+

Nota: Desde que esta propriedade foi descontinuada, você pode determinar se o modo full-screen está ativo no documento checando se {{DOMxRef("Document.fullscreenElement")}} não é null.

+
+ +

Síntaxe

+ +
var isFullScreen = document.fullscreen;
+
+ +

Valor

+ +

Um valor booleano é true se o documento está mostrando um elemento no modo full-screen; se não, o valor é false.

+ +

Exemplo

+ +

Esta simples função retorna se o modo full-sreen está ativo, usando a obsoleta propriedade fullscreen.

+ +
function isDocumentInFullScreenMode() {
+  return document.fullscreen;
+}
+
+ +

Neste próximo exemplo, de outra maneira, usa a propriedade atual fullscreenElement para determinar a mesma coisa:

+ +
function isDocumentInFullScreenMode() {
+  return document.fullscreenElement !== null;
+}
+ +

Se fullscreenElement  não é null, retorna true, indicando se modo full-screen está sendo usado.

+ +

Específicações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fullscreen", "#dom-document-fullscreen", "Document.fullscreen")}}{{Spec2("Fullscreen")}}Definição inicial (como uma proprieda obsoleta).
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.Document.fullscreen")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/getelementbyid/index.html b/files/pt-br/web/api/document/getelementbyid/index.html new file mode 100644 index 0000000000..c77a93fed9 --- /dev/null +++ b/files/pt-br/web/api/document/getelementbyid/index.html @@ -0,0 +1,133 @@ +--- +title: document.getElementById() +slug: Web/API/Document/getElementById +tags: + - API + - DOM + - Document + - Elements + - Method + - Reference + - Web + - getElementById + - id +translation_of: Web/API/Document/getElementById +--- +
{{ ApiRef("DOM") }}
+ +

Sumário

+ +

Retorna a referência do elemento através do seu ID.

+ +

Sintaxe

+ +
var elemento = document.getElementById(id);
+
+ +

onde

+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>Exemplo getElementById</title>
+  <script>
+  function mudarCor(novaCor) {
+    var elemento = document.getElementById("para1");
+    elemento.style.color = novaCor;
+  }
+  </script>
+</head>
+<body>
+  <p id="para1">Algum texto de exemplo</p>
+  <button onclick="mudarCor('blue');">Azul</button>
+  <button onclick="mudarCor('red');">Vermelho</button>
+</body>
+</html>
+
+ +

Notas

+ +

Os novatos devem notar que a caixa de 'Id' no nome deste método deve estar correta para o código da função - 'getElementByID não funciona, por mais natural que possa parecer.

+ +

Se não existe um elemento com o id fornecido, esta função retorna null. Note que o parâmetro ID diferência maiúsculas e minúsculas. Assim document.getElementById("Main") retornará null ao invés do elemento <div id="main">, devido a "M" e "m" serem diferentes para o objetivo deste método.

+ +

Elementos que não estão no documento não são procurados por getElementById. Quando criar um elemento e atribuir um ID ao mesmo, você deve inserir o elemento na árvore do documento com insertBefore ou método similar antes que você possa acessá-lo com getElementById:

+ +
var elemento = document.createElement("div");
+elemento.id = 'testqq';
+var el = document.getElementById('testqq'); // el será null!
+
+ +

Documentos não-HTML. A implementação do DOM deve ter informações que diz quais atributos são do tipo ID.  Atributos com o nome "id" não são do tipo ID a menos que assim sejam definidos nos documentos DTD. O atributo id é definido para ser um tipo ID em casos comuns de  XHTML, XUL, e outros. Implementações que não reconhecem se os atributos são do tipo ID, ou não são esperados retornam null.

+ +

Compatibilidade do Navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{ CompatGeckoDesktop(1.0) }}5.57.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico1.0{{ CompatGeckoMobile(1.0) }}6.06.01.0
+
+ +

Especificações

+ +

getElementById foi introduzido no DOM Level 1 para documentos HTML e movidos para todos documentos no DOM Level 2

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/getelementsbyclassname/index.html b/files/pt-br/web/api/document/getelementsbyclassname/index.html new file mode 100644 index 0000000000..44fa28f840 --- /dev/null +++ b/files/pt-br/web/api/document/getelementsbyclassname/index.html @@ -0,0 +1,104 @@ +--- +title: Document.getElementsByClassName() +slug: Web/API/Document/getElementsByClassName +tags: + - API + - DOM + - Gecko + - HTML5 + - Métodos de Elementos DOM + - Referencia + - metodo +translation_of: Web/API/Document/getElementsByClassName +--- +

{{APIRef("DOM")}}

+ +

Retorna um vetor de objetos com todos os elementos filhos que possuem o nome da classe dada.  Quando invocado no objeto document, o documento é examinado por completo, incluindo o nó raiz. Você também pode invocar {{domxref("Element.getElementsByClassName", "getElementsByClassName()")}} em qualquer elemento; isso retornaria somente elementos que são descendentes do nó raiz especificado com o nome da classe.

+ +

Sintaxe

+ +
var elementos = document.getElementsByClassName(nomes); // ou:
+var elementos = rootElement.getElementsByClassName(nomes);
+ + + +

Exemplos

+ +

Retorna todos os elementos que possuem a classe 'teste'

+ +
document.getElementsByClassName('teste');
+ +

Retorna todos os elementos que possuem as classes 'vermelho' e 'teste'

+ +
document.getElementsByClassName('vermelho teste');
+ +

Retorna todos os elementos que possuem a classe 'teste' dentro do elemento que possui o ID 'principal'

+ +
document.getElementById('principal').getElementsByClassName('teste');
+ +

Nós podemos também usar os métodos do Array.prototype em qualquer dos elementos {{ domxref("HTMLCollection") }} passando o HTMLCollection como valor deste método. Aqui podemos encontrar todos os elementos do tipo div que possuem a classe 'teste':

+ +
var elementosTeste = document.getElementsByClassName('teste');
+var divsTeste = Array.prototype.filter.call(elementosTeste, function(elementoTeste) {
+    return elementoTeste.nodeName === 'DIV';
+});
+ +

Compatibilidade com navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}3.09.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/getelementsbyname/index.html b/files/pt-br/web/api/document/getelementsbyname/index.html new file mode 100644 index 0000000000..8793259751 --- /dev/null +++ b/files/pt-br/web/api/document/getelementsbyname/index.html @@ -0,0 +1,90 @@ +--- +title: Document.getElementsByName() +slug: Web/API/Document/getElementsByName +translation_of: Web/API/Document/getElementsByName +--- +
{{APIRef("DOM")}}
+ +

O métodogetElementsByName() do objeto {{domxref("Document")}} retorna uma coleção de elementos {{domxref("NodeList")}} com um dado {{domxref("element.name","name")}} no documento.

+ +

Sintaxe

+ +
var elementos = document.getElementsByName(nome);
+
+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html lang="en">
+<title>Exemplo: usando document.getElementsByName</title>
+
+<input type="hidden" name="up">
+<input type="hidden" name="down">
+
+<script>
+  var up_nomes = document.getElementsByName("up");
+  console.log(up_nomes[0].tagName); // exibindo o campo "INPUT"
+</script>
+</html>
+
+ +

Notas

+ +

O atributo {{domxref("element.name","name")}} pode somente ser aplicado nos documentos (X)HTML.

+ +

A coleção retornada {{domxref("NodeList")}} contém todos os elementos com o respectivo nome, tal como {{htmlelement("meta")}}, {{htmlelement("object")}}, e até os elementos o qual não suporta o atributo nome para todos.

+ +
+

O método getElementsByName trabalha diferentemente em IE10 e anteriores. Além de que, getElementsByName() também retorna elementos que tem um atributo id com o valor especificado. Seja cuidadoso para não usar a mesma string como ambos nome e id.

+
+ +
+

O método getElementsByName trabalha diferentemente no IE. Portanto, getElementsByName() não retorna todos os elementos no qual não pode ter um atributo nome (tal como <span>).

+
+ +
+

Ambos IE e Edge retorna um {{domxref("HTMLCollection")}}, e não um {{domxref("NodeList")}}

+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EpecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-document-getelementsbyname', "Document.getElementsByName()")}}{{ Spec2('HTML WHATWG') }}
{{SpecName("DOM2 HTML", "html.html#ID-71555259", "Document.getElementsByName()")}}{{Spec2("DOM2 HTML")}}Definição Inicial
+ +

Compatibilidade com Nagevagores

+ + + +

{{Compat("api.Document.getElementsByName")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/getelementsbytagname/index.html b/files/pt-br/web/api/document/getelementsbytagname/index.html new file mode 100644 index 0000000000..3e786ed2f6 --- /dev/null +++ b/files/pt-br/web/api/document/getelementsbytagname/index.html @@ -0,0 +1,113 @@ +--- +title: Document.getElementsByTagName() +slug: Web/API/Document/getElementsByTagName +translation_of: Web/API/Document/getElementsByTagName +--- +
{{APIRef("DOM")}}
+ +

O método getElementsByTagName da interface Document retorna um HTMLCollection de elementos com o nome da tag fornecido. O documento completo é pesquisado, incluindo o nó raiz. A HTMLCollection retornada é ao vivo, o que significa que ela se atualiza automaticamente para permanecer em sincronia com a árvore DOM sem ter que chamar document.getElementsByTagName () novamente.

+ +

O método getElementsByTagName da {{domxref("Document")}} interface returns an {{domxref("HTMLCollection")}} of elements with the given tag name. The complete document is searched, including the root node. The returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName() again.

+ +

Syntax

+ +
var elements = document.getElementsByTagName(name);
+ + + +
The latest W3C specification says elements is an HTMLCollection; however, this method returns a {{domxref("NodeList")}} in WebKit browsers. See {{bug(14869)}} for details.
+ +

Example

+ +

In the following example, getElementsByTagName() starts from a particular parent element and searches top-down recursively through the DOM from that parent element, building a collection of all descendant elements which match the tag name parameter. This demonstrates both document.getElementsByTagName() and the functionally identical {{domxref("Element.getElementsByTagName()")}}, which starts the search at a specific element within the DOM tree.

+ +

Clicking the buttons uses getElementsByTagName() to count the descendant paragraph elements of a particular parent (either the document itself or one of two nested {{HTMLElement("div")}} elements).

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset="UTF-8" />
+  <title>getElementsByTagName example</title>
+  <script>
+    function getAllParaElems() {
+      var allParas = document.getElementsByTagName('p');
+      var num = allParas.length;
+      alert('There are ' + num + ' paragraph in this document');
+    }
+
+    function div1ParaElems() {
+      var div1 = document.getElementById('div1');
+      var div1Paras = div1.getElementsByTagName('p');
+      var num = div1Paras.length;
+      alert('There are ' + num + ' paragraph in #div1');
+    }
+
+    function div2ParaElems() {
+      var div2 = document.getElementById('div2');
+      var div2Paras = div2.getElementsByTagName('p');
+      var num = div2Paras.length;
+      alert('There are ' + num + ' paragraph in #div2');
+    }
+  </script>
+</head>
+<body style="border: solid green 3px">
+  <p>Some outer text</p>
+  <p>Some outer text</p>
+
+  <div id="div1" style="border: solid blue 3px">
+    <p>Some div1 text</p>
+    <p>Some div1 text</p>
+    <p>Some div1 text</p>
+
+    <div id="div2" style="border: solid red 3px">
+      <p>Some div2 text</p>
+      <p>Some div2 text</p>
+    </div>
+  </div>
+
+  <p>Some outer text</p>
+  <p>Some outer text</p>
+
+  <button onclick="getAllParaElems();">
+    show all p elements in document</button><br />
+
+  <button onclick="div1ParaElems();">
+    show all p elements in div1 element</button><br />
+
+  <button onclick="div2ParaElems();">
+    show all p elements in div2 element</button>
+
+</body>
+</html>
+
+ +

Notes

+ +

When called on an HTML document, getElementsByTagName() lower-cases its argument before proceeding. This is undesirable when trying to match camelCase SVG elements in a subtree in an HTML document. {{Domxref("document.getElementsByTagNameNS()")}} is useful in that case. See also {{Bug(499656)}}.

+ +

document.getElementsByTagName() is similar to {{domxref("Element.getElementsByTagName()")}}, except that its search encompasses the whole document.

+ +

Specifications

+ + + +

Browser compatibility

+ + + +

{{Compat("api.Document.getElementsByTagName")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/document/getselection/index.html b/files/pt-br/web/api/document/getselection/index.html new file mode 100644 index 0000000000..9a2aab76d5 --- /dev/null +++ b/files/pt-br/web/api/document/getselection/index.html @@ -0,0 +1,8 @@ +--- +title: Document.getSelection() +slug: Web/API/Document/getSelection +translation_of: Web/API/DocumentOrShadowRoot/getSelection +--- +

{{APIRef("DOM")}}

+ +

Esse método funciona de forma idêntica ao método {{domxref("Window.getSelection()")}};  Ele retorna um objeto {{domxref("Selection")}} representando o texto atualmente selecionado no documento.

diff --git a/files/pt-br/web/api/document/hasfocus/index.html b/files/pt-br/web/api/document/hasfocus/index.html new file mode 100644 index 0000000000..0d238ec062 --- /dev/null +++ b/files/pt-br/web/api/document/hasfocus/index.html @@ -0,0 +1,146 @@ +--- +title: Document.hasFocus() +slug: Web/API/Document/hasFocus +tags: + - API + - Compatibilidade + - DOM + - Focus + - Referencia + - metodo +translation_of: Web/API/Document/hasFocus +--- +
{{APIRef}}
+ +
O método Document.hasFocus() retorna um valor {{jsxref("Boolean")}} que indica se o documento ou qualquer elemento dentro do documento está com o foco ativo. Este método pode ser usado para determinar se o elemento ativo em um documento tem foco.
+ +
+

Quando se está visualizando um documento, um elemento com focus é sempre o ativo no mesmo, mas um elemento ativo não necessariamente tem o foco. Por exemplo, um elemento ativo com uma janela (popup) que não é a principal não tem foco.

+
+ +

Sintaxe

+ +
focused = document.hasFocus();
+ +

Valor retornado

+ +

false se o elemento ativo no documento não tem foco; true se o elemento ativo no documento tem foco.

+ +

Exemplo

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8" />
+<title>TEST</title>
+<style>
+#message { font-weight: bold; }
+</style>
+<script>
+setInterval( checkPageFocus, 200 );
+
+function checkPageFocus() {
+  var info = document.getElementById("message");
+
+  if ( document.hasFocus() ) {
+    info.innerHTML = "O documento tem o foco.";
+  } else {
+    info.innerHTML = "O documento não tem o foco.";
+  }
+}
+
+function openWindow() {
+  window.open (
+    "http://developer.mozilla.org/",
+    "mozdev",
+    "width=640,
+    height=300,
+    left=150,
+    top=260"
+  );
+}
+</script>
+</head>
+<body>
+  <h1>Exemplo do JavaScript hasFocus</h1>
+  <div id="message">Esperando por ação do usuário</div>
+  <div><button onclick="openWindow()">Abre uma nova janela</button></div>
+</body>
+</html>
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'interaction.html#dom-document-hasfocus', 'Document.hasFocus()')}}{{Spec2('HTML WHATWG')}}Definição inicial
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico30{{ CompatGeckoDesktop("1.9") }}6.0{{ CompatNo() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("1.9") }}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}
+
+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/head/index.html b/files/pt-br/web/api/document/head/index.html new file mode 100644 index 0000000000..af0331459f --- /dev/null +++ b/files/pt-br/web/api/document/head/index.html @@ -0,0 +1,102 @@ +--- +title: Document.head +slug: Web/API/Document/head +translation_of: Web/API/Document/head +--- +

{{APIRef("DOM")}}

+ +

Retorna o elemento {{HTMLElement("head")}} do documento atual. Se existir mais de um elemento <head>, apenas o primeiro será devolvido.

+ +

Sintaxe

+ +
var objRef = document.head;
+
+ +

Exemplo

+ +
// No HTML: <head id="my-document-head">
+var aHead = document.head;
+
+alert(aHead.id); // "my-document-head";
+
+alert( document.head === document.querySelector("head") ); // true
+
+ +

Notas

+ +

document.head suporta apenas leitura. Qualquer tentativa de atribuir um valor a essa propriedade irá falhar silenciosamente ou irá, usando o modo ECMAScript Strict de um browser Gecko, disparar um TypeError.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("HTML5 W3C", "dom.html#dom-tree-accessors", "document.head")}}{{Spec2("HTML5 W3C")}}Definição inicial
+ +

Compatibilidade entre Browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico4.0{{CompatGeckoDesktop("2")}}9.011.05.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/document/height/index.html b/files/pt-br/web/api/document/height/index.html new file mode 100644 index 0000000000..5dedba8f99 --- /dev/null +++ b/files/pt-br/web/api/document/height/index.html @@ -0,0 +1,44 @@ +--- +title: Document.height +slug: Web/API/Document/height +translation_of: Web/API/Document/height +--- +
{{APIRef("DOM")}} {{Obsolete_header}}
+ +
+

Nota: A partir do {{Gecko("6.0")}}, document.height  não é mais suportado. Em seu lugar use document.body.clientHeight. Veja {{domxref("element.clientHeight")}}.

+
+ +

Sumário

+ +

Retorna a altura do objeto {{domxref("document")}}. Em muitos casos, isto é igual à do elemento {{HTMLElement("body")}} do documento atual.

+ +

Sintaxe

+ +
height_value = document.height
+
+ +

Exemplo

+ +
// alert document height
+alert(document.height);
+
+ +

Alternativas

+ +
document.body.clientHeight
+document.documentElement.clientHeight
+document.documentElement.scrollHeight
+
+ +

Especificação

+ +

HTML5

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/images/index.html b/files/pt-br/web/api/document/images/index.html new file mode 100644 index 0000000000..f5021122a9 --- /dev/null +++ b/files/pt-br/web/api/document/images/index.html @@ -0,0 +1,38 @@ +--- +title: Document.images +slug: Web/API/Document/images +translation_of: Web/API/Document/images +--- +
+
{{ ApiRef("DOM") }}
+
+ +

Summary

+ +

document.images retorna uma coleção de imagens do documento HTML.

+ +

Sintaxe

+ +
var htmlCollection = document.images;
+ +

Exemplo

+ +
var ilist = document.images;
+
+for(var i = 0; i < ilist.length; i++) {
+    if(ilist[i].src == "banner.gif") {
+        // found the banner
+    }
+}
+ +

Notas

+ +

document.images.length – propriedade, retorna o número de imagens na página.

+ +

document.images é parte do DOM HTML, e só trabalho com documentos HTML.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/implementation/index.html b/files/pt-br/web/api/document/implementation/index.html new file mode 100644 index 0000000000..2f7b5ca992 --- /dev/null +++ b/files/pt-br/web/api/document/implementation/index.html @@ -0,0 +1,52 @@ +--- +title: Document.implementation +slug: Web/API/Document/implementation +tags: + - API + - DOM + - Propriedade + - Referencia +translation_of: Web/API/Document/implementation +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

Sumário

+ +

Retorna um objeto {{domxref("DOMImplementation")}} associado ao documento atual.

+ +

Sintaxe

+ +
DOMImpObj = document.implementation;
+
+ +

Exemplo

+ +
var modName = "HTML";
+var modVer = "2.0";
+var conformTest = document.implementation.hasFeature( modName, modVer );
+
+alert( "DOM " + modName + " " + modVer + " supported?: " + conformTest );
+
+// alerts with: "DOM HTML 2.0 supported?: true" if DOM Level 2 HTML module is supported.
+
+ +

Uma lista dos nomes de módulos (ex., Core, HTML, XML, etc) está disponível na DOM Level 2 Conformance Section

+ +

Notas

+ +

A Recomendação do W3C DOM Level 1 apenas especifica o método hasFeature, que é o único meio de verificar se o módulo DOM é suportado pelo navegador (veja exemplo acima e What does your user agent claim to support?). Quando disponível, outros métodos DOMImplementation proverão serviços para controlar coisas fora deste único documento. Por exemplo, a interface DOMImplementation inclui um método createDocumentType com o qual DTD's podem ser criados para um ou mais documentos gerenciados pela implementação.

+ +

Especificação

+ + + +

Notas específicas para o Gecko

+ + diff --git a/files/pt-br/web/api/document/importnode/index.html b/files/pt-br/web/api/document/importnode/index.html new file mode 100644 index 0000000000..831879f58f --- /dev/null +++ b/files/pt-br/web/api/document/importnode/index.html @@ -0,0 +1,84 @@ +--- +title: Document.importNode() +slug: Web/API/Document/importNode +translation_of: Web/API/Document/importNode +--- +

{{APIRef("DOM")}}

+ +

Cria uma cópia de um nó a partir de um documento externo para ser inserido no document atual.

+ +

Sintaxe

+ +
var node = document.importNode(externalNode, deep);
+
+ +
+
node
+
O novo nó que será importado no documento. A propriedade parentNode do novo nó é null, desde que ele não foi inserido na árvores do documento.
+
externalNode
+
O nó de outro documento para ser importado.
+
deep
+
Um boolean, indicando se os nós filhos, do nó a ser importado, devem ser importados também.
+
+ +
+

Note: In the DOM4 specification (as implemented in Gecko 13.0 {{geckoRelease(13)}}), deep is an optional argument. If omitted, the method acts as if the value of deep was true, defaulting to using deep cloning as the default behavior. To create a shallow clone, deep must be set to false.

+ +

This behavior has been changed in the latest spec, and if omitted, the method will act as if the value of deep was false. Though It's still optional, you should always provide the deep argument both for backward and forward compatibility. With Gecko 28.0 {{geckoRelease(28)}}, the console warned developers not to omit the argument. Starting with Gecko 29.0 {{geckoRelease(29)}}), a shallow clone is defaulted instead of a deep clone.

+
+ +

Exemplo

+ +
var iframe = document.getElementsByTagName("iframe")[0];
+var oldNode = iframe.contentWindow.document.getElementById("myNode");
+var newNode = document.importNode(oldNode, true);
+document.getElementById("container").appendChild(newNode);
+
+ +

Notas

+ +

O nó original não é removido do documento de origem. O nó importado é um clone do original.

+ +

 

+ +

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.

+ +

 

+ +

Especificação

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-document-importnode", "document.importNode()")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM2 Core", "core.html#Core-Document-importNode", "document.importNode()")}}{{Spec2("DOM2 Core")}}Initial definition
+ +

Compatibilidade nos Browsers

+ +
+ + +

{{Compat("api.Document.importNode")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/index.html b/files/pt-br/web/api/document/index.html new file mode 100644 index 0000000000..1fc11a79ba --- /dev/null +++ b/files/pt-br/web/api/document/index.html @@ -0,0 +1,402 @@ +--- +title: Document +slug: Web/API/Document +translation_of: Web/API/Document +--- +
{{ ApiRef("DOM") }}
+ +
+ +

Para cada página carregada no browser, existe um objeto Document. A interface Document serve como um ponto de entrada para o conteúdo da Página ( a árvore DOM, incluindo elementos como {{HTMLElement("body")}} e {{HTMLElement("table")}}) e provê funcionalidades globais ao documento (como obter a URL da página e criar novos elementos no documento).

+ +

{{inheritanceDiagram}}

+ +

Um objeto document pode ser obtido por meio de várias APIs:

+ + + +

Dependendo do tipo do documento (e.g. HTML ou XML), diferentes APIs estarão disponívels no objeto Document.

+ +

Todo objeto Document implementa a interface Document (e consequentemente as interfaces {{domxref("Node")}} e {{domxref("EventTarget")}}). Portanto, as principais propriedades e métodos documentados nesta página estarão disponíveis para todos os tipos de documents.

+ + + +

No futuro, todas essas interfaces irão ser divididas na interface Document.

+ +

Propriedades

+ +
+

Nota: A interface Document também herda das interfaces {{domxref("Node")}} e {{domxref("EventTarget")}}.

+
+ +
+
{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
+
Da acesso a todos os elementos do documento.È uma interface legada não padrão, voce deve usar o método {{domxref("Document.getElementById()")}} como alternativa.
+
{{domxref("Document.async")}} {{Deprecated_inline}}
+
Usado como {{domxref("document.load")}} que indica uma requisição asyncroma.
+
{{domxref("Document.characterSet")}} {{experimental_inline}}
+
Retorna a codificação de caracteres que está sendo usado pelo documento.
+
{{domxref("Document.compatMode")}} {{experimental_inline}}
+
indica se o documento é renderizado no modo Quirks ou Strict.
+
{{domxref("Document.contentType")}} {{experimental_inline}}
+
Retorna o tipo de conteúdo do cabeçalho MIME do documento atual.
+
{{domxref("Document.doctype")}}
+
Retorna o nome do tipo de conteudo do documento HTML.
+
{{domxref("Document.documentElement")}}
+
Returns the Element that is a direct child of the document. For HTML documents, this is normally the HTML element.
+
{{domxref("Document.documentURI")}}
+
Returns the document URL.
+
{{domxref("Document.domConfig")}} {{Deprecated_inline}}
+
Should return a {{domxref("DOMConfiguration")}} object.
+
{{domxref("Document.implementation")}}
+
Returns the DOM implementation associated with the current document.
+
{{domxref("Document.inputEncoding")}} {{Deprecated_inline}}
+
Returns the encoding used when the document was parsed.
+
{{domxref("Document.lastStyleSheetSet")}}
+
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")}}
+
true if this document is synthetic, such as a standalone image, video, audio file, or the like.
+
{{domxref("Document.mozFullScreen")}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
true when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.
+
{{domxref("Document.mozFullScreenElement")}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
The element that's currently in full screen mode for this document.
+
{{domxref("Document.mozFullScreenEnabled")}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
true if calling {{domxref("element.mozRequestFullscreen()")}} would succeed in the curent document.
+
{{domxref("Document.pointerLockElement")}} {{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")}}
+
Returns the preferred style sheet set as specified by the page author.
+
{{domxref("Document.selectedStyleSheetSet")}}
+
Returns which style sheet set is currently in use.
+
{{domxref("Document.styleSheets")}}
+
Returns a list of the style sheet objects on the current document.
+
{{domxref("Document.styleSheetSets")}}
+
Returns a list of the style sheet sets available on the document.
+
{{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")}}

+ +

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.activeElement")}}
+
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")}}
+
Returns a reference to the window object.
+
{{domxref("Document.designMode")}}
+
Gets/sets the ability to edit the whole document.
+
{{domxref("Document.dir")}}
+
Gets/sets directionality (rtl/ltr) of the document.
+
{{domxref("Document.domain")}}
+
Returns the domain of the current document.
+
{{domxref("Document.embeds")}}
+
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")}}
+
Returns a list of the {{HTMLElement("form")}} elements within the current document.
+
{{domxref("Document.head")}}
+
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")}}
+
Returns a list of the images in the current document.
+
{{domxref("Document.lastModified")}}
+
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")}}
+
Returns a list of all the hyperlinks in the document.
+
{{domxref("Document.location")}}
+
Returns the URI of the current document.
+
{{domxref("Document.plugins")}}
+
Returns a list of the available plugins.
+
{{domxref("Document.readyState")}} {{gecko_minversion_inline("1.9.2")}}
+
Returns loading status of the document.
+
{{domxref("Document.referrer")}}
+
Returns the URI of the page that linked to this page.
+
{{domxref("Document.scripts")}}
+
Returns all the {{HTMLElement("script")}} elements on the document.
+
{{domxref("Document.title")}}
+
Returns the title of the current document.
+
{{domxref("Document.URL")}}
+
Returns a string containing the URL of the current document.
+
{{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.onpointerlockchange")}} {{experimental_inline}}
+
Returns the event handling code for the {{event("pointerlockchange")}} event.
+
{{domxref("Document.onpointerlockerror")}} {{experimental_inline}}
+
Returns the event handling code for the {{event("pointerlockerror")}} event.
+
{{domxref("Document.onreadystatechange")}} {{gecko_minversion_inline("1.9.2")}}
+
Returns the event handling code for the readystatechange event.
+
+ +

Methods

+ +
+

Note: The Document interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

+
+ +
+
{{domxref("Document.adoptNode","Document.adoptNode(Node node)")}}
+
Adopt node from an external document.
+
{{domxref("Document.captureEvents","Document.captureEvents(String eventName)")}} {{Deprecated_inline}}
+
See {{domxref("window.captureEvents")}}.
+
{{domxref("Document.caretPositionFromPoint","Document.caretPositionFromPoint(Number x, Number y)")}}
+
Gets a {{domxref("CaretPosition")}} based on two coordinates.
+
{{domxref("Document.createAttribute","Document.createAttribute(String name)")}}
+
Creates a new {{domxref("Attr")}} object and returns it.
+
{{domxref("Document.createAttributeNS","Document.createAttributeNS(String namespace, String name)")}}
+
Creates a new attribute node in a given namespace and returns it.
+
{{domxref("Document.createCDATASection","Document.createCDATASection(String data)")}}
+
Creates a new CDATA node and returns it.
+
{{domxref("Document.createComment","Document.createComment(String comment)")}}
+
Creates a new comment node and returns it.
+
{{domxref("Document.createDocumentFragment()")}}
+
Creates a new document fragment.
+
{{domxref("Document.createElement","Document.createElement(String name)")}}
+
Creates a new element with the given tag name.
+
{{domxref("Document.createElementNS","Document.createElementNS(String namespace, String name)")}}
+
Creates a new element with the given tag name and namespace URI.
+
{{domxref("Document.createEntityReference","Document.createEntityReference(String name)")}} {{obsolete_inline}}
+
Creates a new entity reference object and returns it.
+
{{domxref("Document.createEvent","Document.createEvent(String interface)")}}
+
Creates an event object.
+
{{domxref("Document.createNodeIterator","Document.createNodeIterator(Node root[, Number whatToShow[, NodeFilter filter]])")}}
+
Creates a {{domxref("NodeIterator")}} object.
+
{{domxref("Document.createProcessingInstruction","Document.createProcessingInstruction(String target, String data)")}}
+
Creates a new {{domxref("ProcessingInstruction")}} object.
+
{{domxref("Document.createRange()")}}
+
Creates a {{domxref("Range")}} object.
+
{{domxref("Document.createTextNode","Document.createTextNode(String text)")}}
+
Creates a text node.
+
{{domxref("Document.createTreeWalker","Document.createTreeWalker(Node root[, Number whatToShow[, NodeFilter filter]])")}}
+
Creates a {{domxref("TreeWalker")}} object.
+
{{domxref("Document.elementFromPoint","Document.elementFromPoint(Number x, Number y)")}}
+
Returns the element visible at the specified coordinates.
+
{{domxref("Document.enableStyleSheetsForSet","Document.enableStyleSheetsForSet(String name)")}}
+
Enables the style sheets for the specified style sheet set.
+
{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}
+
Release the pointer lock.
+
{{domxref("Document.getElementsByClassName","Document.getElementsByClassName(String className)")}}
+
Returns a list of elements with the given class name.
+
{{domxref("Document.getElementsByTagName","Document.getElementsByTagName(String tagName)")}}
+
Returns a list of elements with the given tag name.
+
{{domxref("Document.getElementsByTagNameNS","Document.getElementsByTagNameNS(String namespace, String tagName)")}}
+
Returns a list of elements with the given tag name and namespace.
+
{{domxref("Document.importNode","Document.importNode(Node node, Boolean deep)")}}
+
Returns a clone of a node from an external document.
+
{{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.
+
{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}
+
Replaces entities, normalizes text nodes, etc.
+
{{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")}}.
+
+ +

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 formatting command.
+
{{domxref("Document.registerElement","Document.registerElement(String tagname[, Object options])")}}
+
Registers a new custom element in the browser and returns a constructor for the new element.
+
{{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.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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('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
+ +

Browser compatibility

+ +

Firefox notes

+ +

Mozilla defines a set of non-standard properties made only for XUL content:

+ +
+
{{domxref("document.currentScript")}} {{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")}} {{Fx_minversion_inline("1.5")}}
+
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")}}.
+
+ +

Internet Explorer notes

+ +

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-br/web/api/document/keydown_event/index.html b/files/pt-br/web/api/document/keydown_event/index.html new file mode 100644 index 0000000000..4abd69eab7 --- /dev/null +++ b/files/pt-br/web/api/document/keydown_event/index.html @@ -0,0 +1,178 @@ +--- +title: keydown +slug: Web/API/Document/keydown_event +translation_of: Web/API/Document/keydown_event +--- +

O evento keydown é disparado quando uma tecla é pressionada. Diferente do evento keypress, o keydown é disparado para teclas que produzem e que não produzem um caractere.

+ +

Informações gerais

+ +
+
Especificação
+
DOM L3
+
Interface
+
KeyboardEvent
+
Burbulha
+
Sim
+
Cancelável
+
Sim
+
Alvo
+
Document, Element
+
Ação Padrão
+
Variações: evento keypress; carrega sistema de composição de texto; eventos blur e focus; evento DOMActivate; outro evento
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadeTipoDescrição
target {{readonlyInline}}EventTargetO alvo do evento (o alvo de nível mais alto na árvore DOM).
type {{readonlyInline}}DOMStringO tipo do evento.
bubbles {{readonlyInline}}BooleanSe o evento normalmente burbulha ou não
cancelable {{readonlyInline}}BooleanSe o evento é cancelável ou não
view {{readonlyInline}}WindowProxydocument.defaultView (window do documento)
detail {{readonlyInline}}long (float)0.
target {{readonlyInline}}EventTarget (elemento DOM)Elemento focado processando o evento, elemento raiz se nenhum elemento input adequado está focado.
char {{readonlyInline}}DOMString (string)O caractere correspondente à tecla. Se a tecla corresponde a um caractere imprimível, este valor é uma string Unicode não vazia, contendo o caractere. Se a tecla não tem uma representação imprimível, o valor é uma string vazia. Veja key names and char values para detalhes. +
Nota: Se a tecla for usada como uma macro que insere múltiplos caracteres, o valor deste atributo é toda a string, não apenas o primeiro caractere.
+
key {{readonlyInline}}DOMString (string)O valor da tecla pressionada. Se a tecla tem uma representação imprimível, o valor deste atributo é o mesmo do atributo char. Caso contrário, é uma das strings key especificadas em Key Values. Se a tecla não pode ser identificada, o valor do atributo é a string "Unidentified". Veja key names and char values para detalhes. Somente Leitura.
code {{readonlyInline}}DOMString (string)Mantém uma string que identifica a tecla física sendo pressionada. O valor não é afetado pelo layout atual do teclado ou estado de modificador, portando uma tecla particular sempre retornará o mesmo valor. 
charCode {{readonlyInline}}Unsigned long (int)O número de referência Unicode da tecla; este atributo é usado somente pelo evento keypress. Para teclas cujo atributo char contém múltiplos caracteres, este é o valor Unicode do primeiro caractere daquele atributo. +
Aviso: Este atributo está obsoleto; você deve usar char no lugar, se disponível.
+
keyCode {{readonlyInline}}Unsigned long (int)Um código numérico, dependente do sistema e da implementação, identificando o valor não modificado da tecla pressionada. Este é usualmente o código decimal ASCII ({{ RFC(20) }}) ou código Windows 1252 correspondente à tecla; veja {{ anch("Virtual key codes") }} para uma lista de valores comuns. Se a tecla não pode ser identificada, este valor é 0. +
Aviso: Este atributo está obsoleto; você deve usar key no lugar, se disponível.
+
which {{readonlyInline}}Unsigned long (int)Um código numérico, dependente do sistema e da implementação, identificando o valor não modificado da tecla pressionada; este é usualmente o mesmo que keyCode. +
Aviso: Este atributo está obsoleto; você deve usar key no lugar, se disponível.
+
location {{readonlyInline}}long (float)A localização da tecla no dispositivo.
repeat {{readonlyInline}}booleantrue se a tecla foi pressionada tempo suficiente para disparar repetição de tecla, false caso contrário.
locale {{readonlyInline}}stringO código do idioma para o evento, se disponível; uma string vazia caso contrário.
ctrlKey {{readonlyInline}}booleantrue se a tecla control estava pressionada quando o evento foi disparado. false caso contrário.
shiftKey {{readonlyInline}}booleantrue se a tecla shift estava pressionada quando o evento foi disparado. false caso contrário.
altKey {{readonlyInline}}booleantrue se a tecla alt estava pressionada quando o evento foi disparado. false caso contrário.
metaKey {{readonlyInline}}booleantrue se a tecla meta estava pressionada quando o evento foi disparado. false caso contrário.
+ +

preventDefault() do evento keydown

+ +

Iniciando com o Gecko 25, uma chamada para o método preventDefault() do evento keydown evita dispachar o evento keypress seguinte. Este é um comportamento válido para a especificação D3E e os principais navegadores web se comportam desta forma. Por outro lado, o Gecko 24 e anteriores dispachavam o evento keypress mesmo que o método preventDefault() do evento keydown anterior fosse chamado, embora o atributo  defaultPrevented do evento keypress fosse true neste caso.

+ +

Eventos Relacionados

+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+<script>
+
+'use strict';
+
+document.addEventListener('keydown', (event) => {
+  const keyName = event.key;
+  alert('keydown event\n\n' + 'key: ' + keyName);
+});
+
+</script>
+</head>
+<body>
+</body>
+</html>
diff --git a/files/pt-br/web/api/document/keypress_event/index.html b/files/pt-br/web/api/document/keypress_event/index.html new file mode 100644 index 0000000000..e22242028b --- /dev/null +++ b/files/pt-br/web/api/document/keypress_event/index.html @@ -0,0 +1,170 @@ +--- +title: keypress +slug: Web/API/Document/keypress_event +translation_of: Web/API/Document/keypress_event +--- +
{{APIRef}}
+ +

O evento keypress é disparado quando uma tecla que produz um valor do tipo caractere é pressionada. Exemplos de chaves que produzem um valor de caractere são chaves alfabéticas, numéricas e de pontuação. Exemplos de chaves que não produzem um valor de caractere são as teclas modificadoras, como Alt, Shift, Ctrl, ou Meta.

+ +

Informações gerais

+ +
+
Especificação
+
DOM L3 {{deprecated_inline ()}}
+
Interface
+
KeyboardEvent
+
Bolhas
+
sim
+
Cancelável
+
sim
+
Alvo
+
Documento, Elemento
+
Ação padrão
+
Varia: keypressevento; lançar sistema de composição de texto; blure focuseventos; DOMActivateevento; outro evento
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadeTipoDescrição
target {{readonlyInline}}EventTargetO destino do evento (o destino mais alto na árvore do DOM).
type {{readonlyInline}}DOMStringO tipo de evento.
bubbles {{readonlyInline}}boleanoSe o evento normalmente borbulha ou não
cancelable {{readonlyInline}}boleanoSe o evento é cancelável ou não
view {{readonlyInline}}WindowProxydocument.defaultView( windowdo documento)
detail {{readonlyInline}}long( float)0
target {{readonlyInline}}EventTarget (elemento DOM)Elemento focalizado processando o evento chave, elemento raiz se nenhum elemento de entrada adequado estiver focalizado.
char {{readonlyInline}}DOMString (string)O valor do caractere da chave. Se a chave corresponder a um caractere imprimível, esse valor será uma string Unicode não vazia contendo esse caractere. Se a chave não tiver uma representação imprimível, esta é uma string vazia. Veja nomes de chaves e valores de caracteres para os detalhes. +
Nota: Se a chave for usada como uma macro que insere vários caracteres, o valor desse atributo é a cadeia inteira, não apenas o primeiro caractere.
+
key {{readonlyInline}}DOMString (string) +

O valor-chave da chave representada pelo evento. Se o valor tiver uma representação impressa, o valor desse atributo será o mesmo da charpropriedade. Caso contrário, é uma das cadeias de valores de chave especificadas nos valores de chave . Se a chave não puder ser identificada, seu valor será a string "Unidentified". Veja os nomes das chaves e os valores de caracteres para mais detalhes. Somente leitura.

+
code {{readonlyInline}}DOMString (string)Contém uma string que identifica a tecla física sendo pressionada. O valor não é afetado pelo layout do teclado atual ou pelo estado do modificador, portanto, uma chave específica sempre retornará o mesmo valor.
charCode {{readonlyInline}}Longo não assinado (int)O número de referência Unicode da chave; esse atributo é usado apenas pelo keypressevento. Para chaves cujo charatributo contém vários caracteres, esse é o valor Unicode do primeiro caractere nesse atributo. +
Aviso: este atributo está obsoleto; você deve usar em charvez disso, se disponível.
+
keyCode {{readonlyInline}}Longo não assinado (int)Um código numérico dependente do sistema e da implementação que identifica o valor não modificado da tecla pressionada. Este é geralmente o código ASCII decimal ({{RFC (20)}}) ou Windows 1252 correspondente à chave; veja {{anch ("Códigos de teclas virtuais")}} para uma lista de valores comuns. Se a chave não puder ser identificada, esse valor será 0. +
Aviso: este atributo está obsoleto; você deve usar em keyvez disso, se disponível.
+
which {{readonlyInline}}Longo não assinado (int)Um código numérico dependente do sistema e da implementação identificando o valor não modificado da tecla pressionada; isso geralmente é o mesmo que keyCode. +
Aviso: este atributo está obsoleto; você deve usar em keyvez disso, se disponível.
+
location {{readonlyInline}}longo (flutuar)A localização da chave no dispositivo.
repeat {{readonlyInline}}boleanotruese uma tecla foi pressionada o tempo suficiente para disparar a repetição da tecla, caso contrário false.
locale {{readonlyInline}}cordaO código do idioma para o evento principal, se disponível; caso contrário, a cadeia vazia.
ctrlKey {{readonlyInline}}boleanotruese a chave de controle estava inativa quando o evento foi disparado. falsede outra forma.
shiftKey {{readonlyInline}}boleanotruese a tecla shift estava inativa quando o evento foi disparado. falsede outra forma.
altKey {{readonlyInline}}boleanotruese a tecla ALT estava desativada quando o evento foi disparado. falsede outra forma.
metaKey {{readonlyInline}}boleanotruese a meta key estava desativada quando o evento foi disparado. falsede outra forma.
+ +

Exemplo

+ +
document.addEventListener ('keypress', (event) => {
+  const keyName = event.key;
+  alert ('keypress event \ n \ n' + 'chave:' + nome da chave);
+});
+
+ +

Compatibilidade do navegador

+ +

O Chrome não dispara o keypressevento para atalhos de teclado conhecidos ( referência ). Quais atalhos de teclado são conhecidos depende do sistema do usuário. Use o keydownevento para implementar atalhos de teclado.

+ +

Eventos Relacionados

+ + diff --git a/files/pt-br/web/api/document/keyup_event/index.html b/files/pt-br/web/api/document/keyup_event/index.html new file mode 100644 index 0000000000..6423993b63 --- /dev/null +++ b/files/pt-br/web/api/document/keyup_event/index.html @@ -0,0 +1,151 @@ +--- +title: keyup +slug: Web/API/Document/keyup_event +tags: + - Evento de teclado +translation_of: Web/API/Document/keyup_event +--- +

O evento keyup é acionado quando uma tecla é liberada.

+ +

Informações gerais

+ +
+
Especificação
+
DOM L3
+
Interface
+
KeyboardEvent
+
Método Bolha
+
Sim
+
Cancelável
+
Sim
+
Alvo
+
Documento, Elemento
+
Ação Padrão
+
Nenhuma
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not?
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
target {{readonlyInline}}EventTarget (DOM element)Focused element processing the key event, root element if no suitable input element focused.
char {{readonlyInline}}DOMString (string)The character value of the key. If the key corresponds to a printable character, this value is a non-empty Unicode string containing that character. If the key doesn't have a printable representation, this is an empty string. See key names and char values for the detail. +
Note: If the key is used as a macro that inserts multiple characters, this attribute's value is the entire string, not just the first character.
+
key {{readonlyInline}}DOMString (string)The key value of the key represented by the event. If the value has a printed representation, this attribute's value is the same as the char attribute. Otherwise, it's one of the key value strings specified in {{ anch("Key values") }}. If the key can't be identified, this is the string "Unidentified". See key names and char values for the detail. Read Only.
charCode {{readonlyInline}}Unsigned long (int)The Unicode reference number of the key; this attribute is used only by the keypress event. For keys whose char attribute contains multiple characters, this is the Unicode value of the first character in that attribute. +
Warning: This attribute is deprecated; you should use char instead, if available.
+
keyCode {{readonlyInline}}Unsigned long (int)A system and implementation dependent numerical code identifying the unmodified value of the pressed key. This is usually the decimal ASCII ({{ RFC(20) }}) or Windows 1252 code corresponding to the key; see {{ anch("Virtual key codes") }} for a list of common values. If the key can't be identified, this value is 0. +
Warning: This attribute is deprecated; you should use key instead, if available.
+
which {{readonlyInline}}Unsigned long (int)A system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as keyCode. +
Warning: This attribute is deprecated; you should use key instead, if available.
+
location {{readonlyInline}}long (float)The location of the key on the device.
repeat {{readonlyInline}}booleantrue if a key has been depressed long enough to trigger key repetition, otherwise false.
locale {{readonlyInline}}stringThe language code for the key event, if available; otherwise, the empty string.
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

Eventos Relacionados

+ + diff --git a/files/pt-br/web/api/document/location/index.html b/files/pt-br/web/api/document/location/index.html new file mode 100644 index 0000000000..ebf1f2aa27 --- /dev/null +++ b/files/pt-br/web/api/document/location/index.html @@ -0,0 +1,108 @@ +--- +title: Document.location +slug: Web/API/Document/location +translation_of: Web/API/Document/location +--- +

{{APIRef("DOM")}}

+ +

A propriedade, de apenas leitura, Document.location retorna um objeto {{domxref("Location")}}, que contém informações sobre a URL do documento e provém métodos para mudar a URL e carregar outra URL.

+ +

Embora Document.location seja um objeto Location de apenas leitura,  você pode atribuir um {{domxref("DOMString")}} para ele. Isso significa que você pode trabalhar com document.location, na maioria dos casos, como se fosse uma string: document.location = 'http://www.example.com' é um sinônimo de document.location.href = 'http://www.example.com'.

+ +

Para recuperar somente a URL como uma string, a propriedade de apenas leitura {{domxref("document.URL")}} pode ser utilizada.

+ +

Se o documento atual não estiver no contexto de navegação, o valor retornado será null.

+ +

Sintaxe

+ +
locationObj = document.location
+document.location = 'http://www.mozilla.org' // Equivalente a document.location.href = 'http://www.mozilla.org'
+
+ +

Exemplo

+ +
dump(document.location);
+// Imprime uma string como
+// "http://www.example.com/juicybits.html" to the console
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "history.html#the-location-interface", "Document.location")}}{{Spec2('HTML WHATWG')}}Nenhuma mudança de {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Document.location")}}{{Spec2('HTML5 W3C')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + + +

 

diff --git a/files/pt-br/web/api/document/origin/index.html b/files/pt-br/web/api/document/origin/index.html new file mode 100644 index 0000000000..b31decf05f --- /dev/null +++ b/files/pt-br/web/api/document/origin/index.html @@ -0,0 +1,60 @@ +--- +title: Document.origin +slug: Web/API/Document/origin +translation_of: Web/API/Document/origin +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

A propriedade read-only Document.origin retorna a origem do documento. Na maioria dos casos, essa propriedade é equivalente a document.defaultView.location.origin.

+ +

Sintaxe

+ +
var origin = document.origin;
+ +

Exemplos

+ +
var origin = document.origin;
+// Nesta página, retorna:'https://developer.mozilla.org'
+
+var origin = document.origin;
+// Em "about:blank", retorna:'null'
+
+var origin = document.origin;
+// Em "data:text/html,<b>foo</b>", retorna:'null'
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-document-origin', 'Document.origin')}}{{Spec2('DOM WHATWG')}}Definição inicial.
{{SpecName('HTML WHATWG', '#concept-origin', 'origin for various objects (including Document objects)')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ +

Compatibilidade entre navegadores

+ + + +
{{Compat("api.Document.origin")}}
+ +

Veja também 

+ + diff --git a/files/pt-br/web/api/document/queryselector/index.html b/files/pt-br/web/api/document/queryselector/index.html new file mode 100644 index 0000000000..4489a2e823 --- /dev/null +++ b/files/pt-br/web/api/document/queryselector/index.html @@ -0,0 +1,107 @@ +--- +title: Document.querySelector() +slug: Web/API/Document/querySelector +translation_of: Web/API/Document/querySelector +--- +
+
{{ ApiRef("DOM") }}
+
+ +

Sumário

+ +

Retorna o primeiro elemento dentro do documento (usando ordenação em profundidade, pré-ordenada e transversal dos nós do documento) que corresponde ao grupo especificado de seletores.

+ +

Sintaxe

+ +
element = document.querySelector(selectors);
+ +

Onde:

+ + + +

Exemplo

+ +

Neste exemplo, o primeiro elemento no documento com a classe "myclass" é retornado:

+ +
var el = document.querySelector(".myclass");
+
+ +

Notas

+ +

Retorna null se nenhum resultado for encontrado; caso contrário, retorna o primeiro elemento correspondente.

+ +

Se o seletor utilizado for um ID e este ID foi erroneamente utilizado várias vezes no documento, ele retorna somente o primeiro elemento correspondente.

+ +

Gera uma exceção SYNTAX_ERR se o grupo de seletores utilizado for inválido.

+ +

querySelector() foi introduzido com a API de seletores.

+ +

Compatibilidade dos navegadores

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support13.5 (1.9.1)
+ {{bug(416317)}}
8103.2 (525.3)
+ {{Webkitbug("16587")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1yes910.03.2
+
+ +

Especificação

+ + + +

Veja também:

+ + diff --git a/files/pt-br/web/api/document/queryselectorall/index.html b/files/pt-br/web/api/document/queryselectorall/index.html new file mode 100644 index 0000000000..0a05a06180 --- /dev/null +++ b/files/pt-br/web/api/document/queryselectorall/index.html @@ -0,0 +1,110 @@ +--- +title: Document.querySelectorAll() +slug: Web/API/Document/querySelectorAll +tags: + - CSS + - JavaScript + - querySelector +translation_of: Web/API/Document/querySelectorAll +--- +

{{ ApiRef("DOM") }}

+ +

Introdução

+ +

Retorna uma lista de elementos presentes no documento (usando ordenação em profundidade, pré-ordenada e transversal dos nós do documento) que coincidam com o grupo de seletores especificado. O objeto retornado é uma {{ domxref("NodeList") }}.

+ +

Sintaxe

+ +
elementList = document.querySelectorAll(selectors);
+
+ +

onde

+ + + +

A NodeList retornada irá conter todos os elementos do documento que coincidam com os seletores especificados. Se a string selectors conter um CSS {{ cssxref("PseudoElements") }}, o retorno será uma NodeList vazia.

+ +

Exemplo

+ +

Esse exemplo retorna uma lista de todos os elementos div presentes no document que contenham as classes "note" ou "alert":

+ +
var matches = document.querySelectorAll("div.note, div.alert");
+
+ +

Notas

+ +

Retorna uma {{ jsxref("NodeList") }} não-viva (alterações no DOM não refletem na lista) de todos os elementos que coincidam com os seletores informados.

+ +

Lança uma exceção SYNTAX_ERR se o grupo especificado de seletores for inválido.

+ +

querySelectorAll() foi introduzida na WebApps API.

+ +

Navegadores baseados em WebKit têm um bug: quando a string seletores contém um pseudo-elemento CSS, a {{ jsxref("NodeList") }} retornada não esta vazia, neste caso ela contém o elemento {{ HTMLElement("html") }}.

+ +

Compatibilidade nos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
PossuiChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13.5 (1.9.1)8103.2 (525.3)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
PossuiAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico2.1sim910.03.2
+
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/readystate/index.html b/files/pt-br/web/api/document/readystate/index.html new file mode 100644 index 0000000000..d5d2cea5cd --- /dev/null +++ b/files/pt-br/web/api/document/readystate/index.html @@ -0,0 +1,102 @@ +--- +title: Document.readyState +slug: Web/API/Document/readyState +tags: + - API + - HTML DOM + - Propriedade + - Referencia + - eventos +translation_of: Web/API/Document/readyState +--- +
{{APIRef("DOM")}} {{ gecko_minversion_header("1.9.2") }}
+ +

Sumário

+ +

Retorna "loading" enquanto {{ domxref("document") }} está carregando, "interactive" quando foi carregado porém seus sub-recursos (como imagens, por exemplo) ainda não, e "complete" quando foi totalmente carregado.

+ +
O evento readystatechange é acionado no objeto {{ domxref("document") }} quando esse valor é alterado.
+ +

Sintaxe

+ +
var string = document.readyState;
+
+ + + +

Valores

+ +

readyState de um documento pode ser um dos seguintes:

+ +
+
loading
+
O {{domxref("document")}} ainda está carregando.
+
interactive
+
O documento terminou de ser carregado e o documento foi analisado, mas sub-recursos, como imagens, folhas de estilo e quadros, ainda estão sendo carregados.
+
complete
+
O documento e todos os sub-recursos terminaram de carregar. O estado indica que o {{event("load")}} evento está prestes a disparar.
+
+ + + +

Exemplos

+ +

Diferentes estados de readyState

+ +
switch (document.readyState) {
+  case "loading":
+    // O documento esta carregando
+    break;
+  case "interactive":
+    // O documento acabou de carregar. Nós podemos acessar os elementos do DOM.
+    // mas sub-recursos, como imagens, folhas de estilo e quadros, ainda estão sendo carregados.
+    var span = document.createElement("span");
+    span.textContent = "A <span> element.";
+    document.body.appendChild(span);
+    break;
+  case "complete":
+    // A pagina carregou por completo.
+    console.log("The first CSS rule is: " + document.styleSheets[0].cssRules[0].cssText);
+    break;
+}
+ +

readystatechange como uma alternativa para DOMContentLoaded evento

+ +
// alternativa para DOMContentLoaded evento
+document.onreadystatechange = function () {
+  if (document.readyState === 'interactive') {
+    initApplication();
+  }
+}
+ +

readystatechange como uma alternativa para load evento

+ +
// ternativa para load evento
+document.onreadystatechange = function () {
+  if (document.readyState === 'complete') {
+    initApplication();
+  }
+}
+ +

readystatechange como ouvinte de evento para inserir ou modificar o DOM antes de DOMContentLoaded

+ +
document.addEventListener('readystatechange', event => {
+  if (event.target.readyState === 'interactive') {
+    initLoader();
+  }
+  else if (event.target.readyState === 'complete') {
+    initApp();
+  }
+});
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/referrer/index.html b/files/pt-br/web/api/document/referrer/index.html new file mode 100644 index 0000000000..cbf8da950d --- /dev/null +++ b/files/pt-br/web/api/document/referrer/index.html @@ -0,0 +1,33 @@ +--- +title: Document.referrer +slug: Web/API/Document/referrer +tags: + - API + - Anterior + - HTML DOM + - NeedsCompatTable + - NeedsMarkupWork + - NeedsSpecTable + - Propriedade + - Página(2) + - Referência(2) +translation_of: Web/API/Document/referrer +--- +
{{APIRef("DOM")}}
+ +

Retorna o URI da página que continha o link para a página atual.

+ +

Sintaxe

+ +
string = document.referrer;
+
+ +

Notas

+ +

O valor retornado será uma string vazia se o usuário tiver chegado na página diretamente (digitando o endereço no navegador ou como um item "Favorito"). Como essa propriedade retorna apenas uma string, ela não dá acesso DOM à página que fez a referência.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/scripts/index.html b/files/pt-br/web/api/document/scripts/index.html new file mode 100644 index 0000000000..f896f837e8 --- /dev/null +++ b/files/pt-br/web/api/document/scripts/index.html @@ -0,0 +1,84 @@ +--- +title: Document.scripts +slug: Web/API/Document/scripts +translation_of: Web/API/Document/scripts +--- +
+
{{ ApiRef("DOM") }}
+
+ +

Retorna uma lista dos elementos {{HTMLElement("script")}} no documento. O objeto retornado é um {{domxref("HTMLCollection")}}.

+ +

Sintaxe

+ +
var scriptList = document.scripts;
+
+ +

O scriptList retornado é um {{domxref("HTMLCollection")}}. Você pode usar isso apenas como um array para obter todos os elementos da lista.

+ +

Exemplo

+ +

Este exemplo é para ver se a página contém elementos {{HTMLElement("script")}}.

+ +
var scripts = document.scripts;
+
+if (scripts.length) {
+  alert("This page has scripts!");
+}
+
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/url/index.html b/files/pt-br/web/api/document/url/index.html new file mode 100644 index 0000000000..e4a1d2eab7 --- /dev/null +++ b/files/pt-br/web/api/document/url/index.html @@ -0,0 +1,19 @@ +--- +title: Document.URL +slug: Web/API/Document/URL +translation_of: Web/API/Document/URL +--- +
{{APIRef("DOM")}}
+ +

A propriedade URL (usada apenas para leitura) da Interface {{domxref("Document")}} retorna a URL atual do navegador como um texto (string).

+ +

Síntaxe

+ +
var url_atual = document.URL
+
+ +

Documentação

+ + diff --git a/files/pt-br/web/api/document/write/index.html b/files/pt-br/web/api/document/write/index.html new file mode 100644 index 0000000000..4218430e88 --- /dev/null +++ b/files/pt-br/web/api/document/write/index.html @@ -0,0 +1,108 @@ +--- +title: Document.write() +slug: Web/API/Document/write +tags: + - API + - DOM + - Method + - Reference +translation_of: Web/API/Document/write +--- +
{{ApiRef("DOM")}}
+ +

O método Document.write() grava uma sequência de caracteres em um documento aberto por {{domxref("document.open()")}}.

+ +
Nota: à medida que document.write grava no fluxo de documentos, chamando document.write em um documento fechado (carregado) invoca automaticamente document.open, que limpará o documento.
+ +

Sintaxe

+ +
document.write(markup);
+
+ +

Parametros

+ +
+
markup
+
Uma string contendo o texto a ser gravado no documento.
+
+ +

Exemplo

+ +
<html>
+
+<head>
+  <title>Escreva exemplo</title>
+
+  <script>
+    function newContent() {
+      document.open();
+      document.write("<h1>Sair com o velho - entrar com o novo!</h1>");
+      document.close();
+    }
+  </script>
+</head>
+
+<body onload="newContent();">
+  <p>Algum conteúdo do documento original.</p>
+</body>
+
+</html>
+
+ +

{{EmbedLiveSample("Syntax")}}

+ +

Notas

+ +

Escrevendo em um documento que já foi carregado sem chamar {{domxref("document.open()")}} automaticamente vai chamar document.open. Ao términno da escrita, é recomendável chamar {{domxref("document.close()")}} para dizer ao navegador para encerrar o carregamento da página. O texto que você escreve é analisado no modelo de estrutura do documento. No exemplo acima, o elemento h1 se torna um nó (node) no documento.

+ +

Se chamar document.write() incorporada em uma tag HTML <script> embutida, então document.open() não será chamada. Por exemplo:

+ +
<script>
+  document.write("<h1>Título principal</h1>")
+</script>
+
+ +
Nota: document.write e {{domxref("document.writeln")}} não funcionam em documentos XHTML (você receberá o erro "Operation is not supported" [NS_ERROR_DOM_NOT_SUPPORTED_ERR] no console de erros). Isso acontece ao abrir um arquivo local com a extensão .xhtml ou em qualquer documento exibido com um MIME type application/xhtml+xml {{Glossary("MIME type")}}. Mais informações disponíveis em W3C XHTML FAQ.
+ +
Nota: document.write em deferred ou asynchronous scripts será ignorado, e você receberá uma mensagem como "A call to document.write() from an asynchronously-loaded external script was ignored" no console de erros.
+ +
Nota: Somente no Edge, chamando document.write mais de uma vez em {{HTMLElement("iframe")}} causa o erro "SCRIPT70: Permission denied".
+ +
Nota: A partir de 55, Chrome não executará elementos <script> injetados via document.write() caso haja falta de cache HTTP para usuários em uma conexão 2G. Há uma lista de condições que precisam ser atendidas para que isso seja verdade.
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentario
{{SpecName("HTML WHATWG", "#dom-document-write", "document.write(...)")}}{{Spec2("HTML WHATWG")}}
{{SpecName("DOM2 HTML", "html.html#ID-75233634", "document.write(...)")}}{{Spec2("DOM2 HTML")}}
+ +

Compatibilidade de Browser

+ + + +
{{Compat("api.Document.write")}}
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/writeln/index.html b/files/pt-br/web/api/document/writeln/index.html new file mode 100644 index 0000000000..ed2efb2b85 --- /dev/null +++ b/files/pt-br/web/api/document/writeln/index.html @@ -0,0 +1,43 @@ +--- +title: Document.writeln() +slug: Web/API/Document/writeln +tags: + - API + - DOM + - Gecko + - Referencia + - metodo +translation_of: Web/API/Document/writeln +--- +
{{ ApiRef("DOM") }}
+ +

Grava uma seqüência de texto, seguido por um caractere de nova linha a um documento.

+ +

Sintaxes

+ +
document.writeln(line);
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
document.writeln("<p>enter password:</p>");
+
+ +

Notas

+ +

document.writeln é o mesmo que document.write mas acrescenta uma nova linha.

+ +
Note: document.writeln (like document.write) does not work in XHTML documents (you'll get a "Operation is not supported" (NS_ERROR_DOM_NOT_SUPPORTED_ERR) error on the error console). This is the case if opening a local file with a .xhtml file extension or for any document served with an application/xhtml+xml MIME type. More information is available in the W3C XHTML FAQ.
+ +

Especificação

+ +

writeln

diff --git a/files/pt-br/web/api/documentfragment/index.html b/files/pt-br/web/api/documentfragment/index.html new file mode 100644 index 0000000000..5744ea8afe --- /dev/null +++ b/files/pt-br/web/api/documentfragment/index.html @@ -0,0 +1,234 @@ +--- +title: DocumentFragment +slug: Web/API/DocumentFragment +translation_of: Web/API/DocumentFragment +--- +

{{ ApiRef("DOM") }}

+ +

A interface do DocumentFragment representa um objeto de documento mínimo que não possui pai. Ela é utilizada como uma versão leve de {{domxref("Document")}} para armazenar fragmentos bem formados ou fragments potencialmente mal formados de XML.

+ +

Vários outros métodos podem usar um document fragment como argumento (ex. qualquer interface de {{domxref("Node")}} como {{domxref("Node.appendChild")}} e {{domxref("Node.insertBefore")}}) em casos em que os filhos do fragment são acrescentados ou inseridos, e não o próprio fragment.

+ +

Essa interface também é excelente para ser usada com Web components: elementos {{HTMLElement("template")}}  contém um DocumentFragment na propriedade {{domxref("HTMLTemplateElement.content")}} deles.

+ +

Um DocumentFragment pode ser criado usando o método {{domxref("document.createDocumentFragment")}} ou o construtor.

+ +

Propriedades

+ +

Essa interface não tem uma propriedade específica, mas herda de seu pai, {{domxref("Node")}}, e implementa aquelas da interface {{domxref("ParentNode")}}.

+ +
+
{{ domxref("ParentNode.children") }} {{readonlyInline}}{{experimental_inline}}
+
Returns a live {{domxref("HTMLCollection")}} containing all objects of type {{domxref("Node")}} that are children of the DocumentFragment object.
+
{{ domxref("ParentNode.firstElementChild") }} {{readonlyInline}}{{experimental_inline}}
+
Returns the {{domxref("Element")}} that is the first child of the DocumentFragment object, or null if there is none.
+
{{ domxref("ParentNode.lastElementChild") }} {{readonlyInline}}{{experimental_inline}}
+
Returns the {{domxref("Element")}} that is the last child of the DocumentFragment object, or null if there is none.
+
{{ domxref("ParentNode.childElementCount") }} {{readonlyInline}}{{experimental_inline}}
+
Returns an unsigned long giving the amount of children that the DocumentFragment has.
+
+ +

Construtor

+ +
+
{{ domxref("DocumentFragment.DocumentFragment()", "DocumentFragment()") }} {{experimental_inline}}
+
Retorna um objeto DocumentFragment vazio.
+
+ +

Métodos

+ +

This interface inherits the methods of its parent, {{domxref("Node")}}, and implements those of the {{domxref("ParentNode")}} interface.

+ +
+
{{domxref("DocumentFragment.find()")}} {{experimental_inline}}
+
Returns the first matching {{domxref("Element")}} in the tree of the DocumentFragment.
+
{{domxref("DocumentFragment.findAll()")}} {{experimental_inline}}
+
Returns a {{domxref("NodeList")}} of matching {{domxref("Element")}} in the tree of the DocumentFragment.
+
{{domxref("DocumentFragment.querySelector()")}}
+
Returns the first {{domxref("Element")}} node within the DocumentFragment, in document order, that matches the specified selectors.
+
{{domxref("DocumentFragment.querySelectorAll()")}}
+
Returns a {{domxref("NodeList")}} of all the {{domxref("Element")}} nodes within the DocumentFragment that match the specified selectors.
+
+ +
+
{{domxref("DocumentFragment.getElementById()")}}
+
Returns the first {{domxref("Element")}} node within the DocumentFragment, in document order, that matches the specified ID.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#documentfragment', 'DocumentFragment')}}{{Spec2('DOM WHATWG')}}Added the constructor and the implementation of {{domxref("ParentNode")}}.
{{SpecName('Selectors API Level 2', '#the-apis', 'DocumentFragment')}}{{Spec2('Selectors API Level 2')}}Added the find() and findAll() methods.
{{SpecName('Selectors API Level 1', '#the-apis', 'DocumentFragment')}}{{Spec2('Selectors API Level 1')}}Added the querySelector() and querySelectorAll() methods.
{{SpecName('DOM3 Core', 'core.html#ID-B63ED1A3', 'DocumentFragment')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-B63ED1A3', 'DocumentFragment')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-B63ED1A3', 'DocumentFragment')}}{{Spec2('DOM1')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
querySelector() and querySelectorAll()1.0{{CompatGeckoDesktop("1.9.1")}}8.010.03.2 (525.3)
findAll() and find() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
DocumentFragment() constructor {{experimental_inline}}28.0{{CompatGeckoDesktop("24.0")}}{{CompatNo}}15.0{{CompatNo}}
ParentNode properties {{experimental_inline}}28.0{{CompatGeckoDesktop("25.0")}}{{CompatNo}}15.0{{CompatNo}}
ParentNode methods {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
querySelector() and querySelectorAll()2.1{{CompatGeckoDesktop("1.9.1")}}8.010.03.2 (525.3)
findAll() and find() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
DocumentFragment() constructor {{experimental_inline}}{{CompatUnknown}}{{CompatGeckoMobile("24.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
ParentNode properties {{experimental_inline}}28.0{{CompatGeckoMobile("25.0")}}{{CompatNo}}5.0{{CompatNo}}
ParentNode methods {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/domexception/index.html b/files/pt-br/web/api/domexception/index.html new file mode 100644 index 0000000000..743ef8602e --- /dev/null +++ b/files/pt-br/web/api/domexception/index.html @@ -0,0 +1,150 @@ +--- +title: DOMException +slug: Web/API/DOMException +translation_of: Web/API/DOMException +--- +

{{ APIRef("DOM") }}

+ +

A interface DOMException representa um evento anormal (denominado de exceção) durante a chamada ou a espera de um resultado do metodo ou uma solicitação a uma web API. Basicamente, falando, é o tratamento dos erros e condições, dos mesmos, nos processos web.

+ +

Cada exceção tem um nome, que é uma pequena string de estilo "CamelCase" que identifica o erro ou condição anormal.

+ +

Constructor

+ +
+
{{domxref("DOMException.DOMException()", "DOMException()")}} {{experimental_inline}}
+
Returns a DOMException object with a specified message and name.
+
+ +

Properties

+ +
+
{{domxref("DOMException.code")}} {{deprecated_inline}} {{readOnlyInline}}
+
Returns a short that contains one of the {{anch("Error codes", "error code constants")}}, or 0 if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the {{domxref("DOMException.name")}} attribute.
+
{{domxref("DOMException.message")}} {{readOnlyInline}}
+
Returns a {{ domxref("DOMString") }} representing a message or description associated with the given error name.
+
{{domxref("DOMException.name")}} {{readOnlyInline}}
+
Returns a {{domxref("DOMString")}} that contains one of the strings associated with an error name.
+
+ +

Error names

+ +

Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list.

+ +
+

Note: Because historically the errors were identified by a numeric value which corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past.

+
+ +
+
IndexSizeError
+
The index is not in the allowed range. For example, this can be thrown by the {{ domxref("Range") }} object. (Legacy code value: 1 and legacy constant name: INDEX_SIZE_ERR)
+
HierarchyRequestError
+
The node tree hierarchy is not correct. (Legacy code value: 3 and legacy constant name: HIERARCHY_REQUEST_ERR)
+
WrongDocumentError
+
The object is in the wrong {{ domxref("Document") }}. (Legacy code value: 4 and legacy constant name: WRONG_DOCUMENT_ERR)
+
InvalidCharacterError
+
The string contains invalid characters. (Legacy code value: 5 and legacy constant name: INVALID_CHARACTER_ERR)
+
NoModificationAllowedError
+
The object cannot be modified. (Legacy code value: 7 and legacy constant name: NO_MODIFICATION_ALLOWED_ERR)
+
NotFoundError
+
The object cannot be found here. (Legacy code value: 8 and legacy constant name: NOT_FOUND_ERR)
+
NotSupportedError
+
The operation is not supported. (Legacy code value: 9 and legacy constant name: NOT_SUPPORTED_ERR)
+
InvalidStateError
+
The object is in an invalid state. (Legacy code value: 11 and legacy constant name: INVALID_STATE_ERR)
+
SyntaxError
+
The string did not match the expected pattern. (Legacy code value: 12 and legacy constant name: SYNTAX_ERR)
+
InvalidModificationError
+
The object cannot be modified in this way. (Legacy code value: 13 and legacy constant name: INVALID_MODIFICATION_ERR)
+
NamespaceError
+
The operation is not allowed by Namespaces in XML. (Legacy code value: 14 and legacy constant name: NAMESPACE_ERR)
+
InvalidAccessError
+
The object does not support the operation or argument. (Legacy code value: 15 and legacy constant name: INVALID_ACCESS_ERR)
+
TypeMismatchError {{deprecated_inline}}
+
The type of the object does not match the expected type. (Legacy code value: 17 and legacy constant name: TYPE_MISMATCH_ERR) This value is deprecated; the JavaScript {{jsxref("TypeError")}} exception is now raised instead of a DOMException with this value.
+
SecurityError
+
The operation is insecure. (Legacy code value: 18 and legacy constant name: SECURITY_ERR)
+
NetworkError {{experimental_inline}}
+
A network error occurred. (Legacy code value: 19 and legacy constant name: NETWORK_ERR)
+
AbortError {{experimental_inline}}
+
The operation was aborted. (Legacy code value: 20 and legacy constant name: ABORT_ERR)
+
URLMismatchError {{experimental_inline}}
+
The given URL does not match another URL. (Legacy code value: 21 and legacy constant name: URL_MISMATCH_ERR)
+
QuotaExceededError {{experimental_inline}}
+
The quota has been exceeded. (Legacy code value: 22 and legacy constant name: QUOTA_EXCEEDED_ERR)
+
TimeoutError
+
The operation timed out. (Legacy code value: 23 and legacy constant name: TIMEOUT_ERR)
+
InvalidNodeTypeError {{experimental_inline}}
+
The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: 24 and legacy constant name: INVALID_NODE_TYPE_ERR)
+
DataCloneError {{experimental_inline}}
+
The object can not be cloned. (Legacy code value: 25 and legacy constant name: DATA_CLONE_ERR)
+
EncodingError {{experimental_inline}}
+
The encoding or decoding operation failed (No legacy code value and constant name).
+
NotReadableError {{experimental_inline}}
+
The input/output read operation failed (No legacy code value and constant name).
+
UnknownError {{experimental_inline}}
+
The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name).
+
ConstraintError {{experimental_inline}}
+
A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name).
+
DataError {{experimental_inline}}
+
Provided data is inadequate (No legacy code value and constant name).
+
TransactionInactiveError {{experimental_inline}}
+
A request was placed against a transaction which is currently not active, or which is finished (No legacy code value and constant name).
+
ReadOnlyError {{experimental_inline}}
+
The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name).
+
VersionError {{experimental_inline}}
+
An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name).
+
OperationError {{experimental_inline}}
+
The operation failed for an operation-specific reason (No legacy code value and constant name).
+
NotAllowedError
+
The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name).
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebIDL', '#idl-DOMException', 'constructor')}}{{Spec2('WebIDL')}}Adds the constructor for the DOMException class. Adds the NotReadableError, UnknownError, ConstraintError, DataError, TransactionInactiveError, ReadOnlyError, VersionError, OperationError, and NotAllowedError values.
{{SpecName('DOM4', '#exception-domexception', 'DOMException')}}{{Spec2('DOM4')}}Added SECURITY_ERR, NETWORK_ERR, ABORT_ERR, URL_MISMATCH_ERR, QUOTA_EXCEEDED_ERR, TIMEOUT_ERR, INVALID_NODE_TYPE_ERR, and DATA_CLONE_ERR. The property code has been deprecated for exception values. The EncodingError value added.
{{SpecName('DOM3 Core', 'core.html#ID-17189187', 'DOMException')}}{{Spec2('DOM3 Core')}}Added of VALIDATION_ERR and TYPE_MISMATCH_ERR.
{{SpecName('DOM2 Core', 'core.html#ID-17189187', 'DOMException')}}{{Spec2('DOM2 Core')}}Added of INVALID_STATE_ERR, SYNTAX_ERR, INVALID_MODIFICATION_ERR, NAMESPACE_ERR, and INVALID_ACCESS_ERR.
{{SpecName('DOM1', 'level-one-core.html#ID-17189187', 'DOMException')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/domimplementation/createdocument/index.html b/files/pt-br/web/api/domimplementation/createdocument/index.html new file mode 100644 index 0000000000..61c90cd7b8 --- /dev/null +++ b/files/pt-br/web/api/domimplementation/createdocument/index.html @@ -0,0 +1,83 @@ +--- +title: DOMImplementation.createDocument() +slug: Web/API/DOMImplementation/createDocument +translation_of: Web/API/DOMImplementation/createDocument +--- +

{{ApiRef("DOM")}}

+ +

O método DOMImplementation.createDocument() cria e retorna um {{domxref("XMLDocument")}}.

+ +

Sintaxe

+ +
doc = document.implementation.createDocument(namespaceURI, qualifiedNameStr, documentType);
+ +

Parâmetros

+ +
+
namespaceURI
+
É um {{domxref("DOMString")}} contendo a URI do namespace do documento que será criado, ou null se o documento não pertencer a nenhum.
+
+ +
+
qualifiedNameStr
+
Is a {{domxref("DOMString")}} containing the qualified name, that is an optional prefix and colon plus the local root element name, of the document to be created.
+
+ +
+
documentType {{optional_inline}}
+
+

Is the {{domxref("DocumentType")}} of the document to be created. It defaults to null.

+
+
+ + + +

Example

+ +
var doc = document.implementation.createDocument ('http://www.w3.org/1999/xhtml', 'html', null);
+var body = document.createElementNS('http://www.w3.org/1999/xhtml', 'body');
+body.setAttribute('id', 'abc');
+doc.documentElement.appendChild(body);
+alert(doc.getElementById('abc')); // [object HTMLBodyElement]
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-domimplementation-createdocument', 'DOMImplementation.createDocument')}}{{Spec2('DOM WHATWG')}}Modified the return type of createDocument() from {{domxref("Document")}} to {{domxref("XMLDocument")}}.
+ The third argument of createDocument(), doctype, is now optional and default to null.
{{SpecName('DOM3 Core', 'core.html#Level-2-Core-DOM-createDocument', 'DOMImplementation.createDocument')}}{{Spec2('DOM3 Core')}}No change from {{SpecName("DOM2 Core")}}
{{SpecName('DOM2 Core', 'core.html#Level-2-Core-DOM-createDocument', 'DOMImplementation.createDocument')}}{{Spec2('DOM2 Core')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.DOMImplementation.createDocument")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/domimplementation/index.html b/files/pt-br/web/api/domimplementation/index.html new file mode 100644 index 0000000000..e49ceda64a --- /dev/null +++ b/files/pt-br/web/api/domimplementation/index.html @@ -0,0 +1,81 @@ +--- +title: DOMImplementation +slug: Web/API/DOMImplementation +tags: + - API + - DOM + - Interface + - NeedsTranslation + - Reference + - Référence(2) + - TopicStub +translation_of: Web/API/DOMImplementation +--- +

{{ ApiRef("DOM") }}

+ +

The DOMImplementation interface represent an object providing methods which are not dependent on any particular document. Such an object is returned by the {{domxref("Document.implementation")}} property.

+ +

Property

+ +

This interface has no specific property and doesn't inherit any.

+ +

Methods

+ +

No inherited method.

+ +
+
{{domxref("DOMImplementation.createDocument()")}}
+
Creates and returns an {{domxref("XMLDocument")}}.
+
{{domxref("DOMImplementation.createDocumentType()")}}
+
Creates and returns a {{domxref("DocumentType")}}.
+
{{domxref("DOMImplementation.createHTMLDocument()")}}
+
Creates and returns an HTML {{domxref("Document")}}.
+
{{domxref("DOMImplementation.hasFeature()")}}
+
Returns a {{domxref("Boolean")}} indicating if a given feature is supported or not. This function is unreliable and kept for compatibility purpose alone: except for SVG-related queries, it always returns true. Old browsers are very inconsistent in their behavior.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#domimplementation', 'DOMImplementation')}}{{Spec2('DOM WHATWG')}}Removed the getFeature() method.
+ Added the createHTMLDocument() method.
+ Modified the return type of createDocument() from {{domxref("Document")}} to {{domxref("XMLDocument")}}.
{{SpecName('DOM3 Core', 'core.html#ID-102161490', 'DOMImplementation')}}{{Spec2('DOM3 Core')}}Added the getFeature() method (never implemented by any user agent).
{{SpecName('DOM2 Core', 'core.html#ID-102161490', 'DOMImplementation')}}{{Spec2('DOM2 Core')}}Added the createDocument() and createDocumentType() methods.
{{SpecName('DOM1', 'level-one-core.html#ID-102161490', 'DOMImplementation')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/domstring/index.html b/files/pt-br/web/api/domstring/index.html new file mode 100644 index 0000000000..578e449d94 --- /dev/null +++ b/files/pt-br/web/api/domstring/index.html @@ -0,0 +1,52 @@ +--- +title: DOMString +slug: Web/API/DOMString +translation_of: Web/API/DOMString +--- +

{{APIRef("DOM")}}

+ +

DOMString é uma String UTF-16. Como o JavaScript já usa tais strings, uma DOMString é mapeada diretamente a uma {{jsxref("String")}}.

+ +

Passando null para um método ou parâmetro que aceite uma DOMString, tal valor é convertido para a string "null".

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebIDL', '#idl-DOMString', 'DOMString')}}{{Spec2('WebIDL')}}Reformulação da definição para remover alguns casos estranhos.
{{SpecName('DOM3 Core', 'core.html#DOMString', 'DOMString')}}{{Spec2('DOM3 Core')}}Nenhuma mudança da {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-C74D1578', 'DOMString')}}{{Spec2('DOM2 Core')}}Nenhuma mudança da {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-C74D1578', 'DOMString')}}{{Spec2('DOM1')}}Definição inicial.
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/domstringlist/index.html b/files/pt-br/web/api/domstringlist/index.html new file mode 100644 index 0000000000..48547f3d67 --- /dev/null +++ b/files/pt-br/web/api/domstringlist/index.html @@ -0,0 +1,43 @@ +--- +title: DOMStringList +slug: Web/API/DOMStringList +translation_of: Web/API/DOMStringList +--- +

{{ APIRef("DOM") }}

+ +

Um tipo retornado por algumas APIs, que contém uma lista de DOMString (strings).

+ +

Propriedades

+ +
+
{{domxref("DOMStringList.length")}} {{ReadOnlyInline}}
+
Retorna o número de itens da lista
+
+ +

Métodos

+ +
+
{{domxref("DOMStringList.item()")}}
+
Retorna uma {{domxref("DOMString")}}.
+
{{domxref("DOMStringList.contains()")}}
+
Retorna {{jsxref("Boolean")}} indicando se a string em questão está na lista
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("HTML WHATWG", "common-dom-interfaces.html#the-domstringlist-interface", "DOMStringList")}}{{Spec2("HTML WHATWG")}}Especificação Inicial
diff --git a/files/pt-br/web/api/domstringmap/index.html b/files/pt-br/web/api/domstringmap/index.html new file mode 100644 index 0000000000..df9d74a7bd --- /dev/null +++ b/files/pt-br/web/api/domstringmap/index.html @@ -0,0 +1,141 @@ +--- +title: DOMStringMap +slug: Web/API/DOMStringMap +translation_of: Web/API/DOMStringMap +--- +

{{ APIRef("HTML DOM") }}

+ +

Usado pelo atributo HTML {{ htmlattrxref("dataset") }} para representar atributos próprios adicionados ao elemento.

+ +

Visão Geral do Método

+ + + + + + + + + + + + + + + + + + + +
DOMString getDataAttr(in DOMString prop);
boolean hasDataAttr(in DOMString prop);
void removeDataAttr(in DOMString prop);
void removeProp(in nsIAtom attr);
void setDataAttr(in DOMString prop, in DOMString value);
+ +

Métodos

+ +

hasDataAttr()

+ +
boolean hasDataAttr(
+  in DOMString prop
+);
+
+ +
Parâmetros
+ +
+
prop
+
Nome da propriedade a qual a existência deve ser verificada.
+
+ +
Retorno
+ +

true se a propriedade existir ou false se não existir.

+ +

removeDataAttr()

+ +
void removeDataAttr(
+  in DOMString prop
+);
+
+ +
Parâmetros
+ +
+
prop
+
Propriedade a ser removida do data set.
+
+ +

removeProp()

+ +

Remove a propriedade do dataset do objeto. Usada para atualizar o objeto de dataset do objeto quando o atributo data-* houver sido removido do elemento.

+ +
void removeProp(
+  in nsIAtom attr
+);
+
+ +
Parâmetros
+ +
+
attr
+
A propriedade a ser removida do dataset.
+
+ +

Compatibilidade

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/accesskey/index.html b/files/pt-br/web/api/element/accesskey/index.html new file mode 100644 index 0000000000..b05fb5e2b3 --- /dev/null +++ b/files/pt-br/web/api/element/accesskey/index.html @@ -0,0 +1,18 @@ +--- +title: Element.accessKey +slug: Web/API/Element/accessKey +translation_of: Web/API/HTMLElement/accessKey +--- +
{{APIRef("DOM")}}
+ +
 
+ +

A propriedade Element.accessKey define a tecla pelo qual o usuário pode pressionar para saltar para este elemento.

+ +
+

Nota: A propriedade Element.accessKey é raramente usada por causa dos conflitos múltiplos com os atalhos pré-definidos nos navegadores. Para contornar isto, os navegadores implementam o comportamento da tecla de acesso se as teclas são pressionadas com outras teclas "qualificadas" (como Alt + tecla de acesso).

+
+ +

 

+ +

 

diff --git a/files/pt-br/web/api/element/addeventlistener/index.html b/files/pt-br/web/api/element/addeventlistener/index.html new file mode 100644 index 0000000000..fea1e67e7b --- /dev/null +++ b/files/pt-br/web/api/element/addeventlistener/index.html @@ -0,0 +1,322 @@ +--- +title: Element.addEventListener() +slug: Web/API/Element/addEventListener +translation_of: Web/API/EventTarget/addEventListener +--- +

{{apiref("DOM Events")}}

+ +

addEventListener() registra uma única espera de evento em um único alvo. O alvo do evento pode ser um único elemento em um documento, o documento em si, uma janela, ou um XMLHttpRequest.

+ +

Para registrar mais de uma espera de evento como alvo, chame addEventListener() para o mesmo alvo mas com diferentes tipos de evento ou captura de parâmetros.

+ +

Sintaxe

+ +
alvo.addEventListener(type,listener[, options]);
+alvo.addEventListener(type,listener[, useCapture, wantUntrusted {{ Non-standard_inline() }}]); // Gecko/Mozilla only
+ +
+
type
+
Uma linha de texto que representa o tipo de evento a ser esperado.
+
listener
+
O objeto que recebe uma notificação quando um evento do tipo especificado ocorre. Esse objeto precisa implementar a interface do EventListener, ou simplesmente executar uma função JavaScript.
+
useCapture {{ optional_inline() }}
+
Se true, useCapture indica que o usuário deseja iniciar uma captura. Depois de iniciada a captura, todos os eventos do tipo especificado serão enviados à listener registrada antes de serem enviados à qualquer EventTarget abaixo dela na hierarquia de DOMs. Eventos que borbulharem para cima na hierarquia não acionarão a escuta designada  a usar a captura. Veja Eventos DOM Nível 3 para uma explicação detalhada. Perceba que esse parâmetro não é opcional em todos os navegadores. Se não for especificado, useCapture é false.
+
wantsUntrusted {{ Non-standard_inline() }}
+
Se true, o evento pode ser acionado por conteúdo não-confiável. Veja Interação entre páginas com e sem privilégios.
+
+ +
Nota: useCapture tornou-se opcional somente nas versões mais recentes dos principais navegadores; não era opcional antes do Firefox 6, por exemplo. Você deve especificar esse parâmetro para obter uma maior compatibilidade.
+ + +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>Exemplo de Evento DOM</title>
+
+<style>
+#t { border: 1px solid red }
+#t1 { background-color: pink; }
+</style>
+
+<script>
+// Função para mudar o conteúdo de t2
+function modifyText() {
+  var t2 = document.getElementById("t2");
+  t2.firstChild.nodeValue = "three";
+}
+
+// Função para adicionar uma espera de evento em t
+function load() {
+  var el = document.getElementById("t");
+  el.addEventListener("click", modifyText, false);
+}
+
+document.addEventListener("DOMContentLoaded", load, false);
+</script>
+
+</head>
+<body>
+
+<table id="t">
+   <tr><td id="t1">one</td></tr>
+   <tr><td id="t2">two</td></tr>
+</table>
+
+</body>
+</html>
+
+ +

View on JSFiddle

+ +

No exemplo acima, modifyText() é uma escuta para eventos de click registrados usando addEventListener(). Um clique em qualquer lugar da tabela irá borbulhar para cima até o manipulador e executar modifyText().

+ +

Se você deseja passar parâmetros para a função de escuta, você deve usar uma função anônima.

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>Exemplo de Evento DOM</title>
+
+<style>
+#t { border: 1px solid red }
+#t1 { background-color: pink; }
+</style>
+
+<script>
+
+// Função para mudar o conteúdo de t2
+function modifyText(new_text) {
+  var t2 = document.getElementById("t2");
+  t2.firstChild.nodeValue = new_text;
+}
+
+// Função para adicionar uma espera de evento em t
+function load() {
+  var el = document.getElementById("t");
+  el.addEventListener("click", function(){modifyText("four")}, false);
+}
+</script>
+
+</head>
+<body onload="load();">
+
+<table id="t">
+  <tr><td id="t1">one</td></tr>
+  <tr><td id="t2">two</td></tr>
+</table>
+
+</body>
+</html>
+
+ +

Notas

+ +

Por que usar addEventListener?

+ +

addEventListener é a maneira de registrar uma espera de evento como especificada no W3C DOM. Seus benefícios são os seguintes:

+ + + +

Existe outra alternativa, uma maneira ultrapassada de registrar esperas de evento.

+ +

Adicionando uma espera de evento durante um disparo de evento

+ +

Se um EventListener for somado a um EventTarget enquanto está processando um evento, ele não será ativado pelas ações atuais, mas poderá ser ativado em um período posterior no fluxo de eventos, como na fase de borbulha.

+ +

Múltiplas esperas de evento idênticas

+ +

Se múltiplas esperas de evento idênticas forem registradas no mesmo EventTarget com os mesmos parâmetros, as versões duplicadas serão descartadas. Elas não fazem o EventListener ser disparado mais de uma vez, e, como as duplicatas são descartadas, elas não precisam ser removidas manualmente com o método removeEventListener.

+ +

O valor de this no manipulador

+ +

É preferível referenciar o elemento do qual a espera de evento foi disparada, como quando é usado um manipulador genérico para uma série de elementos similares. Quando anexar uma função usando addEventListener(), o valor de this é mudado — perceba que o valor de this é passado para uma função a partir do disparador.

+ +

Nos exemplos acima, o valor de this em modifyText(), quando disparado pelo evento de clique, é uma referência à tabela 't'. Isso é um contraste do comportamento que acontece se o manipulador é adicionado ao HTML fonte:

+ +
<table id="t" onclick="modifyText();">
+  . . .
+ +

O valor de this em modifyText(), quando disparado pelo evento de clique no HTML, será uma referência ao objeto global (no caso, a janela).

+ +
Nota: JavaScript 1.8.5 introduz o método Function.prototype.bind(), que permite especificar o valor que deve ser usado como this para todas as chamadas à uma determinada função. Isso evita problemas quando não é claro o que this será, dependendo do contexto do qual a sua função for chamada. Perceba, entretanto, que é preciso manter uma referência da escuta à mão, para que depois você possa removê-la.
+ +

Este é um exemplo com e sem bind:

+ +
var Algo = function(elemento)
+{
+  this.nome = 'Algo bom';
+  this.onclick1 = function(evento) {
+    console.log(this.nome); // indefinido, porque this é a função de escuta do clique
+  };
+  this.onclick2 = function(evento) {
+    console.log(this.nome); // 'Algo bom', porque this está como objeto Algo através do bind
+  };
+  elemento.addEventListener('click', this.onclick1, false);
+  elemento.addEventListener('click', this.onclick2.bind(this), false); // Truque de bind
+}
+
+ +

Outra solução é usar uma função especial chamada handleEvent para capturar quaisquer eventos:

+ +
var Algo = function(elemento)
+{
+  this.nome = 'Algo bom';
+  this.handleEvent = function(evento) {
+    console.log(this.nome); // 'Algo bom', porque this é o objeto Algo
+    switch(evento.type) {
+      case 'click':
+        // seu codigo aqui...
+        break;
+      case 'dblclick':
+        // seu codigo aqui...
+        break;
+    }
+  };
+  elemento.addEventListener('click', this, false); // Não this.handleEvent, só this
+  elemento.addEventListener('dblclick', this, false); // Não this.handleEvent, só this
+}
+
+ +

Internet Explorer antigos e attachEvent

+ +

Em versões do Internet Explorer anteriores ao IE9, você precisa usar attachEvent em vez do padrão addEventListener. Para dar suporte ao IE, o exemplo acima pode ser modificado para:

+ +
if (el.addEventListener) {
+  el.addEventListener('click', modifyText, false);
+} else if (el.attachEvent)  {
+  el.attachEvent('onclick', modifyText);
+}
+
+ +

Existe um porém com attachEvent: o valor de this será a referência ao objeto window em vez do elemento do qual foi disparado.

+ +

Uma maneira ultrapassada de registrar esperas de evento

+ +

addEventListener() foi introduzido com as especificações de Eventos DOM 2. Antes disso, esperas de evento eram registradas assim:

+ +
// Passe uma função de referência — não adicione '()' depois dela, o que chamaria a função!
+el.onclick = modifyText;
+
+// Usando uma expressão de função
+element.onclick = function() {
+    // ... lógica da função ...
+};
+
+ +

Esse método substitui as esperar de evento de click no elemento, se houve alguma. Igualmente para outros outros eventos e manipuladores de evento associados, como blur (onblur), keypress (onkeypress), e assim por diante.

+ +

Porque era essencialmente uma parte do DOM 0, esse método era largamente suportado e não necessitava de códigos entre-navegadores especiais; logo é normalmente usado para registrar esperas de evento dinâmicamente, a menos que atributos extras do addEventListener() sejam necessários.

+ +

Problemas de memória

+ +
var i;
+var els = document.getElementsByTagName('*');
+
+// Caso 1
+for(i=0 ; i<els.length ; i++){
+  els[i].addEventListener("click", function(e){/*fazer algo*/}, false});
+}
+
+// Caso 2
+function processarEvento(e){
+  /*fazer algo*/
+}
+
+for(i=0 ; i<els.length ; i++){
+  els[i].addEventListener("click", processarEvento, false});
+}
+
+
+ +

No primeiro caso, uma nova função (anônima) é criada em cada turno do loop. No segundo caso, a mesma função previamente declarada é usada como um manipulador de evento. Isso resulta em um consumo menor de memória. Além do mais, no primeiro caso, já que nenhuma referência à função anônima é mantida, não é possível chamar element.removeEventListener porque não há uma referência ao manipulador, enquanto no segundo caso é possível fazer myElement.removeEventListener("click", processEvent, false).

+ +

Compatiblidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{ CompatGeckoDesktop(1.0) }}9.071.0
useCapture é opcional1.06.09.011.60{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico1.0{{ CompatGeckoMobile(1.0) }}9.06.01.0
+
+ +

Notas Gecko

+ + + +

Notas Webkit

+ + + +

Veja também

+ + + +

Especificação

+ + diff --git a/files/pt-br/web/api/element/animate/index.html b/files/pt-br/web/api/element/animate/index.html new file mode 100644 index 0000000000..8c8d5e58c5 --- /dev/null +++ b/files/pt-br/web/api/element/animate/index.html @@ -0,0 +1,202 @@ +--- +title: Element.animate() +slug: Web/API/Element/animate +translation_of: Web/API/Element/animate +--- +
{{APIRef('Web Animations')}} {{SeeCompatTable}}
+ +

Um {{domxref("Element")}} de interface do método animate() é um método de atalho o qual cria uma nova {{domxref("Animation")}}, e a aplica ao elemento, então executa a animação. Retorna a instância do objeto {{domxref("Animation")}} criado.

+ +
+

Elementos podem ter múltiplas animações aplicadas a eles. Você pode obter uma lista de animações que afetam um elemento chamando {{domxref("Element.getAnimations()")}}.

+
+ +

Syntax

+ +
var animation = element.animate(keyframes, options); 
+ +

Paramêtros

+ +
+
keyframes
+
+

An Object formatted to represent a set of keyframes.

+
+
opções
+
Ou um inteiro representando a duração da animação (em milisegundos), ou um objeto contendo uma ou mais propriedades de tempo:
+
id {{optional_inline}}
+
+
+
Um propriedade única á animate(): uma DOMString com a qual a animação é referenciada. 
+
+ {{Page("/en-US/docs/Web/API/Web_Animations_API/Animation_timing_properties", "Properties")}}
+
+ +

Opções Futuras

+ +

As seguintes opções atualmente não são embarcadas em nenhum lugar, porém serão adicionadas num futuro próximo.

+ +
+
composite {{optional_inline}}
+
Determina como os valores são combinados entre animações diferentes, separa animações que não especificam suas próprias operações de composição. Padrão para subtitituir. +
    +
  • Adiciona efeito de imposição e aditivação, onde cada iteração sucessiva é executada sobre a última. Por exemplo, com transform translateX(-200px) não sobreescreveria um valor anterior de rotate(20deg) mas resultaria em translateX(-200px) rotate(20deg).
  • +
  • accumulate é similar porém um pouco mais inteligente: blur(2) e blur(5) se tornam blur(7), não blur(2) blur(5).
  • +
  • replace sobreescreve o valor anterior com um novo. 
  • +
+
+
iterationComposite {{optional_inline}}
+
Determines how values build from iteration to iteration in this animation. Can be set to accumulate or replace (see above). Defaults to replace.
+
spacing {{optional_inline}}
+
Determina como quadros-chaves sem deslocamento temporal devem ser distribuidos durante a duração da animação. Padrão para distribute. +
    +
  • distribuir quadro-chaves de posição de forma que a diferença de deslocamento entre quadros-chaves subsequentes seja igual, distribuirá igualmente os quadros-chaves no decorrer do tempo de execução.
  • +
  • paced positions keyframes so that the distance between subsequent values of a specified paced property are equal, that is to say, keyframes are spaced further apart the greater the difference in their property values.
  • +
+ +

 

+
+
+ +

Valor de retorno

+ +

Retorna uma {{domxref("Animation")}}.

+ +

Exemplo

+ +

Na demonstração Down the Rabbit Hole (with the Web Animation API), nós usamos o método conveniente animate() para imediamente criar e executar uma animação no elemento #tunnel para faze-lo fluir em direção superior, infinitamente.
+ Note o array de quadros-chave passado e também o bloco de opções de temporização.

+ +
document.getElementById("tunnel").animate([
+  // keyframes
+  { transform: 'translateY(0px)' },
+  { transform: 'translateY(-300px)' }
+], {
+  // timing options
+  duration: 1000,
+  iterations: Infinity
+});
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations', '#the-animatable-interface', 'animate()' )}}{{Spec2('Web Animations')}}Initial definition
+ +

Compatibildade entre Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome("36")}}{{CompatNo}}{{ CompatGeckoDesktop("48.0")}}{{CompatNo}}23{{CompatUnknown}}
id option{{CompatChrome(50.0)}}{{CompatNo}}{{ CompatGeckoDesktop("48.0")}}{{CompatNo}}37{{CompatUnknown}}
composite, iterationComposite, and spacing options{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatChrome(39.0)}}{{CompatChrome(39.0)}}{{ CompatGeckoMobile("48.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
id option{{CompatNo}}{{CompatChrome(50.0)}}{{CompatChrome(50.0)}}{{ CompatGeckoMobile("48.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
composite, iterationComposite, and spacing options{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/element/attributes/index.html b/files/pt-br/web/api/element/attributes/index.html new file mode 100644 index 0000000000..b5888e0f04 --- /dev/null +++ b/files/pt-br/web/api/element/attributes/index.html @@ -0,0 +1,166 @@ +--- +title: Element.attributes +slug: Web/API/Element/attributes +tags: + - API + - DOM + - Element + - Elemento + - Property + - Propriedade + - Reference + - Referencia +translation_of: Web/API/Element/attributes +--- +

{{ APIRef("DOM") }}

+ +

A propriedade Element.attributes retorna uma coleção de todos os atributos registrados para um nó especificado. É um {{domxref("NamedNodeMap")}}, e não um Array, então não há os métodos de um {{jsxref("Array")}} e os nós indexados {{domxref("Attr")}} podem ser diferentes entre os navegadores. Para ser mais específico, attributes é um par de chave/valor de strings que representa qualquer informação relacionada ao atributo.

+ +

Sintaxe

+ +
var attr = element.attributes;
+
+ +

Exemplo

+ +

Exemplos básicos

+ +
// Obtem o primeiro elemento <p> no documento
+var para = document.getElementsByTagName("p")[0];
+var atts = para.attributes;
+ +

Listando os atributos dos elementos

+ +

Indexadores numéricos são úteis para percorrer através de todos os atributos de um elemento.
+ O exemplo a seguir percorre através dos nós dos atributos do elemento no documento que tenha o id de "p1", e imprime o valor de cada atributo.

+ +
<!DOCTYPE html>
+
+<html>
+
+ <head>
+  <title>Exemplo com atributos</title>
+  <script type="text/javascript">
+   function listAttributes() {
+     var paragraph = document.getElementById("paragraph");
+     var result = document.getElementById("result");
+
+     // Antes, vamos verificar se o paragrafo tem algum atributo
+     if (paragraph.hasAttributes()) {
+       var attrs = paragraph.attributes;
+       var output = "";
+       for(var i = attrs.length - 1; i >= 0; i--) {
+         output += attrs[i].name + "->" + attrs[i].value;
+       }
+       result.value = output;
+     } else {
+       result.value = "Nenhum atributo para mostrar";
+     }
+   }
+  </script>
+ </head>
+
+<body>
+ <p id="paragraph" style="color: green;">Paragrafo de exemplo</p>
+ <form action="">
+  <p>
+    <input type="button" value="Mostra o nome e o valor do atributo"
+      onclick="listAttributes();">
+    <input id="result" type="text" value="">
+  </p>
+ </form>
+</body>
+</html>
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-element-attributes', 'Element.attributes')}}{{Spec2('DOM WHATWG')}}Da {{SpecName('DOM3 Core')}}, movido de {{domxref("Node")}} para {{domxref("Element")}}
{{SpecName('DOM3 Core', 'core.html#ID-84CF096', 'Element.attributes')}}{{Spec2('DOM3 Core')}}Nenhuma alteração a partir da {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-84CF096', 'Element.attributes')}}{{Spec2('DOM2 Core')}}Nenhuma alteração a partir da {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-84CF096', 'Element.attributes')}}{{Spec2('DOM1')}}Definição inicial.
+ +

Compatibilidade entre os navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }} [1]6.0 [2]{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }} [1]{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

[1] Antes do Firefox 22, este atributo foi implementado na interface {{domxref("Node")}} (herdada por {{domxref("Element")}}). foi movido para esta interface para obedecer a especificação e o uso em outros navegadores.

+ +

[2] Internet Explorer 5.5 retorna um map contendo os valores ao invés dos objetos do atributo.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/classlist/index.html b/files/pt-br/web/api/element/classlist/index.html new file mode 100644 index 0000000000..03b79e63d5 --- /dev/null +++ b/files/pt-br/web/api/element/classlist/index.html @@ -0,0 +1,171 @@ +--- +title: Element.classList +slug: Web/API/Element/classList +translation_of: Web/API/Element/classList +--- +
{{APIRef("DOM")}}
+ +

O Element.classList é uma propriedade somente leitura que retorna uma coleção {{domxref ("DOMTokenList")}} ativa dos atributos de classe do elemento.

+ +

Usar classList é uma alternativa conveniente para acessar a lista de classes de um elemento como uma seqüência delimitada por espaço através de {{domxref ("element.className")}}.

+ +

Sintaxe

+ +
const elementClasses = elementNodeReference.classList;
+
+ +

elementClasses é um DOMTokenList que representa o atributo de classe de elementNodeReference. Se o atributo de classe não foi definido ou está vazio elementClasses.length retorna 0. element.classList propriamente dito é somente leitura, embora você possa modificá-lo usando os métodos add () e remove ().

+ +

Métodos

+ +
+
add( String [, String] )
+
Adicione valores de classe especificados. Se essas classes já existem no atributo do elemento, elas são ignoradas.
+
remove( String [,String] )
+
Remover valores de classe específicos.
+
item ( Number )
+
Retorna o valor da classe por índice na coleção.
+
toggle ( String [, force] )
+
Quando apenas um argumento está presente: Toggle class value; Ou seja, se a classe existir, em seguida, removê-lo e retornar false, se não, então adicioná-lo e retornar true.
+ Quando um segundo argumento está presente: Se o segundo argumento é avaliado como true, adicione o valor especificado da classe e, se ele for avaliado como false, remova-o.
+
contains( String )
+
Verifica se o valor da classe especificado existe no atributo de classe do elemento.
+
+ +

Exemplos

+ +
// div é uma referência de objeto para um elemento <div> com class = "foo bar"
+div.classList.remove("foo");
+div.classList.add("anotherclass");
+
+// Se estiver visível, remova-o, caso contrário, adicione-o
+div.classList.toggle("visible");
+
+// adicionar/remover, dependendo do teste condicional, i menos de 10
+div.classList.toggle("visible", i < 10 );
+
+alert(div.classList.contains("foo"));
+
+// adicionar ou remover várias classes
+div.classList.add("foo","bar");
+div.classList.remove("foo", "bar");
+ +
+

As versões do Firefox antes de 26 não implementam o uso de vários argumentos nos métodos add / remove / toggle. Veja https://bugzilla.mozilla.org/show_bug.cgi?id=814014

+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName("HTML WHATWG", "dom.html#dom-classlist", "Element.classList")}}{{Spec2("HTML WHATWG")}}Observe dentro da especificação HTML relacionada ao {{htmlattrxref("class")}} attribute.
{{SpecName("DOM WHATWG", "#dom-element-classlist", "Element.classList")}}{{Spec2("DOM WHATWG")}}Definição inicial
{{SpecName("DOM4", "#dom-element-classlist", "Element.classList")}}{{Spec2("DOM4")}} 
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support8.0{{CompatVersionUnknown}}[3]{{CompatGeckoDesktop("1.9.2")}}10[1][3]11.505.1
toggle method's second argument24{{CompatVersionUnknown}}{{CompatGeckoDesktop("24")}}{{CompatNo}}[2]155.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support3.0{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.2")}}1011.105.0
toggle method's second argument{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("24")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Não suportado para elementos SVG. Veja a report at Microsoft about that.
+ [2] O Internet Explorer nunca implementou isso. Veja a report at Microsoft about that.
+ [3] Internet Explorer usa apenas o primeiro parâmetro em "add" e "remove".

+ +

 

+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/classname/index.html b/files/pt-br/web/api/element/classname/index.html new file mode 100644 index 0000000000..1db2b4f71e --- /dev/null +++ b/files/pt-br/web/api/element/classname/index.html @@ -0,0 +1,123 @@ +--- +title: Element.className +slug: Web/API/Element/className +tags: + - API + - DOM + - Gecko + - Property + - Reference +translation_of: Web/API/Element/className +--- +
{{APIRef("DOM")}}
+ +

Sumário

+ +

className retorna e define o valor do atributo class do elemento especificado.

+ +

Syntax

+ +
var cName = elementNodeReference.className;
+elementNodeReference.className = cName;
+ + + +

Exemplo

+ +
var element = document.getElementById("div1");
+
+if (element.className === "fixed") {
+  // verifica a partir de uma classe específica do elemento
+  goNextElement();
+}
+ +

Notas

+ +

O nome className é utilizado para esta propriedade ao invés de class por conta de conflitos com a palavra-chave "class" em variáveis linguagens que são utilizadas para manipulação do DOM.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-element-classname", "element.className")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM4", "#dom-element-classname", "element.className")}}{{Spec2("DOM4")}} 
{{SpecName("DOM2 HTML", "html.html#ID-95362176", "element.className")}}{{Spec2("DOM2 HTML")}}Definição inicial
+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/click_event/index.html b/files/pt-br/web/api/element/click_event/index.html new file mode 100644 index 0000000000..1044c53281 --- /dev/null +++ b/files/pt-br/web/api/element/click_event/index.html @@ -0,0 +1,276 @@ +--- +title: click +slug: Web/API/Element/click_event +translation_of: Web/API/Element/click_event +--- +

O evento click event é disparado quando o botão de um dispositivo apontador (normalmente o botão de um mouse) é pressionado e solto logo em seguida em um mesmo elemento.

+ +

Informações gerais

+ +
+
Especificação
+
DOM L3
+
Interface
+
{{domxref("MouseEvent")}}
+
Bubbles
+
Sim
+
Cancelável
+
Sim
+
Target
+
Element
+
Ação padrão
+
Variável
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetO alvo do evento (o mais alto na arvore de DOM).
type {{readonlyInline}}DOMStringTipo do evento.
bubbles {{readonlyInline}}BooleanSe o evento "bubbles" naturalmente ou não.
cancelable {{readonlyInline}}BooleanSe o evento é cancelável ou não
view {{readonlyInline}}WindowProxydocument.defaultView (window do documento)
detail {{readonlyInline}}long (float) +

Um contador de cliques consecutivos que ocorrem em um curto espaço de tempo, incrementado em 1.

+
currentTarget {{readonlyInline}}EventTargetO node que contem o eventListener.
relatedTarget {{readonlyInline}}EventTargetPara eventos mouseover, mouseout, mouseentermouseleave: o alvo do evento complementar (o mouseleave no caso de um evento mouseenter ). null , se falso.
screenX {{readonlyInline}}longA coordenada X do ponteiro do mouse na tela.
screenY {{readonlyInline}}longA coordenada Y do ponteiro do mouse na tela.
clientX {{readonlyInline}}longA coordenada X do ponteiro do mouse no DOM atual.
clientY {{readonlyInline}}longA coordenada Y do ponteiro do mouse no DOM atual.
button {{readonlyInline}}unsigned shortThe button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2. For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left.
buttons {{readonlyInline}}unsigned shortThe buttons being pressed when the mouse event was fired: Left button=1, Right button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, 5th button (typically, "Browser Forward" button)=16. If two or more buttons are pressed, returns the logical sum of the values. E.g., if Left button and Right button are pressed, returns 3 (=1 | 2). More info.
mozPressure {{readonlyInline}}floatThe amount of pressure applied to a touch or tabdevice when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

Exemplo

+ +
<div id="test"></div>
+
+<script>
+  document.getElementById("test").addEventListener("click", function( event ) {
+    // mostra o contador de cliques dentro da div clicada
+    event.target.innerHTML = "Total de cliques: " + event.detail;
+  }, false);
+</script>
+
+ +

Compatibilidade nos Browsers

+ +

Internet Explorer

+ +

O Internet Explorer 8 e 9 apresentam um bug onde o elemento com a propriedade {{cssxref("background-color")}} é definida como transparent that are overlaid on top of other element(s) won't receive click events. Todos os eventos click serão disparados no elemento underlying instead. Veja uma demonstração neste exemplo.

+ +

Soluções de contorno para este bug:

+ + + +

Safari Mobile

+ +

Safari Mobile 7.0+ (and likely earlier versions too) suffers from a bug where click events aren't fired on elements that aren't typically interactive (e.g. {{HTMLElement("div")}}) and which also don't have event listeners directly attached to the elements themselves (i.e. event delegation is being used). See this live example for a demonstration. See also Safari's docs on making elements clickable and the definition of "clickable element".

+ +

Known workarounds for this bug:

+ + + +

Safari Mobile considers the following elements to be typically interactive (and thus they aren't affected by this bug):

+ + + +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
On disabled form elements{{CompatVersionUnknown}}[1]{{CompatNo}}{{CompatVersionUnknown}}[2]{{CompatNo}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
On disabled form elements{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Only works for {{HTMLElement("textarea")}} elements and some {{HTMLElement("input")}} element types.

+ +

[2] Internet Explorer only triggers the click event on {{HTMLElement("input")}} elements of type checkbox or radio when the element is double-clicked.

+ +

See also

+ + diff --git a/files/pt-br/web/api/element/closest/index.html b/files/pt-br/web/api/element/closest/index.html new file mode 100644 index 0000000000..cfae3b2c98 --- /dev/null +++ b/files/pt-br/web/api/element/closest/index.html @@ -0,0 +1,127 @@ +--- +title: Element.closest() +slug: Web/API/Element/closest +translation_of: Web/API/Element/closest +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

O método Element.closest() retorna o ancestral mais próximo, em relação ao elemento atual, que possui o seletor fornecido como parâmetro. No caso de o elemento atual possuir o seletor, o mesmo é retornado.  Caso não exista um ancestral o método retorna null.

+ +

Sintaxe

+ +
var elt = element.closest(selectors);
+
+ +

Parâmetros

+ + + +

Valor retornado

+ + + +

Exceções

+ + + +

Exemplo

+ +
<article>
+  <div id="div-01">Esta é a div-01
+    <div id="div-02">Esta é a div-02
+      <div id="div-03">Esta é a div-03</div>
+    </div>
+  </div>
+</article>
+ +
var el = document.getElementById('div-03');
+
+var r1 = el.closest("#div-02");
+// retorna o elemento com id=div-02
+
+var r2 = el.closest("div div");
+// retorna o ancestral mais próximo que é uma div dentro de uma div, nesse caso div-03 é retornada
+
+var r3 = el.closest("article > div");
+// retorna o ancestral mais próximo que é uma div e tem um article como elemento pai, nesse caso div-01 é retornada
+
+var r4 = el.closest(":not(div)");
+// retorna o ancestral mais próximo que não é uma div, neste caso article é retornado
+
+ +

Polyfill

+ +

Para navegadores que não suportam Element.closest(), mas possuem suporte para element.matches() (ou um prefixo equivalente, ou seja IE9+), o seguinte polyfill pode ser usado: 

+ +
if (!Element.prototype.matches)
+    Element.prototype.matches = Element.prototype.msMatchesSelector ||
+                                Element.prototype.webkitMatchesSelector;
+
+if (!Element.prototype.closest)
+    Element.prototype.closest = function(s) {
+        var el = this;
+        if (!document.documentElement.contains(el)) return null;
+        do {
+            if (el.matches(s)) return el;
+            el = el.parentElement;
+        } while (el !== null);
+        return null;
+    };
+
+ +

Contudo, se você de fato precisa dar suporte ao IE 8, você pode usar o polyfill abaixo, o qual é lento mas eficaz. Além disso, ele só garante suporte a seletores CSS 2.1 no IE 8 e ainda pode causar picos de lentidão em websites em produção.

+ +
if (window.Element && !Element.prototype.closest) {
+    Element.prototype.closest =
+    function(s) {
+        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
+            i,
+            el = this;
+        do {
+            i = matches.length;
+            while (--i >= 0 && matches.item(i) !== el) {};
+        } while ((i < 0) && (el = el.parentElement));
+        return el;
+    };
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-element-closest', 'Element.closest()')}}{{Spec2('DOM WHATWG')}}Definição inicial.
+ +

Compatibilidade em navegadores

+ +
{{Compat("api.Element.closest")}}
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/getattribute/index.html b/files/pt-br/web/api/element/getattribute/index.html new file mode 100644 index 0000000000..c5d1a9475b --- /dev/null +++ b/files/pt-br/web/api/element/getattribute/index.html @@ -0,0 +1,76 @@ +--- +title: Element.getAttribute() +slug: Web/API/Element/getAttribute +tags: + - API + - DOM + - Referencia + - metodo +translation_of: Web/API/Element/getAttribute +--- +
{{APIRef("DOM")}}
+ +

Resumo

+ +

getAttribute() retorna o valor de um argumento específico do elemento. Se o atributo não existir, o valor retornado será null ou "" (string vazia). Veja {{Anch("Notas")}} para mais detalhes.

+ +

Sintaxe

+ +
var atributo = element.getAttribute(nomeDoAtributo);
+
+ +

onde

+ + + +

Exemplo

+ +
var div1 = document.getElementById("div1");
+var align = div1.getAttribute("align");
+
+alert(align); // mostra o valor do atributo "align" do elemento com id="div1"
+ +

Notas

+ +

Quando for utilizado para um elemento HTML num DOM sinalizado como documento HTML,  getAttribute() troca de caixa alta para caixa baixa (maiúscula para minúscula) seu argumento antes de prosseguir.

+ +

Essencialmente todos navegadores (Firefox, Internet Explorer, versões recentes do Opera, Safari, Konqueror, e iCab, por exemplo) retornam null quando o atributo especificado não existe no elemento em questão, seguindo que o esboço atual de especificações DOM diz. A velha especificação do DOM 3 Core, por sua vez, diz que correto é retornar uma string vazia e algumas implementações de DOM se comportam dessa forma. Por exemplo, a implementação do getAttribute no XUL (Gecko) segue as especificações do DOM 3 Core e retorna uma string vazia. Consequentemente, deve-se usar {{domxref("Element.hasAttribute()")}} para checar a existência do atributo antes de utilizar o getAttribute()caso exista a possibilidade do argumento inexistir.

+ +
+

Compatibilidade entre browsers

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico2923{{CompatVersionUnknown}}{{CompatVersionUnknown}}6
+ +

{{DOMAttributeMethods}}

+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/element/getboundingclientrect/index.html b/files/pt-br/web/api/element/getboundingclientrect/index.html new file mode 100644 index 0000000000..5f32a3512a --- /dev/null +++ b/files/pt-br/web/api/element/getboundingclientrect/index.html @@ -0,0 +1,84 @@ +--- +title: Element.getBoundingClientRect() +slug: Web/API/Element/getBoundingClientRect +tags: + - API + - CSSOM View + - Método(2) + - Referência(2) +translation_of: Web/API/Element/getBoundingClientRect +--- +
{{APIRef("DOM")}}
+ +

O método Element.getBoundingClientRect() retorna o tamanho de um elemento e sua posição relativa ao viewport.

+ +

Sintaxe

+ +
rectObject = object.getBoundingClientRect();
+
+ +

Valor de retorno

+ +

O valor de retorno é o objeto DOMRect que é a uniāo dos retângulos retornados por getClientRects() para o elemento, ou seja, os atributos border-boxes do CSS associados ao elemento.

+ +

O valor retornado é um objeto DOMRect, que contém as propriedades apenas-leitura left, top, right e bottom que descrevem o border-box em pixels. top e left são relativos às propriedades top-left do viewport.

+ +
+

Nota: {{Gecko("1.9.1")}} adiciona as propriedades width e height ao objeto DOMRect.

+
+ +

Border-boxes vazias são completamente ignoradas. Se todos os border-boxes do elemento são vazias, então é retornado o retângulo com width e height como zero, e no lugar de top e left determina-se o top-left do border-box relacionado ao primeiro box CSS (determinado pela ordem do conteúdo) em relaçāo ao elemento.

+ +

A quantidade de scrolling que foi feita na área do viewport (ou qualquer outra área de qualquer outro elemento scrollable) é tomada com medida ao computar o delimitador do retângulo. Isso significa que as propriedades top e left mudam seus valores tão logo a posiçāo do scroll for alterada (assim seus valores sāo relativos ao viewport e não são absolutos). Se esse não for o comportamento esperado basta adicionar a posição atual do scroll para as propriedades top e left (via window.scrollX e window.scrollY) para pegar os valores constantes independentemente da posiçāo atual do scroll.

+ +

Scripts que requerem uma alta compatibilidade cross-browser podem usar window.pageXOffset e window.pageYOffset ao invés de window.scrollX e window.scrollY. Scripts sem acesso ao window.pageXOffset, window.pageYOffset, window.scrollX e window.scrollY podem usar:

+ +
// Para o scrollX
+(((t = document.documentElement) || (t = document.body.parentNode))
+  && typeof t.ScrollLeft == 'number' ? t : document.body).ScrollLeft
+// Para o scrollY
+(((t = document.documentElement) || (t = document.body.parentNode))
+  && typeof t.ScrollTop == 'number' ? t : document.body).ScrollTop
+
+ +

Exemplo

+ +
// rect é um objeto DOMRect com seis propriedades: left, top, right, bottom, width, height
+var rect = obj.getBoundingClientRect();
+
+ +

Especificaçōes

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSSOM View", "#dom-element-getboundingclientrect", "Element.getBoundingClientRect()")}}{{Spec2("CSSOM View")}}Definiçāo Inicial
+ +

Notas

+ +

getBoundingClientRect() foi primeiramente introduzida no modelo de objeto MS IE DHTML.

+ +

O valor de retorno de getBoundingClientRect() é frozen.

+ +

Compatibilidade

+ +
{{Compat("api.Element.getBoundingClientRect")}}
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/getelementsbyclassname/index.html b/files/pt-br/web/api/element/getelementsbyclassname/index.html new file mode 100644 index 0000000000..2660d0009b --- /dev/null +++ b/files/pt-br/web/api/element/getelementsbyclassname/index.html @@ -0,0 +1,108 @@ +--- +title: Element.getElementsByClassName() +slug: Web/API/Element/getElementsByClassName +translation_of: Web/API/Element/getElementsByClassName +--- +
{{APIRef("DOM")}}
+ +

O método getElementsByClassName() da interface {{domxref("Element")}} retorna um {{domxref("HTMLCollection")}} atualizado simultaneamente que contém todos os elementos descendentes da classe ou das classes especificadas.

+ +

O método {{domxref("Document.getElementsByClassName", "getElementsByClassName()")}} da interface {{domxref("Document")}} funciona da mesma forma, exceto que atua em todo o documento, começando da raíz.

+ +

Sintaxe

+ +
var elements = element.getElementsByClassName(names);
+ +

Parâmetros

+ +
+
names
+
Uma {{domxref("DOMString")}} contendo um ou mais nomes de classes separados por espaço em branco.
+
+ +

Valor de retorno

+ +

Um {{domxref("HTMLCollection")}} que contém uma lista de elementos atualizada em tempo real com todos os elementos que são membros das classes especificadas em names.

+ +

Notas de uso

+ +

Habitualmente, o conjunto de elementos retornado será atualizado simultaneamente com as mudanças feitas, refletindo no estado atual da árvore DOM, no elemento em que a função foi chamada. Assim que novos elementos que satisfazem as classes contidas em names são adicionados na subárvore, eles imediatamente aparecem no conjunto de elementos. Em um exemplo similar, se um elemento existente que não satisfaz nenhuma classe contida em names tem as suas classes ajustadas para que satisfaça, ele irá instantaneamente ser adicionado ao conjunto de elementos.

+ +

O oposto disso também acontece; os elementos que não satisfazerem mais as classes contidas em name serão removidos instantaneamente do conjunto.

+ +
+

No modo quirks, o nome das classes são comparadas da forma case-insensitive. Caso contrário, considere case sensitive.

+
+ +

Exemplos

+ +

Usando uma única classe

+ +

Para procurarmos elementos que incluem uma classe específica, nós apenas informamos o nome da classe ao chamar getElementsByClassName():

+ +
element.getElementsByClassName('test');
+ +

Esse exemplo retorna todos os elementos que possuem a classe test, e que também são filhos do elemento que possui o id com valor main:

+ +
document.getElementById('main').getElementsByClassName('test');
+ +

Usando várias classes

+ +

Para retornar elementos que incluem as classes red and test:

+ +
element.getElementsByClassName('red test');
+ +

Examinando os resultados

+ +

You can use either the {{domxref("HTMLCollection.item", "item()")}} method on the returned HTMLCollection or standard array syntax to examine individual elements in the collection. However the following code will not work as one might expect because "matches" will change as soon as any "colorbox" class is removed.

+ +
var matches = element.getElementsByClassName('colorbox');
+
+for (var i=0; i<matches.length; i++) {
+  matches[i].classList.remove('colorbox');
+  matches.item(i).classList.add('hueframe');
+}
+
+ +

Instead, use another method, such as:

+ +
var matches = element.getElementsByClassName('colorbox');
+
+while (matches.length > 0) {
+  matches.item(0).classList.add('hueframe');
+  matches[0].classList.remove('colorbox');
+}
+ +

This code finds descendant elements with the "colorbox" class, adds the class "hueframe", by calling item(0), then removes "colorbox" (using array notation). Another element (if any are left) will then become item(0).

+ +

Filtering the results using array methods

+ +

We can also use methods of {{jsxref("Array.prototype")}} on any {{ domxref("HTMLCollection") }} by passing the {{domxref("HTMLCollection")}} as the method's this value. Here we'll find all {{HTMLElement("div")}} elements that have a class of test:

+ +
var testElements = document.getElementsByClassName('test');
+var testDivs = Array.prototype.filter.call(testElements, function(testElement) {
+  return testElement.nodeName === 'DIV';
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-getelementsbyclassname', 'Element.getElementsByClassName()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Element.getElementsByClassName")}}

diff --git a/files/pt-br/web/api/element/id/index.html b/files/pt-br/web/api/element/id/index.html new file mode 100644 index 0000000000..864b1fe8b3 --- /dev/null +++ b/files/pt-br/web/api/element/id/index.html @@ -0,0 +1,119 @@ +--- +title: Element.id +slug: Web/API/Element/id +tags: + - API + - DOM + - Gecko + - Property + - Reference +translation_of: Web/API/Element/id +--- +
{{ApiRef("DOM")}}
+ +
 
+ +

A propriedade Element.id representa o identificador do elemento, refletindo no atributo global id.

+ +

O ID precisa ser único no documento, e geralmente é utilizado para obter o elemento usando {{domxref("document.getElementById", "getElementById")}}.. Outro uso comum de id é utilizar o ID como um seletor ao estilizar o documento com CSS.

+ +
+

Nota: IDs são case-sensitive, mas você não deve criar IDs cuja única diferença nos nomes sejam letras maiúsculas/minúsculas (veja Case sensitivity in class and id names).

+
+ +

Sintaxe

+ +
var idStr = element.id; // Retorna o id.
+element.id = idStr; // Insere o id
+
+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-element-id', 'id')}}{{Spec2('DOM WHATWG')}}Sem alteração desde {{SpecName('DOM2 HTML')}}.
{{SpecName('DOM2 HTML', 'html.html#ID-63534901', 'id')}}{{Spec2('DOM2 HTML')}}Sem alteração desde {{SpecName('DOM1')}}.
{{SpecName('DOM1', 'level-one-html.html#ID-63534901', 'id')}}{{Spec2('DOM1')}}Definição inicial.
+ +

Compatibilidade com os browsers

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/index.html b/files/pt-br/web/api/element/index.html new file mode 100644 index 0000000000..b3779720d9 --- /dev/null +++ b/files/pt-br/web/api/element/index.html @@ -0,0 +1,529 @@ +--- +title: Element +slug: Web/API/Element +tags: + - API + - DOM + - DOM Reference + - Element + - Interface + - Reference + - Web API +translation_of: Web/API/Element +--- +

{{ APIRef("DOM") }}

+ +

A interface Element é a classe base mais geral da qual todos os objetos em um {{domxref("Document")}} herda. Ela somente tem métodos e propriedades comuns para todos os tipos de elementos. Mais classes específicas herdam de Element. Por exemplo, a interface {{domxref("HTMLElement")}} é a interface base para elementos HTML, enquanto a interface {{domxref("SVGElement")}} é a base para todos os elementos SVG. A maioria das funcionalidades é especificada mais abaixo da hierarquia de classes. 

+ +

Linguagens fora do domínio da plataforma da Web, como XUL através da interface XULElement, também implementa Element.

+ +

Propriedades

+ +

Herda propriedades de seus parentes {{domxref("Node")}}, e seu próprio parente, {{domxref("EventTarget")}}, e implementa aqueles de {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}, e {{domxref("Animatable")}}.

+ +
+
{{ domxref("Element.attributes") }}  {{readOnlyInline}}
+
Retorna um {{ domxref("NamedNodeMap") }} que lista todos os atributos associados ao elemento.
+
{{ domxref("ParentNode.childElementCount") }}
+
É um {{jsxref("Number")}} representando o número de nós filhos que são elementos.
+
{{ domxref("ParentNode.children") }}
+
É um {{ domxref("HTMLCollection") }} ao vivo contendo todos os elementos filhos do elemento, como uma coleção.
+
{{ domxref("Element.classList") }} {{readOnlyInline}}
+
Retorna um {{ domxref("DOMTokenList") }} contendo a lista de atributos de classe.
+
{{ domxref("Element.className") }}
+
É um {{domxref("DOMString")}} representando a classe do elemento.
+
{{ domxref("Element.clientHeight") }} {{experimental_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando a altura interna do elemento.
+
{{ domxref("Element.clientLeft") }} {{experimental_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando a largura da borda do elemento..
+
{{ domxref("Element.clientTop") }} {{experimental_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando a largura da borda do topo do elemento.
+
{{ domxref("Element.clientWidth") }} {{experimental_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando a largura interna do elemento.
+
{{ domxref("ParentNode.firstElementChild") }}
+
+

É um {{ domxref("Element") }}, o primeiro elemento filho direto de um elemento, ou null se o elemento não tem elementos filho.

+
+
{{ domxref("Element.id") }}
+
É um {{domxref("DOMString")}} representando o id do elemento.
+
{{ domxref("Element.innerHTML") }} {{experimental_inline}}
+
É um {{domxref("DOMString")}} representando a marcação do conteúdo do elemento.
+
{{ domxref("ParentNode.lastElementChild") }}
+
É um {{ domxref("Element") }}, o último elemento filho direto de um elemento, ou null se o elemento não tem elementos filho.
+
{{ domxref("NonDocumentTypeChildNode.nextElementSibling") }}
+
É um {{ domxref("Element") }}, o elemento seguido imediatamente do dito na árvore, ou null se não há nó irmão.
+
{{ domxref("Element.outerHTML") }} {{experimental_inline}}
+
É um {{domxref("DOMString")}} representando a marcação do elemento incluindo seu conteúdo. Quando usado como um setter, substitui o elemento com nós analisados a partir de uma determinada string.
+
{{ domxref("NonDocumentTypeChildNode.previousElementSibling") }}
+
É um {{ domxref("Element") }}, o elemento precedido imediatamente do dito na árvore, ou nulo se não há elemento irmão.
+
{{ domxref("Element.scrollHeight") }} {{experimental_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando a altura da vista de rolagem de um elemento.
+
{{ domxref("Element.scrollLeft") }} {{experimental_inline}}
+
É um {{jsxref("Number")}} representando o deslocamento de rolagem esquerdo do elemento.
+
{{ domxref("Element.scrollLeftMax") }} {{non-standard_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando o deslocamento de rolagem esquerdo máximo possível para o elemento.
+
{{ domxref("Element.scrollTop") }} {{experimental_inline}}
+
É um {{jsxref("Number")}} representando o deslocamento de rolagem superior de um elemento.
+
{{ domxref("Element.scrollTopMax") }} {{non-standard_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando o deslocamento de rolagem máximo superior possível para o elemento.
+
{{ domxref("Element.scrollWidth") }} {{experimental_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando a largura de exibição de rolagem do elemento.
+
{{domxref("Element.shadowRoot") }} {{experimental_inline}} {{readOnlyInline}}
+
...
+
{{ domxref("Element.tagName") }} {{readOnlyInline}}
+
Retorna um {{domxref("String")}} com o nome da tag para o elemento em questão.
+
{{ domxref("Element.undoManager")}} {{experimental_inline}} {{readOnlyInline}}
+
Retorna o {{domxref("UndoManager")}} associado com o elemento.
+
{{ domxref("Element.undoScope")}} {{experimental_inline}}
+
É a {{jsxref("Boolean")}} indicando se o elemento é um anular hospedagem de escopo, ou não.
+
+ +

Manipuladores de Eventos

+ +
+
{{ domxref("Element.ongotpointercapture") }}
+
+
{{ domxref("Element.onlostpointercapture") }}
+
+
{{ domxref("Element.onwheel") }} {{ non-standard_inline() }}
+
Retorna o código de manipulação de evento para o evento wheel.
+
+ +

Métodos

+ +

Herda métodos de seus parentes {{domxref("Node")}}, e seu proprío parente, {{domxref("EventTarget")}}, e implementa aqueles de  {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}, e {{domxref("Animatable")}}.

+ +
+
{{ domxref("EventTarget.addEventListener()") }}
+
Registra um manipulador de evento para um tipo específico de evento no elemento.
+
{{ domxref("Element.closest()")}} {{experimental_inline}}
+
Retorna o {{domxref("Element")}}, descendente deste elemento(ou este elemento em si), que é o ancestral mais próximo dos elementos selecionados pelos seletores dados no parâmetro.
+
{{ domxref("Element.createShadowRoot()")}} {{experimental_inline}}
+
+
{{ domxref("EventTarget.dispatchEvent()") }}
+
Despacha um evento para este nó no DOM e retorna um {{jsxref("Boolean")}} que indica que pelo menos um manipulador não o cancelou.
+
{{domxref("Element.find()")}}{{experimental_inline}}
+
...
+
{{domxref("Element.findAll()")}}{{experimental_inline}}
+
...
+
{{domxref("Animatable.getAnimationPlayers()")}} {{experimental_inline}}
+
+
{{ domxref("Element.getAttribute()") }}
+
Recupera o valor do atributo nomeado do nó atual e o retorna como um {{jsxref("Object")}}.
+
{{ domxref("Element.getAttributeNS()") }}
+
Recupera o valor do atributo com o nome especificado e namespace, do nó atual e o retorna como um {{jsxref("Object")}}.
+
{{ domxref("Element.getAttributeNode()") }} {{obsolete_inline}}
+
Recupera a representação do nó de um atributo nomeado do nó atual e o retorna como um {{ domxref("Attr") }}.
+
{{ domxref("Element.getAttributeNodeNS()") }} {{obsolete_inline}}
+
Recupera a representação de nó do atributo com o nome especificado e namespace, do nó atual e o retorna como um {{ domxref("Attr") }}.
+
{{ domxref("Element.getBoundingClientRect()") }} {{experimental_inline}}
+
...
+
{{ domxref("Element.getClientRects()") }} {{experimental_inline}} TYPE of returnvalue????
+
Retorna uma coleção de retângulos que indicam os retângulos delimitadores para cada linha de texto em um cliente.
+
{{domxref("Element.getDestinationInsertionPoints()")}} {{experimental_inline}}
+
+
{{ domxref("Element.getElementsByClassName()") }}
+
Retorna um {{ domxref("HTMLCollection") }} vivo que contêm todos os descendentes do elemento atual que possui a lista de classes dadas no parâmetro.
+
{{ domxref("Element.getElementsByTagName()") }}
+
Retorna um {{ domxref("HTMLCollection") }} vivo contendo todos os elementos descendentes, de uma etiqueta de nome particular, do elemento atual.
+
{{ domxref("Element.getElementsByTagNameNS()") }}
+
Retorna um {{ domxref("HTMLCollection") }} vivo contendo todos os elementos descendentes, de uma etiqueta de nome particular e namespace, do elemento atual.
+
{{ domxref("Element.hasAttribute()") }}
+
Retorna um {{jsxref("Boolean")}} indicando se o elemento tem o atributo especificado ou não.
+
{{ domxref("Element.hasAttributeNS()") }}
+
Retorna um {{jsxref("Boolean")}} indicando se o elemento tem um atributo especificado, no namespace especificado, ou não.
+
{{ domxref("Element.insertAdjacentHTML") }} {{experimental_inline}}
+
Analisa o texto como HTML ou XML e insere os nós resultantes na árvore em dada posição.
+
{{ domxref("Element.matches()") }} {{experimental_inline}}
+
Retorna um {{jsxref("Boolean")}} indicando se o elemento seria ou não selecionado pelo seletor de string specificada.
+
{{ domxref("Element.querySelector()") }}
+
Retorna {{ domxref("Node") }}...
+
{{ domxref("Element.querySelectorAll") }}
+
Retorna um {{ domxref("NodeList") }}...
+
{{ domxref("Element.releasePointerCapture")}} {{experimental_inline}}
+
+
{{domxref("ChildNode.remove()")}}
+
Remove o elemento da lista de filhos de seu parente.
+
{{ domxref("Element.removeAttribute()") }}
+
Remove um atributo nomeado do nó atual.
+
{{ domxref("Element.removeAttributeNS()") }}
+
Remove o atributo com o nome especificado ou namespace, do nó atual.
+
{{ domxref("Element.removeAttributeNode()") }} {{obsolete_inline}}
+
Remove a representação do nó do atributo nomeado do nó atual.
+
{{ domxref("EventTarget.removeEventListener()") }}
+
Remove um ouvinte de eventos do elemento.
+
{{ domxref("Element.requestFullscreen()") }} {{experimental_inline}}
+
Assíncronamente pede o navegador para fazer o elemento tela cheia.
+
{{ domxref("Element.requestPointerLock()")}} {{experimental_inline}}
+
Permite assíncronamente pedir pelo apontador para ser bloqueado em um dado elemento.
+
+ +
+
{{ domxref("Element.scrollIntoView()") }} {{experimental_inline}}
+
Rola a página até que o elemento apareça na visão.
+
{{ domxref("Element.setAttribute()") }}
+
Define o valor de um atributo nomeado do nó atual.
+
{{ domxref("Element.setAttributeNS()") }}
+
Define o valor do atributo com o nome especificado e namespace, do nó atual.
+
{{ domxref("Element.setAttributeNode()") }} {{obsolete_inline}}
+
Define a representação do nó de um atributo nomeado do nó atual.
+
{{ domxref("Element.setAttributeNodeNS()") }} {{obsolete_inline}}
+
Define a representação do nó do atributo com o nome especificado e namespace, do nó atual.
+
{{ domxref("Element.setCapture()") }} {{non-standard_inline}}
+
Define a captura de evento do mouse, redirecionando todos os eventos de mouse para este elemento.
+
{{domxref("Element.setPointerCapture()")}}
+
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Web Animations", '', '')}}{{Spec2("Web Animations")}}Adicionado o método getAnimationPlayers().
{{SpecName('Undo Manager', '', 'Element')}}{{Spec2('Undo Manager')}}Adicionadas as propriedades undoScopeundoManager.
{{SpecName('Pointer Events', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('Pointer Events')}}Adicionados os seguintes manipuladores de evento: ongotpointercaptureonlostpointercapture.
+ Adicionados os seguintes métodos: setPointerCapture()releasePointerCapture().
{{SpecName('Selectors API Level 2', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 2')}}Adicionados os seguintes métodos: matches() (implementado como mozMatchesSelector()), find(), findAll().
{{SpecName('Selectors API Level 1', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 1')}}Adicionados os seguintes métodos: querySelector()querySelectorAll().
{{SpecName('Pointer Lock', 'index.html#element-interface', 'Element')}}{{Spec2('Pointer Lock')}}Adicionado o método requestPointerLock().
{{SpecName('Fullscreen', '#api', 'Element')}}{{Spec2('Fullscreen')}}Adicionado o método requestFullscreen().
{{SpecName('DOM Parsing', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('DOM Parsing')}}Adicionadas as seguintes propriedades: innerHTML, e outerHTML.
+ Adicionado o seguinte método: insertAdjacentHTML().
{{SpecName('CSSOM View', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('CSSOM View')}}Adicionadas as seguintes propriedades: scrollTop, scrollLeft, scrollWidth, scrollHeight, clientTop, clientLeft, clientWidth, e clientHeight.
+ Adicionados os seguintes métodos: getClientRects(), getBoundingClientRect(), e scrollIntoView().
{{SpecName('Element Traversal', '#ecmascript-bindings', 'Element')}}{{Spec2('Element Traversal')}}Adicionada herança da interface {{domxref("ElementTraversal")}}.
{{SpecName('DOM WHATWG', '#interface-element', 'Element')}}{{Spec2('DOM WHATWG')}}Removidos os seguintes métodos: closest(), setIdAttribute(), setIdAttributeNS(), e setIdAttributeNode().
+ Removida a propriedade schemaTypeInfo.
+ Modificado o valor de retorno de getElementsByTag()getElementsByTagNS().
+ Movida hasAttributes() da interface Node para esta.
{{SpecName('DOM3 Core', 'core.html#ID-745549614', 'Element')}}{{Spec2('DOM3 Core')}}Adicionados os seguintes métodos: setIdAttribute(), setIdAttributeNS(), e setIdAttributeNode(). Estes métodos nunca foram implementados e foram removidos em especificações posteriores.
+ Adicionada a propriedade schemaTypeInfo. Esta propriedade nunca foi implementada e foi removida em especificações posteriores.
{{SpecName('DOM2 Core', 'core.html#ID-745549614', 'Element')}}{{Spec2('DOM2 Core')}}O método normalize() foi movido para {{domxref("Node")}}.
{{SpecName('DOM1', 'level-one-core.html#ID-745549614', 'Element')}}{{Spec2('DOM1')}}Definição inicial.
+ +

Compatibilidade de Navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{CompatGeckoDesktop("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}1.0
children{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}7.0 com um bug significativo[1]
+ 9.0 de acordo com as especificações
{{CompatVersionUnknown}}{{CompatNo}}
childElementCount, nextElementSibling, previousElementSibling{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
firstElementChild, lastElementChild{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
classList{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}} {{CompatVersionUnknown}}{{CompatVersionUnknown}}
outerHTML {{experimental_inline}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("11")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
clientLeft, clientTop {{experimental_inline}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getBoundingClientRect(), getClientRects() {{experimental_inline}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
querySelector(), querySelectorAll()1.0{{CompatGeckoDesktop("1.9.1")}}8.010.03.2 (525.3)
insertAdjacentHTML() {{experimental_inline}}1.0{{CompatGeckoDesktop("8")}}4.07.04.0 (527)
setCapture() {{non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("2")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
oncopy, oncut, onpaste {{non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}} {{CompatNo}}
onwheel {{non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("17")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
ongotpointercapture, onlostpointercapture, setPointerCapture(), e releasePointerCapture(){{CompatNo}}{{CompatNo}}10.0 {{property_prefix("MS")}}{{CompatNo}}{{CompatNo}}
matches() {{experimental_inline}}{{CompatVersionUnknown}} com o nome não padrão webkitMatchesSelector{{CompatGeckoDesktop("1.9.2")}} com o nome não padrão mozMatchesSelector
+ {{CompatGeckoDesktop("34")}} com o nome padrão
9.0 com o nome não padrão msMatchesSelector11.5 com o nome não padrão oMatchesSelector
+ 15.0 com o nome não padrão webkitMatchesSelector
5.0 com o nome não padrão webkitMatchesSelector
find()findAll(){{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
requestPointerLock()16.0  {{property_prefix("webkit")}}, atrás de um about:flags
+ 22.0 {{property_prefix("webkit")}} (com casos especiais, levantados progressivamente, veja [2])
{{CompatGeckoDesktop("14")}}{{property_prefix("moz")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
requestFullscreen()14.0 {{property_prefix("webkit")}}{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}11.0 {{property_prefix("ms")}}12.10
+ 15.0 {{property_prefix("webkit")}}
5.1 {{property_prefix("webkit")}}
undoManagerundoScope{{CompatNo}}{{CompatVersionUnknown}} (atrás do pref dom.undo_manager.enabled){{CompatNo}}{{CompatNo}}{{CompatNo}}
attributes{{CompatUnknown}}{{CompatGeckoDesktop("22")}}
+ Antes era disponível via interface {{domxref("Node")}} que qualquer element herda.
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
scrollTopMax()scrollLeftMax(){{CompatNo}}{{CompatGeckoDesktop("16")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
closest(){{CompatUnknown}}{{CompatGeckoDesktop("35")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
hasAttributes(){{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}} (na interface {{domxref("Node")}})
+ {{CompatGeckoDesktop("35")}} (nesta interface)
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico1.0{{CompatGeckoMobile("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}1.0
scrollTopMax() and scrollLeftMax(){{CompatNo}}{{CompatGeckoMobile("16")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
closest(){{CompatUnknown}}{{CompatGeckoMobile("35")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
hasAttributes(){{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}} (na interface {{domxref("Node")}})
+ {{CompatGeckoMobile("35")}} (nesta interface)
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Internet Explorer 7 e 8 incorretamente retorna os comentários como parte do filho de um Element. Isto está fixado no Internet Explorer 9 e posterior.

+ +

[2] Chrome 16 permitiu webkitRequestPointerLock() somente em tela cheia; Chrome 21 para website confiável(com permissão do usuário);  Chrome 22 permitiu por padrão para todos documentos de mesma origem; Chrome 23 permitiu em testes em ambientes locais {{HTMLElement("iframe")}} se o valor não padrão webkit-allow-pointer-lock é definido para o atributo {{htmlattrxref("sandbox", "iframe")}}.

diff --git a/files/pt-br/web/api/element/innerhtml/index.html b/files/pt-br/web/api/element/innerhtml/index.html new file mode 100644 index 0000000000..f9ba30f9cf --- /dev/null +++ b/files/pt-br/web/api/element/innerhtml/index.html @@ -0,0 +1,148 @@ +--- +title: Element.innerHTML +slug: Web/API/Element/innerHTML +tags: + - API + - DOM + - Gecko + - NeedsBrowserCompatibility + - Propriedade + - Referência(2) +translation_of: Web/API/Element/innerHTML +--- +

{{APIRef("DOM")}}

+ +

A propriedade Element.innerHTML define ou obtém a sintaxe HTML ou XML descrevendo os elementos descendentes.

+ +
Nota: Se um nó {{HTMLElement("div")}}, {{HTMLElement("span")}}, ou {{HTMLElement("noembed")}} tem um nó filho que inclui os caracteres (&), (<), ou (>), o innerHTML retornará esses caracteres como &amp, &lt e &gt respectivamente. Utilize {{domxref("Node.textContent")}} para recuperar uma cópia correta do conteúdo desses nós de texto.
+ +

Sintaxe

+ +
var content = element.innerHTML;
+ +

No retorno, content contém o código HTML serializado descrevendo todos os descendentes dos elementos.

+ +
 element.innerHTML = content;
+ +

Remove todos os elementos filhos, analisa o conteúdo da string e atribui os nós resultantes como filhos do elemento.

+ +

Exceptions

+ +
+
SyntaxError
+
Foi feita uma tentativa de definir o valor de um innerHTML usando uma string que não é HTML.
+
NoModificationAllowedError
+
Foi feita uma tentativa de inserir HTML dentro de um nó no qual o pai é um {{domxref("Document")}}.
+
+ +

Exemplo

+ +
<html>
+<head></head>
+<body>
+
+<div id="txt">
+  <script     id="txt0"> x=0 </script>
+    <noembed    id="txt1"> 1   </noembed>
+    <noframes   id="txt2"> 2   </noframes>
+    <noscript   id="txt3"> 3   </noscript>
+    <div        id="txt4"> 4   </div>
+    <div>
+      <noscript id="txt5"> 5   </noscript>
+    </div>
+    <span       id="txt6"> 6   </span>
+  </div>
+
+  <div id="innerHTMLtxt"></div>
+<div id="textContenttxt"><div>
+
+<script>
+for (i = 0; i < 7; i++) {
+    x = "txt" + i;
+    document.getElementById(x).firstChild.nodeValue = '&<>';
+}
+
+document.getElementById("innerHTMLtxt").textContent = document.getElementById("txt").innerHTML
+document.getElementById("textContenttxt").textContent = document.getElementById("txt").textContent
+</script>
+
+<body>
+</html>
+ +
// HTML:
+// <div id="d"><p>Content</p>
+// <p>Further Elaborated</p>
+// </div>
+
+const d = document.getElementById("d");
+dump(d.innerHTML);
+
+//  a string "<p>Content</p><p>Further Elaborated</p>"
+// é exibida na janela do console
+
+ +

Notas

+ +

Essa propriedade fornece uma forma simples de trocar completamente o conteúdo de um elemento. Por exemplo, o conteúdo inteiro do elemento body pode ser excluído ao fazer:

+ +
// Troca o conteúdo de body por uma string vazia.
+document.body.innerHTML = "";  
+ +

A propriedade innerHTML de vários tipos de elementos — incluindo {{HTMLElement("body")}} ou {{HTMLElement("html")}} — pode ser retornada ou trocada. Essa também pode ser usada para ver o código fonte de uma página que foi modificada dinamicamente:

+ +
// Copie e cole este código, em uma única linha, na barra de endereços
+javascript:"<pre>"+document.documentElement.innerHTML.replace(/</g,"&lt;") + "</pre>";
+
+ +

Essa propriedade foi implementada inicialmente pelos navegadores web, e então especificada pela WHATWG e W3C no HTML5. Implementações antigas talvez não tenham implementado-a exatamente da mesma forma. Por exemplo, quando um texto é inserido em uma caixa de texto, o Internet Explorer muda o valor do atributo innerHTML dessa entrada, mas os navegadores Gecko não.

+ +

Considerações de segurança

+ +

Não é incomum ver a propriedade innerHTML usada para inserir texto em uma página web. Isso vem com um risco de segurança.

+ +
var name = "John";
+
+// presumindo que el é um elemento DOM HTML
+el.innerHTML = name; // inofensivo, nesse caso
+
+// ...
+
+name = "<script>alert('I am John in an annoying alert!')</script>";
+el.innerHTML = name; // inofensivo, nesse caso
+ +

Embora isso talvez se pareça como um ataque  {{interwiki("wikipedia", "cross-site scripting")}}, o resultado é inofensivo. O HTML5 especifica que uma tag {{HTMLElement("script")}}, inserida via innerHTML, não deve ser executada.

+ +

No entanto, há formas de se executar JavaScript sem usar elementos {{HTMLElement("script")}}, por isso ainda há um risco de segurança sempre que você usa innerHTML para definir uma string sobre a qual você não tem controle. Por exemplo:

+ +
const name = "<img src='x' onerror='alert(1)'>";
+el.innerHTML = name; // exibe uma caixa de alerta
+ +

Por essa razão, recomenda-se que você não use o innerHTML quando estiver inserindo texto puro; como alternativa, utilize {{domxref("node.textContent")}}. Isso não interpreta o conteúdo passado como HTML, mas em vez disso, insere-o como texto puro.

+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('DOM Parsing', '#widl-Element-innerHTML', 'Element.innerHTML')}}{{ Spec2('DOM Parsing') }}Definição inicial
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/insertadjacenthtml/index.html b/files/pt-br/web/api/element/insertadjacenthtml/index.html new file mode 100644 index 0000000000..89a0bbdfcc --- /dev/null +++ b/files/pt-br/web/api/element/insertadjacenthtml/index.html @@ -0,0 +1,138 @@ +--- +title: Element.insertAdjacentHTML() +slug: Web/API/Element/insertAdjacentHTML +translation_of: Web/API/Element/insertAdjacentHTML +--- +
{{APIRef("DOM")}}
+ +

Resumo

+ +

insertAdjacentHTML analisa o texto especificado como HTML ou XML e insere os nós que resultam na árvore DOM em uma posição especificada. Não reanalisa o elemento que está a ser utilizado e, portanto, não corrompe os elementos existentes dentro do elemento. Esta, e evitando a etapa extra de serialização, torna-o muito mais rápido do que a manipulação direta innerHTML.

+ +

Sintaxe

+ +
element.insertAdjacentHTML(posição, texto);
+ +

Posição é a posição em relação ao elemento, e deve ser um dos seguintes tipos:

+ +
+
'beforebegin'
+
Antes do elemento.
+
'afterbegin'
+
Dentro do elemento, antes de seu primeiro filho (childNode).
+
'beforeend'
+
Dentro do elemento, após seu último filho (childNode) .
+
'afterend'
+
Após o elemento.
+
+ +

texto é a string a ser analisada como HTML ou XML e inserido na árvore.

+ +

Visualização da posição de nomes

+ +
<!-- beforebegin -->
+<p>
+<!-- afterbegin -->
+foo
+<!-- beforeend -->
+</p>
+<!-- afterend -->
+ +
Nota:  As posições beforeBegin e afterEnd funcionam apenas se o nó está em uma árvore DOM e tem um elemento pai.
+ +

Exemplo

+ +
// Estrutura inicial:
+// <div id="one">one</div>
+
+var d1 = document.getElementById('one');
+d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
+
+// Neste ponto, a nova estrutura é:
+// <div id="one">one</div>
+// <div id="two">two</div>
+ +

Especificação

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#insertadjacenthtml()', 'Element.insertAdjacentHTML()')}}{{ Spec2('DOM Parsing') }} 
+ +

Compatibilidade de Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{ CompatGeckoDesktop("8.0") }}4.0*7.04.0 (527)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
 CaracterísticaAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("8.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+ +

 

+ +

Questão no IE:

+ + +
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/matches/index.html b/files/pt-br/web/api/element/matches/index.html new file mode 100644 index 0000000000..06ce8b5c31 --- /dev/null +++ b/files/pt-br/web/api/element/matches/index.html @@ -0,0 +1,165 @@ +--- +title: Element.matches() +slug: Web/API/Element/matches +translation_of: Web/API/Element/matches +--- +
{{APIRef("DOM")}}
+ +

O método Element.matches() retorna verdadeiro se o elemento puder ser selecionado pela sequência de caracteres específica; caso contrário retorna falso.

+ +
+

Diversos navegadores implementam isto, prefixado, sob nome não padronizado matchesSelector().

+
+ +

Sintaxe

+ +
var result = element.matches(selectorString);
+
+ + + +

Exemplo

+ +
<ul id="birds">
+  <li>Orange-winged parrot</li>
+  <li class="endangered">Philippine eagle</li>
+  <li>Great white pelican</li>
+</ul>
+
+<script type="text/javascript">
+  var birds = document.getElementsByTagName('li');
+
+  for (var i = 0; i < birds.length; i++) {
+    if (birds[i].matches('.endangered')) {
+      console.log('The ' + birds[i].textContent + ' is endangered!');
+    }
+  }
+</script>
+
+ +

Isto irá logar "The Philippine eagle is endangered!" para o console, desde que o elemento tenha de fato um atributo de classe com o valor endangered.

+ +

Exceções

+ +
+
SYNTAX_ERR
+
O seletor de string específico é inválido.
+
+ +

Polyfill

+ +

Para navegadores que não suportam Element.matches() ou Element.matchesSelector(),  mass possuem suporte para document.querySelectorAll(), existe um polyfill:

+ +
if (!Element.prototype.matches) {
+    Element.prototype.matches =
+        Element.prototype.matchesSelector ||
+        Element.prototype.mozMatchesSelector ||
+        Element.prototype.msMatchesSelector ||
+        Element.prototype.oMatchesSelector ||
+        Element.prototype.webkitMatchesSelector ||
+        function(s) {
+            var matches = (this.document || this.ownerDocument).querySelectorAll(s),
+                i = matches.length;
+            while (--i >= 0 && matches.item(i) !== this) {}
+            return i > -1;
+        };
+}
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-element-matches', 'Element.prototype.matches')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Compatibilidade de navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Original support with a non-standard name +

{{CompatVersionUnknown}}[1]

+
{{CompatGeckoDesktop("1.9.2")}}[2]9.0[3]11.5[4]
+ 15.0[1]
5.0[1]
Specified version{{CompatChrome("34")}}{{CompatGeckoDesktop("34")}}{{CompatUnknown}}21.07.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Original support with a non-standard name{{CompatUnknown}}{{CompatGeckoMobile("1.9.2")}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Specified version{{CompatUnknown}}{{CompatGeckoMobile("34")}}{{CompatUnknown}}{{CompatUnknown}}8
+
+ +

[1] Esta feature foi implementada com o nome não padronizado webkitMatchesSelector.

+ +

[2] Esta feature foi implementada com o nome não padronizado mozMatchesSelector. Anteriormente para o Gecko 2.0, seletores de string inválido faziam com que retornasse false ao invés de empurrar uma exceção.

+ +

[3] Esta feature foi implementada com o nome não padronizado msMatchesSelector.

+ +

[4] Esta feature foi implementada com o nome não padronizado oMatchesSelector.

diff --git a/files/pt-br/web/api/element/mousedown_event/index.html b/files/pt-br/web/api/element/mousedown_event/index.html new file mode 100644 index 0000000000..bbddbff605 --- /dev/null +++ b/files/pt-br/web/api/element/mousedown_event/index.html @@ -0,0 +1,235 @@ +--- +title: mousedown +slug: Web/API/Element/mousedown_event +tags: + - API + - DOM + - Interface + - NeedsSpecTable + - Reference + - events +translation_of: Web/API/Element/mousedown_event +--- +
{{APIRef}}
+ +

O evento mousedown é ativado quando um botão de um dispositivo apontador é pressionado sobre um elemento.

+ +

Informação geral

+ +
+
Especificação
+
DOM L3
+
Interface
+
{{domxref("MouseEvent")}}
+
Bubbles
+
Sim
+
Cancelável
+
Sim
+
Alvo
+
Elemento
+
Ação Padrão
+
Varia: Inicia um operação de arrastar/soltar; inicia a seleção de texto; inicia a interação de rolagem/arrastar (junto do botão do meio do mouse, se suportado)
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}} +

O alvo do evento (o alvo mais alto na árvore do DOM).

+
type {{readonlyInline}}{{domxref("DOMString")}}O tipo de evento
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not
cancelable {{readonlyInline}}BooleanO evento é cancelável ou não?
view {{readonlyInline}}{{domxref("WindowProxy")}}{{domxref("document.defaultView")}} (window do documento)
detail {{readonlyInline}}long (float) +

Um número de cliques consecutivos que aconteceu num pequeno espaço de tempo, acrescido em um.

+
currentTarget {{readonlyInline}}{{domxref("EventTarget")}}O nó que teve o listener do evento anexado.
relatedTarget {{readonlyInline}}{{domxref("EventTarget")}}Para os eventos mouseovermouseoutmouseenter e mouseleave: o alvo do evento complementar (o alvo do mouseleave no caso de um evento mouseenter). Caso contrário, null.
screenX {{readonlyInline}}longA coordenada X do mouse baseada nas coordenadas globais (tela).
screenY {{readonlyInline}}longA coordenada Y do mouse baseada nas coordenadas globais (tela).
clientX {{readonlyInline}}longA coordenada X do ponteiro do mouse baseada nas coordenadas locais (conteúdo do DOM).
clientY {{readonlyInline}}longA coordenada Y do ponteiro do mouse baseada nas coordenadas locais (conteúdo do DOM).
button {{readonlyInline}}unsigned shortO número do botão que foi pressionado quando o evento mouse foi ativado: Botão esquerdo = 0, botão do meio = 1 (se presente), botão direito = 2. Para os mouses configurados para uso por canhotos onde as ações do mouse são invertidas, os valores são lidos da direita para a esquerda.
buttons {{readonlyInline}}unsigned short +

Os botões pressionados que foram pressionados quando o evento do mouse foi ativado: Botão esquerdo = 1, botão direito = 2, botão do meio (roda) = 4, 4º botão (geralmente, o "botão de voltar") = 8, 5º botão (geralmente, o "botão de avançar") = 16. Se dois ou mais botões são pressionados, retorna a soma lógica dos valores. Exemplo: se o Botão esquerdo e o Botão direito são pressionados, retorna 3 (=1 | 2). Mais informações.

+
mozPressure {{readonlyInline}}floatA quantidade de pressão aplicada a um dispositivo touch ou tablet quando o evento estava sendo gerado; este valor varia entre 0.0 (pressão mínima) e 1.0 (pressão máxima).
ctrlKey {{readonlyInline}}booleantrue se a tecla control estava pressionada quando o evento foi ativado. Caso contrário, false.
shiftKey {{readonlyInline}}booleantrue se a tecla shift estava pressionada quando o evento foi ativado. Caso contrário, false.
altKey {{readonlyInline}}booleantrue se a tecla alt estava pressionada quando o evento foi ativado. Caso contrário, false.
metaKey {{readonlyInline}}booleantrue se a tecla meta estava pressionada quando o evento foi ativado. Caso contrário, false.
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Em elementos desativados{{CompatVersionUnknown}}[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Em elementos desativados{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Só funciona em elementos {{HTMLElement("textarea")}} e alguns tipos do elemento {{HTMLElement("input")}}.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/mouseenter_event/index.html b/files/pt-br/web/api/element/mouseenter_event/index.html new file mode 100644 index 0000000000..881958914b --- /dev/null +++ b/files/pt-br/web/api/element/mouseenter_event/index.html @@ -0,0 +1,314 @@ +--- +title: mouseenter +slug: Web/API/Element/mouseenter_event +translation_of: Web/API/Element/mouseenter_event +--- +
{{APIRef}}
+ +

O evento mouseenter é disparado quando um dispositivo de apontamento (geralmente um mouse) se move sobre um elemento (para dentro do mesmo).

+ +

Similar ao {{event('mouseover')}}, ele se diferencia no fato de que não ocorre a fase bubble e não é disparado quando o cursor / apontador mover-se do espaço físico de um de seus descendentes para o seu próprio espaço físico.

+ +
+
mouseenter.png
+Um evento mouseenter é enviado para cada elemento da hierarquia ao entrar neles. Aqui 4 eventos são enviados aos quatro elementos da hierarquia quando o cursor / apontador chega no Text. + +
mouseover.png
+Um único evento mouseover é enviado ao elemento de maior profundidade na árvore DOM, a partir do qual ocorre a fase bubble e o mesmo percorre subindo na hierarquia dos elementos  até que seja cancelado por um handler ou alcance a raíz da árvore.
+ +

De acordo com a profundidade da hierarquia, a quantidade de eventos mouseenter disparados pode se tornar muito grande e causar problemas de performance significativos. Nestes casos é melhor escutar por eventos mouseover.

+ +

Combinado ao comportamento do seu evento simétrico, mouseleave, o evento DOM mouseenter age de modo bastante similar à pseudo-classe CSS {{cssxref(':hover')}}.

+ +

Informações Gerais

+ +
+
Especificação
+
DOM L3
+
Interface
+
{{domxref('MouseEvent')}}
+
Sincronismo
+
Síncrono
+
Fase Bubble
+
Não
+
Cancelável
+
Não
+
Target
+
Element
+
Ação Padrão
+
Nenhuma
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}The event target (the topmost target in the DOM tree).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not?
view {{readonlyInline}}{{domxref("WindowProxy")}}{{domxref("document.defaultView")}} (window of the document)
detail {{readonlyInline}}long (float)0.
currentTarget {{readonlyInline}}{{domxref("EventTarget")}}The node that had the event listener attached.
relatedTarget {{readonlyInline}}{{domxref("EventTarget")}}For mouseover, mouseout, mouseenter and mouseleave events: the target of the complementary event (the mouseleave target in the case of a mouseenter event). null otherwise.
screenX {{readonlyInline}}longThe X coordinate of the mouse pointer in global (screen) coordinates.
screenY {{readonlyInline}}longThe Y coordinate of the mouse pointer in global (screen) coordinates.
clientX {{readonlyInline}}longThe X coordinate of the mouse pointer in local (DOM content) coordinates.
clientY {{readonlyInline}}longThe Y coordinate of the mouse pointer in local (DOM content) coordinates.
button {{readonlyInline}}unsigned shortThe button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2. For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left.
buttons {{readonlyInline}}unsigned shortThe buttons being pressed when the mouse event was fired: Left button=1, Right button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, 5th button (typically, "Browser Forward" button)=16. If two or more buttons are pressed, returns the logical sum of the values. E.g., if Left button and Right button are pressed, returns 3 (=1 | 2). More info.
mozPressure {{readonlyInline}}floatThe amount of pressure applied to a touch or tabdevice when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

Examples

+ +

The mouseover documentation has an example illustrating the difference between mouseover and mouseenter.

+ +

The following example illustrates how to use mouseover to simulate the principle of event delegation for the mouseenter event.

+ +
<ul id="test">
+  <li>
+    <ul class="enter-sensitive">
+      <li>item 1-1</li>
+      <li>item 1-2</li>
+    </ul>
+  </li>
+  <li>
+    <ul class="enter-sensitive">
+      <li>item 2-1</li>
+      <li>item 2-2</li>
+    </ul>
+  </li>
+</ul>
+
+<script>
+  var delegationSelector = ".enter-sensitive";
+
+  document.getElementById("test").addEventListener("mouseover", function( event ) {
+    var target = event.target,
+        related = event.relatedTarget,
+        match;
+
+    // search for a parent node matching the delegation selector
+    while ( target && target != document && !( match = matches( target, delegationSelector ) ) ) {
+        target = target.parentNode;
+    }
+
+    // exit if no matching node has been found
+    if ( !match ) { return; }
+
+    // loop through the parent of the related target to make sure that it's not a child of the target
+    while ( related && related != target && related != document ) {
+        related = related.parentNode;
+    }
+
+    // exit if this is the case
+    if ( related == target ) { return; }
+
+    // the "delegated mouseenter" handler can now be executed
+    // change the color of the text
+    target.style.color = "orange";
+    // reset the color after a small amount of time
+    setTimeout(function() {
+        target.style.color = "";
+    }, 500);
+
+
+  }, false);
+
+
+  // function used to check if a DOM element matches a given selector
+  // the following code can be replaced by this IE8 compatible function: https://gist.github.com/2851541
+  function matches( elem, selector ){
+    // the matchesSelector is prefixed in most (if not all) browsers
+    return elem.matchesSelector( selector );
+  };
+</script>
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support30[1]{{CompatVersionUnknown}}10[2]5.5{{CompatVersionUnknown}}
+ {{CompatNo}} 15.0
+ 17.0
7[3]
On disabled form elements{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("44.0")}}[4]{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
On disabled form elements{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Implemented in bug 236215.

+ +

[2] Implemented in {{bug("432698")}}.

+ +

[3] Safari 7 fires the event in many situations where it's not allowed to, making the whole event useless. See bug 470258 for the description of the bug (it existed in old Chrome versions as well). Safari 8 has correct behavior

+ +

[4] Implemented in {{bug("218093")}}.

+ +

See also

+ + diff --git a/files/pt-br/web/api/element/mouseover_event/index.html b/files/pt-br/web/api/element/mouseover_event/index.html new file mode 100644 index 0000000000..f4a5c56a9e --- /dev/null +++ b/files/pt-br/web/api/element/mouseover_event/index.html @@ -0,0 +1,262 @@ +--- +title: mouseover +slug: Web/API/Element/mouseover_event +translation_of: Web/API/Element/mouseover_event +--- +

O evento mouseover é acionado quando um dispositivo ponteiro é movido para o elemento que esteja escutando ou para um de seus filhos.

+ +

Informações Gerais

+ +
+
Especificação
+
DOM L3
+
Interface
+
{{domxref("MouseEvent")}}
+
Bubbles
+
Sim
+
Cancelable
+
Sim
+
Alvo
+
Element
+
Ação Padrão
+
None
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}O evento alvo(o mais alto alvo na arvore do DOM).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not
view {{readonlyInline}}{{domxref("WindowProxy")}}{{domxref("document.defaultView")}} (window of the document)
detail {{readonlyInline}}long (float)0.
currentTarget {{readonlyInline}}{{domxref("EventTarget")}}The node that had the event listener attached.
relatedTarget {{readonlyInline}}{{domxref("EventTarget")}}For mouseover, mouseout, mouseenter and mouseleave events: the target of the complementary event (the mouseleave target in the case of a mouseenter event). null otherwise.
screenX {{readonlyInline}}longThe X coordinate of the mouse pointer in global (screen) coordinates.
screenY {{readonlyInline}}longThe Y coordinate of the mouse pointer in global (screen) coordinates.
clientX {{readonlyInline}}longThe X coordinate of the mouse pointer in local (DOM content) coordinates.
clientY {{readonlyInline}}longThe Y coordinate of the mouse pointer in local (DOM content) coordinates.
button {{readonlyInline}}unsigned shortThis is always 0 as no button presses trigger this event (mouse movement does).
buttons {{readonlyInline}}unsigned shortThe buttons depressed when the mouse event was fired: Left button=1, Right button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, 5th button (typically, "Browser Forward" button)=16. If two or more buttons are depressed, returns the logical sum of the values. E.g., if Left button and Right button are depressed, returns 3 (=1 | 2). More info.
mozPressure {{readonlyInline}}floatThe amount of pressure applied to a touch or tabdevice when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

Example

+ +

The following example illustrates the difference between mouseover and mouseenter events.

+ +
<ul id="test">
+  <li>item 1</li>
+  <li>item 2</li>
+  <li>item 3</li>
+</ul>
+
+<script>
+  var test = document.getElementById("test");
+
+
+  // this handler will be executed only once when the cursor moves over the unordered list
+  test.addEventListener("mouseenter", function( event ) {
+    // highlight the mouseenter target
+    event.target.style.color = "purple";
+
+    // reset the color after a short delay
+    setTimeout(function() {
+      event.target.style.color = "";
+    }, 500);
+  }, false);
+
+
+  // this handler will be executed every time the cursor is moved over a different list item
+  test.addEventListener("mouseover", function( event ) {
+    // highlight the mouseover target
+    event.target.style.color = "orange";
+
+    // reset the color after a short delay
+    setTimeout(function() {
+      event.target.style.color = "";
+    }, 500);
+  }, false);
+</script>
+
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
On disabled form elements{{CompatVersionUnknown}}[1]{{CompatGeckoDesktop("44.0")}}[2]{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
On disabled form elements{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Only works for {{HTMLElement("textarea")}} elements and some {{HTMLElement("input")}} element types.

+ +

[2] Implemented in {{bug("218093")}}.

+ +

See also

+ + diff --git a/files/pt-br/web/api/element/name/index.html b/files/pt-br/web/api/element/name/index.html new file mode 100644 index 0000000000..d91ce0aa28 --- /dev/null +++ b/files/pt-br/web/api/element/name/index.html @@ -0,0 +1,79 @@ +--- +title: Element.name +slug: Web/API/Element/name +tags: + - API + - DOM + - Element + - NeedsBrowserCompatibility + - NeedsUpdate + - Property + - Reference + - Web +translation_of: Web/API +--- +

{{ APIRef("DOM") }}

+ +

Summary

+ +

name recebe ou ajusta uma propriedade name de um objeto do DOM; ele se aplica somente aos seguintes elementos: {{ HTMLelement("a") }}, {{ HTMLelement("applet") }}, {{ HTMLelement("button") }}, {{ HTMLelement("form") }}, {{ HTMLelement("frame") }}, {{ HTMLelement("iframe") }}, {{ HTMLelement("img") }}, {{ HTMLelement("input") }}, {{ HTMLelement("map") }}, {{ HTMLelement("meta") }}, {{ HTMLelement("object") }}, {{ HTMLelement("param") }}, {{ HTMLelement("select") }} e {{ HTMLelement("textarea") }}.

+ +
+

Nota: A propriedade name não existe para outros elementos; diferente de tagName e nodeName, ela não é uma propriedade das interfaces {{domxref("Node")}}, {{domxref("Element")}} ou {{domxref("HTMLElement")}}.

+
+ +

name pode ser usada no método {{ domxref("document.getElementsByName()") }}, em um form ou com uma coleção de elementos de formulário. Ela pode retornar um único elemento ou uma coleção quando usada com um formulário ou elementos de coleção.

+ +

Sintaxe

+ +
HTMLElement.name = string;
+var elName = HTMLElement.name;
+
+var fControl = HTMLFormElement.elementName;
+var controlCollection = HTMLFormElement.elements.elementName;
+
+ +

Exemplo

+ +
<form action="" name="formA">
+  <input type="text" value="foo">
+</form>
+
+<script type="text/javascript">
+
+  // Recebe uma referência ao primeiro elemento no formulário
+  var formElement = document.forms['formA'].elements[0];
+
+  // Fornece um name a ele
+  formElement.name = 'inputA';
+
+  // Exibe o valor do input
+  alert(document.forms['formA'].elements['inputA'].value);
+
+</script>
+
+ +

Notas

+ +

No Internet Explorer (IE), não é possível ajustar ou modificar a propriedade name de objetos do DOM criados com {{ domxref("document.createElement()") }}.

+ +

Especificação

+ +

Especificação W3C DOM 2 HTML:

+ + diff --git a/files/pt-br/web/api/element/outerhtml/index.html b/files/pt-br/web/api/element/outerhtml/index.html new file mode 100644 index 0000000000..1cdfa0826d --- /dev/null +++ b/files/pt-br/web/api/element/outerhtml/index.html @@ -0,0 +1,144 @@ +--- +title: Element.outerHTML +slug: Web/API/Element/outerHTML +translation_of: Web/API/Element/outerHTML +--- +

{{APIRef("DOM")}}

+ +

Sumário

+ +

O atributo outerHTML da estrutura DOM(Document object model) obtem  um fragmento serializado de código HTML descrevendo o elemento incluindo seus descendentes. É possível substituir o elemento em questão com nós obtidos através da análise de uma string.

+ +

Sintaxe

+ +

var conteudo = elemento.outerHTML;

+ +

Na atribuição, conteudo armazena o fragmento de código HTML que descreve o elemento e seus descentes.

+ +
elemento.outerHTML = conteudo;
+
+ +

Atribui a elemento  os nós obtidos pela análise da  string conteudo, tendo nó pai de elemento como nó de contexto o para o algoritmo de análise do fragmento de código HTML.

+ +

Exemplos

+ +

Obtendo o valor da propriedade outerHtml de um elemento :

+ +
// HTML:
+// <div id="d"><p>Conteúdo</p><p>Parágrafo</p></div>
+
+d = document.getElementById("d");
+dump(d.outerHTML);
+
+// A string '<div id="d"><p>Conteúdo</p><p>Parágrafo</p></div>'
+// é mostrada na janela do console.
+
+ +

Substituindo um nó atribuindo- lhe a propriedade outerHTML

+ +
// HTML:
+// <div id="container"><div id="d">Isto é uma div.</div></div>
+
+container = document.getElementById("container");
+d = document.getElementById("d");
+console.log(container.firstChild.nodeName); // mostra "DIV"
+
+d.outerHTML = "<p>Este parágrafo substitui a div original</p>";
+console.log(container.firstChild.nodeName); // mostra "P"
+
+// A div #d não faz mais parte da estrutura do documento,
+// O novo parágrafo a substituiu.
+
+ +

Notas

+ +

Se o elemento não tiver um nó pai, ou seja se o nó é a raiz do documento, tentar alterar sua propriedade outerHTML irá lançar um  DOMException com o código de erro NO_MODIFICATION_ALLOWED_ERR. Por exemplo:

+ +
document.documentElement.outerHTML = "test";  // Irá lançar uma DOMException
+
+ +

inclusive, quando o elemento for substituído na estrutura do documento, a variável a qual a propriedade outerHTML foi atribuída ainda irá conter uma referência para o elemento original.

+ +
var p = document.getElementsByTagName("p")[0];
+console.log(p.nodeName); // mostra: "P"
+p.outerHTML = "<div>Esta div substituiu o parágrafo.</div>";
+console.log(p.nodeName); // ainda contém "P";
+
+ +

Especificação

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#outerhtml', 'Element.outerHTML')}}{{ Spec2('DOM Parsing') }} 
+ +

Compatibilidade com os navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Suporte básico{{ CompatGeckoDesktop("11") }}0.24.071.3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
+

Suporte básico

+
{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("11") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/queryselector/index.html b/files/pt-br/web/api/element/queryselector/index.html new file mode 100644 index 0000000000..cbd41e09ff --- /dev/null +++ b/files/pt-br/web/api/element/queryselector/index.html @@ -0,0 +1,94 @@ +--- +title: Element.querySelector() +slug: Web/API/Element/querySelector +tags: + - API + - DOM + - Elemento + - Referencia +translation_of: Web/API/Element/querySelector +--- +
{{APIRef("DOM")}}
+ +

Retorna o primeiro elemento descendente do elemento em que a função foi invocada e que corresponde aos seletores especificado. 

+ +

Sintaxe

+ +
elemento = elementoBase.querySelector(seletores);
+
+ + + +

Exemplo

+ +

Neste exemplo é retornado o primeiro elemento style que, ou não tem nenhum atributo type, ou tem o atributo type igual a  text/css:

+ +
var el = document.body.querySelector("style[type='text/css'], style:not([type])");
+
+ +

Notas

+ +

Retorna null se nenhum elemento for encontrado; caso contrário retorna o primeiro elemento; 

+ +

Lança uma exceção SYNTAX_ERR se o grupo de seletores é inválido.

+ +

querySelector() foi introduzido em WebApps API.

+ +

O argumento de string do querySelector deve seguir a sintaxe CSS. Veja exemplos concretos em {{domxref("document.querySelector")}}

+ +

Compatibilidade de Browsers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BrowserSuporteNotas
Internet Explorer8(IE8) apenas selectores CSS 2.1
Firefox (Gecko)3.5 (1.9.1) 
Opera10 
Chrome1 
Safari (webkit)3.2 (525.3)webk.it/16587
+ +

Especificação

+ + + +

Veja Também

+ + diff --git a/files/pt-br/web/api/element/queryselectorall/index.html b/files/pt-br/web/api/element/queryselectorall/index.html new file mode 100644 index 0000000000..92f6e93506 --- /dev/null +++ b/files/pt-br/web/api/element/queryselectorall/index.html @@ -0,0 +1,118 @@ +--- +title: Element.querySelectorAll() +slug: Web/API/Element/querySelectorAll +translation_of: Web/API/Element/querySelectorAll +--- +
{{APIRef("DOM")}}
+ +

Sumário

+ +

Retorna uma  NodeList de todos os elementos descendentes do elemento que foi invocado que sejam compatíveis com o grupo de seletores CSS especificados.

+ +

Sintaxe

+ +
elementList = baseElement.querySelectorAll(selectors);
+
+ +

Onde

+ + + +

Exemplos

+ +

Este exemplo retorna uma lista de todos os elementos p no corpo do HTML:

+ +
var matches = document.body.querySelectorAll('p');
+
+ +

Este exemplo retorna uma lista de elementos p que estejam contidos em outro elemento, o qual é uma div que tem a classe 'highlighted':

+ +

 

+ +
var el = document.querySelector('#test');
+var matches = el.querySelectorAll('div.highlighted > p'); 
+ +

Este exemplo retorna uma lista de elementos iframe que contenham um atributo data 'src':

+ +
var matches = el.querySelectorAll('iframe[data-src]');
+
+ +

Notas

+ +

Joga uma excessão SYNTAX_ERR se o grupo especificado de seletores for inválido.

+ +

querySelectorAll() foi introduzida na WebApps API.

+ +

A string passada como argumento para querySelectorAll deve seguir a sintaxe do CSS. veja {{domxref("document.querySelector")}} para um exemplo concreto.

+ +

Lembre-se que o valor retornado é uma NodeList, então não é recomendado o uso de recursões for...in, nem de nenhum método de array. Se realmente houver a necessidade de usar métodos de uma array, então o NodeList deve ser convertido em uma array antes de ser usado.

+ +

Compatibilidade com Browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1{{CompatGeckoDesktop("1.9.1")}}8103.2 (525.3)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Especificações

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/element/removeattribute/index.html b/files/pt-br/web/api/element/removeattribute/index.html new file mode 100644 index 0000000000..c160dee957 --- /dev/null +++ b/files/pt-br/web/api/element/removeattribute/index.html @@ -0,0 +1,36 @@ +--- +title: Element.removeAttribute() +slug: Web/API/Element/removeAttribute +translation_of: Web/API/Element/removeAttribute +--- +

{{ APIRef("DOM") }}

+ +

removeAttribute remove um atributo de um elemento específico.

+ +

Sintaxe

+ +
element.removeAttribute(attrName);
+
+ + + +

Exemplo

+ +
// <div id="div1" align="left" width="200px">
+document.getElementById("div1").removeAttribute("align");
+// agora: <div id="div1" width="200px">
+
+ +

Observação

+ +

Você deve usar removeAttribute ao invés de atribuir null ao atributo usando setAttribute.

+ +

Tentar remover um atributo que não existe no elemento não fará que uma exceção seja lançada.

+ +

{{ DOMAttributeMethods() }}

+ +

Especificação

+ +

DOM Level 2 Core: removeAttribute (introduzido no DOM Level 1 Core)

diff --git a/files/pt-br/web/api/element/scrollintoview/index.html b/files/pt-br/web/api/element/scrollintoview/index.html new file mode 100644 index 0000000000..28714a4b1e --- /dev/null +++ b/files/pt-br/web/api/element/scrollintoview/index.html @@ -0,0 +1,89 @@ +--- +title: Element.scrollIntoView() +slug: Web/API/Element/scrollIntoView +tags: + - API + - CSSOM Views + - DOM + - Elemento + - Experimental + - Referencia + - Rolagem + - View + - metodo + - scrollIntoView +translation_of: Web/API/Element/scrollIntoView +--- +
{{ APIRef("DOM")}}{{SeeCompatTable}}
+ +

O método Element.scrollIntoView() move o elemento ao qual é aplicado para a área visível da janela do navegador.

+ +

Sintaxe

+ +
element.scrollIntoView(); // Equivalente a element.scrollIntoView(true)
+element.scrollIntoView(alignToTop); // Argumentos booleanos
+element.scrollIntoView(scrollIntoViewOptions); // argumento Objeto
+
+ +

Parâmetros

+ +
+
alignToTop {{optional_inline}}
+
É um valor {{jsxref("Boolean")}}: +
    +
  • Se true, a parte superior do elemento ficará alinhada com o topo da área visível do elemento-pai. Correponde a scrollIntoViewOptions: {block: "start", inline: "nearest"}. Este é o valor default.
  • +
  • Se false, a parte inferior do elemento ficará alinhada com o fundo da área visível do elemento-pai. Corresponde a scrollIntoViewOptions: {block: "end", inline: "nearest"}
  • +
+
+
scrollIntoViewOptions {{optional_inline}}
+
Um booleano ou um objeto com as seguintes opções:
+
+
{
+  behavior: "auto"  | "instant" | "smooth",
+  block:    "start" | "center" | "end" | "nearest",
+  inline:   "start" | "center" | "end" | "nearest"
+}
+
+
Caso seja um valor booleano, true corresponde a {block: "start"} e false a {block: "end"}.
+
+ +

Exemplo

+ +
var element = document.getElementById("box");
+
+element.scrollIntoView();
+element.scrollIntoView(false);
+element.scrollIntoView({block: "end"});
+element.scrollIntoView({block: "end", behavior: "smooth"});
+
+ +

Observações

+ +

O elemento poderá não ser movido completamento ao topo ou ao fundo dependendo de sua composição com outros elementos.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSSOM View", "#dom-element-scrollintoview", "Element.scrollIntoView()")}}{{Spec2("CSSOM View")}}Definição inicial
+ +

Compatibilidade com navegadores

+ +

{{Compat("api.Element.scrollIntoView")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/scrollleft/index.html b/files/pt-br/web/api/element/scrollleft/index.html new file mode 100644 index 0000000000..30df424288 --- /dev/null +++ b/files/pt-br/web/api/element/scrollleft/index.html @@ -0,0 +1,83 @@ +--- +title: Element.scrollLeft +slug: Web/API/Element/scrollLeft +translation_of: Web/API/Element/scrollLeft +--- +

{{ APIRef("DOM") }}

+ +

A propriedade Element.scrollLeft obtem, ou define o número de pixels do contéudo de um elemento que é rolado para a esquerda.

+ +

Note que se os {{cssxref("direction")}} do elemento do elemento é rtl (direita-para-esquerda) então scrollLeft é 0 quando a barra de rolagem está na posição mais à direita (o início do conteúdo rolado) e então, fica cada vez mais negativa à medida que se desloca em direção ao fim do conteúdo.

+ +

Sintaxe

+ +
// Obtem o número de pixels rolado
+var sLeft = element.scrollLeft;
+
+ +

sLeft é um inteiro representando o número de pixels do elemento que foi movido para a esquerda.

+ +
// Define o número de pixels rolado
+element.scrollLeft = 10;
+
+ +

scrollLeft pode ser definido para qualquer valor inteiro, entretanto:

+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+    <meta charset="utf-8">
+    <style>
+        #container {
+            border: 1px solid #ccc; height: 100px; overflow: scroll; width: 100px;
+        }
+        #content {
+            background-color: #ccc; width: 250px;
+        }
+    </style>
+    <script>
+        document.addEventListener('DOMContentLoaded', function () {
+            var button = document.getElementById('slide');
+            button.onclick = function () {
+                document.getElementById('container').scrollLeft += 20;
+            };
+        }, false);
+    </script>
+</head>
+<body>
+    <div id="container">
+        <div id="content">Lorem ipsum dolor sit amet.</div>
+    </div>
+    <button id="slide" type="button">Slide</button>
+</body>
+</html>
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('CSSOM View', '#dom-element-scrollleft', 'scrollLeft')}}{{Spec2("CSSOM View")}} 
+ +

Referências

+ +

{{Compat("api.Element.scrollLeft")}}

diff --git a/files/pt-br/web/api/element/scrolltop/index.html b/files/pt-br/web/api/element/scrolltop/index.html new file mode 100644 index 0000000000..f8f7dc4cd6 --- /dev/null +++ b/files/pt-br/web/api/element/scrolltop/index.html @@ -0,0 +1,69 @@ +--- +title: Element.scrollTop +slug: Web/API/Element/scrollTop +translation_of: Web/API/Element/scrollTop +--- +

{{ APIRef("DOM") }}

+ +

A propriedade Element.scrollTop obtém ou define o número de pixels quando o conteúdo de um elemento é rolado para baixo. O ScrollTop de um elemento é uma medida da distância do topo de um elemento para o seu conteúdo superior visível. Quando um conteúdo de elemento não gera uma barra de rolagem vertical, então o seu valor será padronizado scrollTop = 0.

+ +

Sintaxe

+ +
// Obtém o número de pixels rolados
+var intElemScrollTop = element.scrollTop;
+
+ +

Depois de executar este código, intElemScrollTop é um número inteiro correspondente ao número de pixels que o {{domxref ("elemento")}}  conteúdo foi rolado para cima.

+ +
// Define o número de pixels rolados
+element.scrollTop = intValue;
+
+ +

scrollTop pode ser definido como qualquer valor inteiro, com algumas ressalvas:

+ + + +

Exemplo

+ +
+
+

padding-top

+ +

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

+ +

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

+ +

padding-bottom

+
+Left Top Right Bottom margin-top margin-bottom border-top border-bottom
+ +

Image:scrollTop.png

+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-element-scrolltop', 'scrollTop')}}{{Spec2("CSSOM View")}} 
+ +

Referências

+ + diff --git a/files/pt-br/web/api/element/scrollwidth/index.html b/files/pt-br/web/api/element/scrollwidth/index.html new file mode 100644 index 0000000000..9f0c3009b5 --- /dev/null +++ b/files/pt-br/web/api/element/scrollwidth/index.html @@ -0,0 +1,116 @@ +--- +title: Element.scrollWidth +slug: Web/API/Element/scrollWidth +translation_of: Web/API/Element/scrollWidth +--- +
{{ APIRef("DOM") }}
+ +

A propriedade de somente leitura Element.scrollWidth retorna a largura em pixels do conteúdo de um elemento ou a largura do elemento em si, o que for maior. Se o elemento for mais amplo do que a área de conteúdo (por exemplo, se houver barras de rolagem para percorrer o conteúdo), o scrollWidth é maior do que o clientWidth.

+ +
+

Esta propriedade irá arredondar o valor para um número inteiro. Se você precisar de um valor fracionário, use {{ domxref("element.getBoundingClientRect()") }}.

+
+ +

Syntaxe

+ +
var xScrollWidth = element.scrollWidth;
+ +

xScrollWidth é a largura do conteúdo do elemento em pixels.

+ +

Examplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+    <title>Example</title>
+    <style>
+        div {
+            overflow: hidden;
+            white-space: nowrap;
+            text-overflow: ellipsis;
+        }
+
+        #aDiv {
+            width: 100px;
+        }
+
+        button {
+            margin-bottom: 2em;
+        }
+    </style>
+</head>
+
+<body>
+    <div id="aDiv">
+        FooBar-FooBar-FooBar-FooBar
+    </div>
+    <button id="aButton">
+        Check for overflow
+    </button>
+
+    <div id="anotherDiv">
+        FooBar-FooBar-FooBar-FooBar
+    </div>
+    <button id="anotherButton">
+        Check for overflow
+    </button>
+</body>
+<script>
+    var buttonOne = document.getElementById('aButton'),
+    buttonTwo = document.getElementById('anotherButton'),
+    divOne = document.getElementById('aDiv'),
+    divTwo = document.getElementById('anotherDiv');
+
+    //check to determine if an overflow is happening
+    function isOverflowing(element) {
+        return (element.scrollWidth > element.offsetWidth);
+    }
+
+    function alertOverflow(element) {
+        if (isOverflowing(element)) {
+            alert('Contents are overflowing the container.');
+        } else {
+            alert('No overflows!');
+        }
+    }
+
+    buttonOne.addEventListener('click', function() {
+        alertOverflow(divOne);
+    });
+
+    buttonTwo.addEventListener('click', function() {
+        alertOverflow(divTwo);
+    });
+</script>
+</html>
+
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSSOM View", "#dom-element-scrollwidth", "Element.scrollWidth")}}{{Spec2("CSSOM View")}}Definição inicial
+ +

Referências

+ +

{{Compat("api.Element.scrollWidth")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/setattribute/index.html b/files/pt-br/web/api/element/setattribute/index.html new file mode 100644 index 0000000000..0a3642be64 --- /dev/null +++ b/files/pt-br/web/api/element/setattribute/index.html @@ -0,0 +1,58 @@ +--- +title: Element.setAttribute() +slug: Web/API/Element/setAttribute +tags: + - Elemento + - IPA + - MOD + - Referencia + - metodo +translation_of: Web/API/Element/setAttribute +--- +

{{APIRef("DOM")}}

+ +

Adiciona um novo atributo ou modifica o valor de um atributo existente num elemento específico.

+ +

Sintaxe

+ +
element.setAttribute(name, value);
+
+ + + +

Exemplo

+ +

No seguinte exemplo, setAttribute() é usado para definir o atributo {{htmlattrxref("disabled")}} em {{htmlelement("button")}}, desabilitado-o.

+ +
<button>Hello World</button>
+ +
var b = document.querySelector("button");
+
+b.setAttribute("disabled", "disabled");
+
+ +

{{ EmbedLiveSample('Example', '300', '50', '', 'Web/API/Element/setAttribute') }}

+ +

Notas

+ +

Quando chamado em um documento HTML, setAttribute lower-cases its attribute name argument.

+ +

Se um atributo especificado já existe, então o valor do atributo é mudado para o valor passado para a função. Se não existe, então o atributo é criado.

+ +

Apesar de getAttribute() retornar null para atributos ausentes, você precisa usar removeAttribute() ao invés de elt.setAttribute(attr, null) para remover o atributo. Este último forçará o valor null para a string "null", o que não é provavelmente o que você quer.

+ +

Usar setAttribute() para modificar certos atributos, mais notavelmente valor em XUL, funciona inconsistentemente, como atributos específicos de valor padrão. Para acessar ou modificar os valores atuais, você deve usar as propriedades. Por exemplo, use elt.value ao invés de elt.setAttribute('value', val).

+ +

Para definir um atributo que não leva valor, assim como o atributo autoplay de um elemento {{HTMLElement("audio")}}, use null ou um valor vazio. Por exemplo: elt.setAttribute('autoplay', '')

+ +
{{DOMAttributeMethods}}
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/element/setattributens/index.html b/files/pt-br/web/api/element/setattributens/index.html new file mode 100644 index 0000000000..d4837965a7 --- /dev/null +++ b/files/pt-br/web/api/element/setattributens/index.html @@ -0,0 +1,33 @@ +--- +title: Element.setAttributeNS() +slug: Web/API/Element/setAttributeNS +translation_of: Web/API/Element/setAttributeNS +--- +

{{ APIRef("DOM") }}

+ +

setAttributeNS adiciona um novo atributo ou modifica o valor de um atributo com um namespace e um nome.

+ +

Syntax

+ +
element.setAttributeNS(namespace,name,value)
+
+ + + +

Exemplo

+ +
var d = document.getElementById("d1");
+d.setAttributeNS("http://www.mozilla.org/ns/specialspace", "align", "center");
+
+ +

Notas

+ +

{{ DOMAttributeMethods() }}

+ +

Especificação

+ +

DOM Level 2 Core: setAttributeNS

diff --git a/files/pt-br/web/api/element/tagname/index.html b/files/pt-br/web/api/element/tagname/index.html new file mode 100644 index 0000000000..c0345f4763 --- /dev/null +++ b/files/pt-br/web/api/element/tagname/index.html @@ -0,0 +1,119 @@ +--- +title: Element.tagName +slug: Web/API/Element/tagName +tags: + - API + - DOM + - Gecko + - PrecisaCompatibilidadeBrowser + - Propriedade + - Referência DOM +translation_of: Web/API/Element/tagName +--- +

{{ApiRef("DOM")}}

+ +

Retorna o nome do elemento.

+ +

Sintaxe

+ +
nomeDoElemento = element.tagName;
+
+ + + +

Notas

+ +

Em XML (e linguagens baseadas, como XHTML), tagName conserva o case  (caixa alta/baixa) da tag. Nos elementos HTML da árvore do DOM marcados como documentos HTML, tagName retorna o nome do elemento em uppercase (caixa alta). O valor de tagName é o mesmo que o nodeName

+ +

Exemplo

+ +

conteúdo HTML

+ +
<span id="exemplo">Descrição do exemplo...</span>
+
+ +

conteúdo JavaScript

+ +
var span = document.getElementById("exemplo");
+console.log(span.tagName);
+
+ +

Em XHTML (ou qualquer outro formato XML), "span" será a saída. Em HTML, "SPAN" será a saída.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("DOM3 Core", "core.html#ID-104682815", "Element.tagName")}}{{Spec2("DOM3 Core")}}No change
{{SpecName("DOM2 Core", "core.html#ID-104682815", "Element.tagName")}}{{Spec2("DOM2 Core")}}Initial definition
+ +

Compatibilidade de browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/element/touchstart_event/index.html b/files/pt-br/web/api/element/touchstart_event/index.html new file mode 100644 index 0000000000..ae2649f49c --- /dev/null +++ b/files/pt-br/web/api/element/touchstart_event/index.html @@ -0,0 +1,174 @@ +--- +title: touchstart +slug: Web/API/Element/touchstart_event +tags: + - Event + - Evento Toque + - Toque + - TouchEvent +translation_of: Web/API/Element/touchstart_event +--- +

O evento touchstart é acionado quando o ponteiro de toque(dedo ou caneta) é aplicado sobre à superfície de toque da tela(toque sobre a tela no elemento alvo).

+ +

Info Geral

+ +
+
Especificações
+
Touch Events
+
Interface
+
{{domxref("TouchEvent")}}
+
Bubbles
+
Sim
+
Cancelável
+
Sim
+
Alvo
+
Documento, Elemento
+
Ação Padrão
+
undefined (indefinido)
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not.
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not.
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
touches {{readonlyInline}}TouchListA list of Touches for every point of contact currently touching the surface.
targetTouches {{readonlyInline}}TouchListA list of Touches for every point of contact that is touching the surface and started on the element that is the target of the current event.
changedTouches {{readonlyInline}}TouchListA list of Touches for every point of contact which contributed to the event.
+ For the touchstart event this must be a list of the touch points that just became active with the current event. For the touchmove event this must be a list of the touch points that have moved since the last event. For the touchend and touchcancel events this must be a list of the touch points that have just been removed from the surface.
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

Exemplos

+ +

Os códigos de exemplos para este evento estão disponíveis nesta página dedicada: Touch events.

+ +

Compatibilidade de Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome("22.0")}}{{CompatGeckoDesktop("18.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidAndroid WebviewChrome para AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6.0")}}{{CompatVersionUnknown}}11{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Eventos Relacionados

+ + diff --git a/files/pt-br/web/api/encoding_api/index.html b/files/pt-br/web/api/encoding_api/index.html new file mode 100644 index 0000000000..543a842cdc --- /dev/null +++ b/files/pt-br/web/api/encoding_api/index.html @@ -0,0 +1,55 @@ +--- +title: Encoding API +slug: Web/API/Encoding_API +translation_of: Web/API/Encoding_API +--- +

{{DefaultAPISidebar("Encoding API")}}{{SeeCompatTable}}

+ +

Encoding API providência uma mecânismo para tratar textos em vários tipos de {{Glossary("character encoding", "encode de caracteres")}}, incluindo encodes legados non-{{Glossary("UTF-8")}}

+ +

A API provém de quatro interfaces: {{domxref("TextDecoder")}}, {{domxref("TextEncoder")}}, {{domxref("TextDecoderStream")}} e {{domxref("TextEncoderStream")}}.

+ +

Interfaces

+ +
+ +
+ +

Tutoriais & ferramentas

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Encoding")}}{{Spec2("Encoding")}}Definição inicial.
+ +

Compatibilidade dos navegadores

+ + + +

TextDecoder

+ +

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

+ +

TextEncoder

+ +

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

diff --git a/files/pt-br/web/api/event/comparativo_entre_event_targets/index.html b/files/pt-br/web/api/event/comparativo_entre_event_targets/index.html new file mode 100644 index 0000000000..e9b2004719 --- /dev/null +++ b/files/pt-br/web/api/event/comparativo_entre_event_targets/index.html @@ -0,0 +1,167 @@ +--- +title: Comparativo entre Event Targets +slug: Web/API/Event/Comparativo_entre_Event_Targets +tags: + - DOM + - Event + - event target +translation_of: Web/API/Event/Comparison_of_Event_Targets +--- +
{{ ApiRef() }}
+ +

Event targets

+ +

É facil se confundir sobre o tipo de alvo (target) que deseja-se examinar ao criar um manipulador de eventos (event handler). Este artigo se propõe a esclarecer o uso da propriedade target.

+ +

Há 5 tipos de targets a se considerar:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadeDefinido emObjetivo
event.targetDOM Event Interface +

O elemento do DOM à esquerda da chamada que disparou este evento, por exemplo:

+ +
+element.dispatchEvent(event)
+
+
event.currentTargetDOM Event InterfaceO EventTarget do qual o EventListeners está sendo atualmente processado. Logo que a captura e a subida do evento ocorre a mudança deste valor.
event.relatedTargetDOM MouseEvent InterfaceIdentifica um alvo secundário para o evento.
event.explicitOriginalTarget{{ Source("/dom/public/idl/events/nsIDOMNSEvent.idl", "nsIDOMNSEvent.idl") }}{{ Non-standard_inline() }} Se o evento foi redirecionado por alguma outra razão senão o cruzamento de uma fronteira anônima, este evento será colocado no alvo antes que o redirecionamento ocorra. por exemplo, eventos do mouse são redirecionados à seus elementos pais quando acontecem sobre nós de texto ({{ Bug("185889") }}), e neste caso .target mostrará o nó pai e .explicitOriginalTarget mostrará o nó texto. Diferente de .originalTarget, .explicitOriginalTarget nunca irá conter um conteúdo anônimo.
event.originalTarget{{ Source("/dom/public/idl/events/nsIDOMNSEvent.idl", "nsIDOMNSEvent.idl") }}{{ Non-standard_inline() }} O alvo original do evento, antes de qualquer redirecionamento. Veja Anonymous Content#Event_Flow_and_Targeting para mais detalhes.
+ +

Uso de explicitOriginalTarget e originalTarget

+ +

TODO: Disponível apensas em navegadores Mozilla-based?

+ +

TODO: Adequado apenas para desenvolvedores de extensões?

+ +

Exemplos

+ +
<!DOCTYPE html>
+<html>
+<head>
+    <meta charset="utf-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <title>Comparison of Event Targets</title>
+    <style>
+        table {
+            border-collapse: collapse;
+            height: 150px;
+            width: 100%;
+        }
+        td {
+            border: 1px solid #ccc;
+            font-weight: bold;
+            padding: 5px;
+            min-height: 30px;
+        }
+        .standard {
+            background-color: #99ff99;
+        }
+        .non-standard {
+            background-color: #902D37;
+        }
+    </style>
+</head>
+<body>
+    <table>
+    <thead>
+        <tr>
+            <td class="standard">Original target dispatching the event <small>event.target</small></td>
+            <td class="standard">Target who's event listener is being processed <small>event.currentTarget</small></td>
+            <td class="standard">Identify other element (if any) involved in the event <small>event.relatedTarget</small></td>
+            <td class="non-standard">If there was a retargetting of the event for some reason <small> event.explicitOriginalTarget</small> contains the target before retargetting (never contains anonymous targets)</td>
+            <td class="non-standard">If there was a retargetting of the event for some reason <small> event.originalTarget</small> contains the target before retargetting (may contain anonymous targets)</td>
+        </tr>
+    </thead>
+    <tr>
+        <td id="target"></td>
+        <td id="currentTarget"></td>
+        <td id="relatedTarget"></td>
+        <td id="explicitOriginalTarget"></td>
+        <td id="originalTarget"></td>
+    </tr>
+</table>
+<p>Clicking on the text will show the difference between explicitOriginalTarget, originalTarget and target</p>
+<script>
+    function handleClicks(e) {
+        document.getElementById('target').innerHTML = e.target;
+        document.getElementById('currentTarget').innerHTML = e.currentTarget;
+        document.getElementById('relatedTarget').innerHTML = e.relatedTarget;
+        document.getElementById('explicitOriginalTarget').innerHTML = e.explicitOriginalTarget;
+        document.getElementById('originalTarget').innerHTML = e.originalTarget;
+    }
+
+    function handleMouseover(e) {
+        document.getElementById('target').innerHTML = e.target;
+        document.getElementById('relatedTarget').innerHTML = e.relatedTarget;
+    }
+
+    document.addEventListener('click', handleClicks, false);
+    document.addEventListener('mouseover', handleMouseover, false);
+</script>
+</body>
+</html>
+ +

Uso de target e relatedTarget

+ +

A propriedade relatedTarget do evento de mouseover mantém o nó de onde o mouse estava sobre anteriormente. Para o evento de mouseout, mantém o nó para onde o mouse se moveu.

+ + + + + + + + + + + + + + + + + + + +
Tipo de Eventoevent.targetevent.relatedTarget
mouseoverO EventTarget do qual o dispositivo apontador entrou.O EventTarget do qual o dispositivo apontador saiu.
mouseoutO EventTarget do qual o dispositivo apontador saiu.O EventTarget do qual o dispositivo apontador entrou.
+ +

TODO: Necessário descrição complemento sobre eventos de dragenter e dragexit.

+ +

Exemplo

+ +
<hbox id="outer">
+  <hbox id="inner"
+        onmouseover="dump('mouseover ' + event.relatedTarget.id + ' > ' + event.target.id + '\n');"
+        onmouseout="dump('mouseout  ' + event.target.id + ' > ' + event.relatedTarget.id + '\n');"
+        style="margin: 100px; border: 10px solid black; width: 100px; height: 100px;" />
+</hbox>
+
diff --git a/files/pt-br/web/api/event/currenttarget/index.html b/files/pt-br/web/api/event/currenttarget/index.html new file mode 100644 index 0000000000..e74a58fb61 --- /dev/null +++ b/files/pt-br/web/api/event/currenttarget/index.html @@ -0,0 +1,129 @@ +--- +title: Event.currentTarget +slug: Web/API/Event/currentTarget +tags: + - API + - CompatibilidadeEntreNavegadores + - DOM + - Gecko + - Propriedade +translation_of: Web/API/Event/currentTarget +--- +

{{APIRef("DOM")}}

+ +

Identifica o alvo atual para o evento quando o event percorre o DOM. O currentTarget sempre se refere ao elemento associado ao event handler, ao invés do event.target que identifica o elemento ao qual o evento ocorreu.

+ +

Exemplo

+ +

event.currentTarget é bom para ser usado quando nós queremos associar o mesmo event handler para vários elementos.

+ +
function hide(e){
+  e.currentTarget.style.visibility = "hidden";
+  console.log(e.currentTarget);
+  // Quando essa função é usada como um event
+  // handler: this === e.currentTarget
+}
+
+var ps = document.getElementsByTagName('p');
+
+for(var i = 0; i < ps.length; i++){
+  // console: print the clicked <p> element
+  ps[i].addEventListener('click', hide, false);
+}
+// console: print <body>
+document.body.addEventListener('click', hide, false);
+
+// Clique e faça os parágrafos desaparecerem
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("DOM WHATWG", "#dom-event-currenttarget", "Event.currentTarget")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM4", "#dom-event-currenttarget", "Event.currentTarget")}}{{Spec2("DOM4")}} 
{{SpecName("DOM3 Events", "#dfn-current-event-target", "current event target")}}{{Spec2("DOM3 Events")}} 
{{SpecName("DOM2 Events", "#Events-Event-currentTarget", "Event.currentTarget")}}{{Spec2("DOM2 Events")}}Definição incial
+ +

Compatibilidade  dos navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Supote básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}10.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supote básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}10.0
+
+ +

[1] Do Internet Explorer 6 até o 8, o modelo do event é diferente. Event listeners estão acoplados com o {{domxref("EventTarget.attachEvent")}} método não padronizado. Neste modelo não há um equivalente para event.currentTarget e this é um objeto global. Uma solução para simular o event.currentTarget é envolver seu handler em uma função e chamando-a usando o Function.prototype.call com o elemento sendo o primeiro argumento. Desta forma, this será o valor esperado.

+ +

Veja também

+ +

Comparativo dos Event Targets

diff --git a/files/pt-br/web/api/event/defaultprevented/index.html b/files/pt-br/web/api/event/defaultprevented/index.html new file mode 100644 index 0000000000..d0407443c7 --- /dev/null +++ b/files/pt-br/web/api/event/defaultprevented/index.html @@ -0,0 +1,79 @@ +--- +title: Event.defaultPrevented +slug: Web/API/Event/defaultPrevented +translation_of: Web/API/Event/defaultPrevented +--- +

{{ ApiRef("DOM") }}

+ +

Resumo

+ +

Retorna um booleano que indica se ou não {{ domxref("event.preventDefault()") }} foi chamado no evento.

+ +
Nota: Você deve usar isso em vez de a não-padrão, método desatualizado getPreventDefault()  (ver {{ bug(691151) }}).
+ +

Sintaxe

+ +
bool = event.defaultPrevented 
+ +

Exemplo

+ +
 if (e.defaultPrevented) {
+   /* o padrão foi impedido */
+ }
+
+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(18) }}{{ CompatGeckoDesktop("6.0") }}{{ CompatIE(9.0) }}{{ CompatOpera(11.0) }}{{ CompatSafari("5.0") }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("6.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatSafari(5.0) }}
+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/event/event/index.html b/files/pt-br/web/api/event/event/index.html new file mode 100644 index 0000000000..40bc836e77 --- /dev/null +++ b/files/pt-br/web/api/event/event/index.html @@ -0,0 +1,69 @@ +--- +title: Event() +slug: Web/API/Event/Event +translation_of: Web/API/Event/Event +--- +

{{APIRef("DOM")}}

+ +

O Event() cria uma nova {{domxref("Event")}}.

+ +

Sintaxe

+ +
 event = new Event(typeArg, eventInit);
+ +

Valores

+ +
+
typeArg
+
É uma {{domxref("DOMString")}} representa o nome do evento.
+
eventInit{{optional_inline}}
+
+ +
+
É um dicionário EventInit, tendo os seguintes campos: + +
    +
  • "bubbles", opcional e false por default, do tipo {{jsxref("Boolean")}}, indica se o evento é bubbles ou não.
  • +
  • "cancelable", opcional e false por default, do tipo {{jsxref("Boolean")}}, indica se o evento pode ser cancelado ou não.
  • +
+
+
+ +

Exemplo

+ +
// criar um evento com bubbles true e que não pode ser cancelado
+
+var ev = new Event("look", {"bubbles":true, "cancelable":false});
+document.dispatchEvent(ev);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG','#interface-event','Event()')}}{{Spec2('DOM WHATWG')}}Definição inicial.
+ +

Compatibilidade de browser

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/event/index.html b/files/pt-br/web/api/event/index.html new file mode 100644 index 0000000000..7fe5549c48 --- /dev/null +++ b/files/pt-br/web/api/event/index.html @@ -0,0 +1,146 @@ +--- +title: Event +slug: Web/API/Event +tags: + - API + - DOM + - Event + - Interface + - NeedsTranslation + - Reference + - Référence(2) + - TopicStub +translation_of: Web/API/Event +--- +

{{APIRef("DOM")}}

+ +

A interface de eventos representa qualquer evento de DOM. Ele contém propriedades comuns e métodos para qualquer evento.

+ +

Um monte de outras interfaces herdam, diretamente ou não, a partir desta interface base:

+ +
+ +
+ +

Construtor

+ +
+
{{domxref("Event.Event", "Event()")}}
+
Cria um objeto Event.
+
+ +

Propriedades

+ +

Esta interface não herda nenhuma propriedade.

+ +
+
{{domxref("Event.bubbles")}} {{readonlyinline}}
+
Um booleano que indica se o evento surge em bolha pela DOM ou não.
+
{{domxref("Event.cancelable")}} {{readonlyinline}}
+
Um booleano que indica se o evento é cancelado.
+
{{domxref("Event.currentTarget")}} {{readonlyinline}}
+
Uma referencia para o alvo registrado atualmente para o evento.
+
{{domxref("Event.defaultPrevented")}} {{readonlyinline}}
+
Indica se ou não {{domxref("event.preventDefault()")}} foi chamado no evento..
+
{{domxref("Event.eventPhase")}} {{readonlyinline}}
+
Indica que fase do fluxo de eventos está a ser processada.
+
{{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
O objetivo original explícito do evento (Mozilla-specific).
+
{{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
O objectivo inicial do evento, antes de qualquer redirecionamento (Mozilla-specific).
+
{{domxref("Event.target")}} {{readonlyinline}}
+
A referência ao objectivo para o qual o evento foi originalmente despachado.
+
{{domxref("Event.timeStamp")}} {{readonlyinline}}
+
O tempo em que o evento foi criado.
+
{{domxref("Event.type")}} {{readonlyinline}}
+
O nome do evento (case-insensitive).
+
{{domxref("Event.isTrusted")}} {{readonlyinline}}
+
Indica se ou não o evento foi iniciado pelo navegador (depois de um clique do usuário, por exemplo) ou por um script (usando um método de criação de evento, como event.initEvent)
+
+ +

Metodos

+ +

Esta interface não herda nenhum método.

+ +
+
{{domxref("Event.initEvent()")}} {{deprecated_inline}}
+
Inicializa o valor de um evento criado. Se o evento já está sendo despachado, este método não faz nada.
+
{{domxref("Event.preventBubble()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
Impede o evento de borbulhar. Obsoleto, use {{domxref ("event.stopPropagation")}} em vez disso.
+
{{domxref("Event.preventCapture()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
Obsoleto, use {{domxref("event.stopPropagation")}} ao invés.
+
{{domxref("Event.preventDefault()")}}
+
Cancela o evento (caso seja cancelável).
+
{{domxref("Event.stopImmediatePropagation()")}}
+
Para este evento em particular, nenhum outro ouvinte será chamado. Ou aqueles ligados no mesmo elemento, nem aqueles associados em elementos que serão percorridos mais tarde
+ (em fase de captura, por exemplo)​.
+
{{domxref("Event.stopPropagation()")}}
+
Para a propagação de eventos mais adiante no DOM.
+
{{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}
+
Obsoleto, use {{domxref("Event.defaultPrevented")}} ao invés.
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/event/initevent/index.html b/files/pt-br/web/api/event/initevent/index.html new file mode 100644 index 0000000000..6a26dcb3e8 --- /dev/null +++ b/files/pt-br/web/api/event/initevent/index.html @@ -0,0 +1,137 @@ +--- +title: Event.initEvent() +slug: Web/API/Event/initEvent +tags: + - API + - DOM + - Descontinuado + - Evento + - Referencia + - metodo +translation_of: Web/API/Event/initEvent +--- +
{{ ApiRef("DOM") }}{{deprecated_header}}
+ +

O método Event.initEvent() é usado para inicializar o valor de um {{ domxref("event") }} criado usando {{ domxref("Document.createEvent()") }}.

+ +

Eventos inicializados desta maneira precisam ter sido criados com o método {{ domxref("Document.createEvent()") }}. Este método precisar ser chamado para definir o evento antes de ser despachado, usando {{ domxref("EventTarget.dispatchEvent()") }}. Uma vez despachado, não faz mais nada.

+ +
+

Não use esse método mais, pois está depreciado.

+ +

Ao invés, use construtores de eventos específicos, como {{domxref("Event.Event", "Event()")}}. A página sobre Criando e disparando eventos detalha mais informações sobre o uso desses eventos.

+
+ +

Syntax

+ +
event.initEvent(tipo, bubbles, cancelable);
+ +
+
tipo
+
É um {{domxref("DOMString")}} definido o tipo do evento.
+
bolhas
+
É um {{jsxref("Boolean")}} decidindo se o evento precisa ser enviado para cima, na cadeia de eventos ou não. Uma vez definido, a propriedade read-only {{ domxref("Event.bubbles") }} irá informar o seu valor.
+
cancelable
+
É um {{jsxref("Boolean")}} definindo se o evento pode ser cancelado. Uma vez definido, a propriedade read-only {{ domxref("Event.cancelable") }} will irá informar o seu valor.
+
+ +

Exemplo

+ +
// Cria o evento.
+var event = document.createEvent('Event');
+
+// Cria um evento de clique que borbulha e
+// não pode ser cancelado
+event.initEvent('click', true, false);
+
+// Escuta este evento.
+elem.addEventListener('click', function (e) {
+  // e.target matches elem
+}, false);
+
+elem.dispatchEvent(event);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('DOM WHATWG', '#dom-event-initevent','Event.initEvent()')}}{{Spec2("DOM WHATWG")}}From {{SpecName('DOM2 Events')}}, deprecated it, superseded by event constructors.
{{SpecName('DOM2 Events','##Events-Event-initEvent','Event.initEvent()')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

Compatibilidade com navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown()}} [1]{{CompatVersionUnknown()}}{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }} [1]{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] Antes do Firefox 17, uma chamada a este método depois de despachar o evento gerava uma exceção ao invés de não fazer nada.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/event/istrusted/index.html b/files/pt-br/web/api/event/istrusted/index.html new file mode 100644 index 0000000000..711fcae44b --- /dev/null +++ b/files/pt-br/web/api/event/istrusted/index.html @@ -0,0 +1,57 @@ +--- +title: Event.isTrusted +slug: Web/API/Event/isTrusted +translation_of: Web/API/Event/isTrusted +--- +
{{APIRef("DOM")}}
+A propriedade  isTrusted da interface {{domxref("Event")}}, exclusiva para leitura, é uma booleana ({{domxref("Boolean")}}) de valor verdadeiro (true) se tal evento é disparado pela ação do usuário. Retorna falso (false) caso o acionamento do evento seja ocasionado pelo método {{domxref("EventTarget.dispatchEvent()")}} ou tenha sido criado ou modificado por um script.
+ +
 
+ +

Sintaxe

+ +
var eventIsTrusted = event.isTrusted;
+
+ +

Valor

+ +

{{domxref("Boolean")}}

+ +

Exemplo

+ +
if (e.isTrusted) {
+  /* The event is trusted */
+} else {
+  /* The event is not trusted */
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecifiaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-event-istrusted', 'Event.isTrusted')}}{{ Spec2('DOM WHATWG') }} 
{{SpecName('DOM3 Events', '#trusted-events', 'Trusted events')}}{{Spec2('DOM3 Events')}}Amplia requisito para confiabilidade de um evento, embora isto não defina por si só a propriedade isTrusted.
+ + + +
+ + +

{{Compat("api.Event.isTrusted")}}

+
diff --git a/files/pt-br/web/api/event/preventdefault/index.html b/files/pt-br/web/api/event/preventdefault/index.html new file mode 100644 index 0000000000..cc39be846e --- /dev/null +++ b/files/pt-br/web/api/event/preventdefault/index.html @@ -0,0 +1,113 @@ +--- +title: Event.preventDefault() +slug: Web/API/Event/preventDefault +translation_of: Web/API/Event/preventDefault +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

Resumo

+ +

Cancela o evento se for cancelável, sem parar a propagação do mesmo.

+ +

Sintaxe

+ +
event.preventDefault();
+ +

Exemplo

+ +

Alternar é a ação padrão de clicar em uma caixa de seleção. Este exemplo demonstra como impedir que isso aconteça:

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>preventDefault example</title>
+
+<script>
+function stopDefAction(evt) {
+    evt.preventDefault();
+}
+
+document.getElementById('my-checkbox').addEventListener(
+    'click', stopDefAction, false
+);
+</script>
+</head>
+
+<body>
+
+<p>Please click on the checkbox control.</p>
+
+<form>
+    <input type="checkbox" id="my-checkbox" />
+    <label for="my-checkbox">Checkbox</label>
+</form>
+
+</body>
+</html>
+ +

Você pode ver o preventDefault em ação aqui.

+ +

O exemplo a seguir demonstra como um input com texto inválido pode ser parado ao chegar ao campo de entrada com o preventDefault().

+ +
+
<!DOCTYPE html>
+<html>
+<head>
+<title>preventDefault example</title>
+
+<script>
+
+ +
function Init () {
+    var myTextbox = document.getElementById('my-textbox');
+    myTextbox.addEventListener( 'keypress', checkName, false );
+}
+
+function checkName(evt) {
+    var charCode = evt.charCode;
+    if (charCode != 0) {
+        if (charCode < 97 || charCode > 122) {
+            evt.preventDefault();
+            alert(
+                "Please use lowercase letters only."
+                + "\n" + "charCode: " + charCode + "\n"
+            );
+        }
+    }
+}
+
+ +
</script>
+</head>
+<body onload="Init ()">
+    <p>Please enter your name using lowercase letters only.</p>
+    <form>
+        <input type="text" id="my-textbox" />
+    </form>
+</body>
+</html>
+
+ +

Aqui está o resultado do código anterior:

+ +

{{ EmbedLiveSample('preventDefault_invalid_text', '', '', '') }}

+ +

Notas

+ +

Chamar preventDefault durante qualquer fase do fluxo de eventos cancela o evento, o que significa que qualquer ação padrão normalmente feita pela aplicação como um resultado do evento não ocorrerá.

+ +
+

Nota: A partir do {{Gecko("6.0")}}, chamar o preventDefault() faz com que o {{ domxref("event.defaultPrevented") }} se torne true.

+
+ +

Você pode usar o event.cancelable para checar se o evento é cancelável. Chamar o preventDefault para um evento não cancelável não fará efeito.

+ +

Se o preventDefault não parar a propagação do evento através do DOM. event.stopPropagation deve ser usada para isso.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/event/srcelement/index.html b/files/pt-br/web/api/event/srcelement/index.html new file mode 100644 index 0000000000..c66dc744d4 --- /dev/null +++ b/files/pt-br/web/api/event/srcelement/index.html @@ -0,0 +1,74 @@ +--- +title: Event.srcElement +slug: Web/API/Event/srcElement +translation_of: Web/API/Event/srcElement +--- +

{{ApiRef("DOM")}}

+ +

{{ Non-standard_header() }}

+ +

Event.srcElement é uma propriedade alias para a propriedade padrão {{domxref("Event.target")}}. É específica para versões antigas do Microsoft Internet Explorer.

+ +

Especificações

+ +

Não é parte de nenhuma especificação.

+ +

Microsoft tem uma descrição na MSDN.

+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatNo}} [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1]: {{bug(453968)}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/event/stopimmediatepropagation/index.html b/files/pt-br/web/api/event/stopimmediatepropagation/index.html new file mode 100644 index 0000000000..a5de39c083 --- /dev/null +++ b/files/pt-br/web/api/event/stopimmediatepropagation/index.html @@ -0,0 +1,99 @@ +--- +title: Event.stopImmediatePropagation() +slug: Web/API/Event/stopImmediatePropagation +tags: + - API + - Method + - Referência(2) + - event.stopImmediatePropagation(); + - events + - pt-br + - stopImmediatePropagation +translation_of: Web/API/Event/stopImmediatePropagation +--- +
{{APIRef("DOM")}}
+ +

Evita que outros listeners escutem o evento.

+ +

Sintaxe

+ +
event.stopImmediatePropagation();
+
+ +

Notas

+ +

No caso de um evento onde vários listeners o estão escutando, os mesmos são disparados na ordem em que foram adicionados. Porém, se durante uma chamada (ou disparo), event.stopImmediatePropagation() for chamado, os demais listeners não serão disparados.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('DOM WHATWG', '#dom-event-stopimmediatepropagation', 'Event.stopImmediatePropagation()')}}{{Spec2('DOM WHATWG')}} 
{{SpecName('DOM4', '#dom-event-stopimmediatepropagation', 'Event.stopImmediatePropagation()')}}{{Spec2('DOM4')}}Initial definition
+ +

Compatibilidade

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatChrome("6.0")}}{{CompatGeckoDesktop("10.0")}}{{CompatIE(9.0)}}{{CompatOpera("15.0")}}{{CompatSafari("5.0")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/event/stoppropagation/index.html b/files/pt-br/web/api/event/stoppropagation/index.html new file mode 100644 index 0000000000..54d0c9bd5f --- /dev/null +++ b/files/pt-br/web/api/event/stoppropagation/index.html @@ -0,0 +1,93 @@ +--- +title: Event.stopPropagation() +slug: Web/API/Event/stopPropagation +tags: + - API + - Evento + - Referencia + - Referência(2) + - metodo + - stopPropagation +translation_of: Web/API/Event/stopPropagation +--- +

{{APIRef("DOM")}}

+ +

Resumo

+ +

Impede a propagação do evento por seus respectivos listeners.

+ +

Sintaxe

+ +
event.stopPropagation();
+ +

Parametros

+ +

Nenhum

+ +

Valor retornado

+ +

undefined.

+ +

Exemplo

+ +

Veja o exemplo 5: Event Propagation no capítulo Eventos para um exemplo mais detalhado desse método e propagação de evento no DOM.

+ +

Notas

+ +

Veja DOM specification para a explicação do fluxo de eventos. (O DOM Level 3 Events draft possui uma ilustração.)

+ +

preventDefault é um método de complemento que pode ser usado para previnir a ação padrão do evento que estiver acontecendo.

+ +

Especificação

+ +

DOM Level 3 Events: stopPropagation

+ +

Compatibilidade do Browser

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}9{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
diff --git a/files/pt-br/web/api/event/target/index.html b/files/pt-br/web/api/event/target/index.html new file mode 100644 index 0000000000..8a3ab35191 --- /dev/null +++ b/files/pt-br/web/api/event/target/index.html @@ -0,0 +1,69 @@ +--- +title: Event.target +slug: Web/API/Event/target +tags: + - PortuguêsBrasil + - pt-br +translation_of: Web/API/Event/target +--- +
{{ApiRef("DOM")}}
+ +

Uma referência ao objeto que enviou o evento. É diferente de {{domxref ("event.currentTarget")}} quando o manipulador de eventos é chamado durante a fase de borbulhagem ou captura do evento.

+ +

Sintaxe

+ +
theTarget = event.target
+ +

Exemplo

+ +

A propriedade event.target pode ser usada para implementar a delegação de eventos.

+ +
// Assumindo que existe uma variável 'list' contendo uma instância de um elemento ul de HTML.
+function hide(e) {
+  // A menos que os itens da lista sejam separados por uma margem, e.target deve ser diferente de e.currentTarget
+  e.target.style.visibility = 'hidden';
+}
+
+list.addEventListener('click', hide, false);
+
+// Se algum elemento (elemento <li> ou um link dentro de um elemento <li> por exemplo) for clicado, ele desaparecerá.
+// Só requer um único listener para fazer isso.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-event-target", "Event.target")}}{{Spec2("DOM WHATWG")}}
{{SpecName("DOM4", "#dom-event-target", "Event.target")}}{{Spec2("DOM4")}}
{{SpecName("DOM2 Events", "#Events-Event-target", "Event.target")}}{{Spec2("DOM2 Events")}}Initial definition
+ +

Compatibilidade do navegador

+ + +

{{Compat("api.Event.target")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/event/type/index.html b/files/pt-br/web/api/event/type/index.html new file mode 100644 index 0000000000..3ca34e79f3 --- /dev/null +++ b/files/pt-br/web/api/event/type/index.html @@ -0,0 +1,60 @@ +--- +title: Event.type +slug: Web/API/Event/type +translation_of: Web/API/Event/type +--- +

{{APIRef("DOM")}}

+ +

Sumário

+ +

Retorna uma string contendo o tipo de evento.

+ +

O argumento do evento {{ domxref("EventTarget.addEventListener()") }} e {{ domxref("EventTarget.removeEventListener()") }} é caso insensível(case insensitive).

+ +

Veja Mozilla event reference para obter a lista de tipos de evento disponíveis

+ +

Sintaxe

+ +
event.type
+
+ +

Exemplos

+ +
var string = event.type;
+
+ +
<!DOCTYPE html>
+<html lang="pt-br">
+<head>
+
+<title>exemplo de tipo</title>
+
+<script>
+var currEvent = null;
+
+function getEvtType(evt) {
+  currEvent = evt.type;
+  document.getElementById("Etype").firstChild.nodeValue = currEvent;
+}
+
+</script>
+</head>
+
+<body
+  onkeydown="getEvtType(event)"
+  onkeyup="getEvtType(event)"
+  onmousedown="getEvtType(event)"
+  onmouseup="getEvtType(event)">
+
+<p>Pressione uma tecla ou clique com o mouse para obter o tipo de evento.</p>
+<p>Tipo de evento: <span id="Etype">-</span></p>
+
+</body>
+</html>
+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/eventlistener/index.html b/files/pt-br/web/api/eventlistener/index.html new file mode 100644 index 0000000000..0e00e865a2 --- /dev/null +++ b/files/pt-br/web/api/eventlistener/index.html @@ -0,0 +1,48 @@ +--- +title: EventListener +slug: Web/API/EventListener +tags: + - API + - DOM + - Eventos DOM +translation_of: Web/API/EventListener +--- +

{{APIRef("DOM Events")}}

+ +

Visão Geral

+ + + + + + + +
void handleEvent(in Event event);
+ +

Métodos

+ +

handleEvent()

+ +

Este método é chamado sempre que ocorrer o evento para qual a interface do  EventListener for registrada.

+ +
void handleEvent(
+  in Event event
+);
+
+ +
Parâmetros
+ +
+
event
+
O {{ domxref("Evento") }} DOM que foi acionado.
+
+ +

Observaçōes

+ +

Conforme a interface for marcada com a flag [function], todos os objetos Function automaticamente implementtam essa interface. Chamar o método {{ manch("handleEvent") }} em uma dessas implementaçōes automaticamente invoca a função.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/eventsource/eventsource/index.html b/files/pt-br/web/api/eventsource/eventsource/index.html new file mode 100644 index 0000000000..30db3e3761 --- /dev/null +++ b/files/pt-br/web/api/eventsource/eventsource/index.html @@ -0,0 +1,157 @@ +--- +title: EventSource() +slug: Web/API/EventSource/EventSource +tags: + - API + - Construtor + - EventSource + - Eventos enviados pelo servidor + - Referencia +translation_of: Web/API/EventSource/EventSource +--- +
{{APIRef('WebSockets API')}}
+ +

O construtor EventSource() retorna uma nova {{domxref("EventSource")}}, que representa um recurso remoto.

+ +

Sintaxe

+ +
eventSource = new EventSource(url, configuration);
+ +

Parâmetros

+ +
+
url
+
Uma {{domxref("USVString")}} que representa a localização de um recurso remoto servindo os eventos/mensagens.
+
configuration {{optional_inline}}
+
Fornece opções para configurar a nova conexão. Os atributos possíveis são: +
    +
  • withCredentials, valor padrão false, indicando se o CORS deve ser instruído a incluir credenciais.
  • +
+
+
+ +

Exemplos

+ +
var evtSource = new EventSource('sse.php');
+var eventList = document.querySelector('ul');
+
+evtSource.onmessage = function(e) {
+  var newElement = document.createElement("li");
+
+  newElement.textContent = "message: " + e.data;
+  eventList.appendChild(newElement);
+}
+ +
+

Nota: Você pode encontrar um exemplo completo no GitHub — veja Simple SSE demo using PHP.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "comms.html#dom-eventsource", "EventSource()")}}{{Spec2('HTML WHATWG')}}Definição inicial
+ + + +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico9{{ CompatGeckoDesktop("6.0") }}{{CompatUnknown}}115
Suporte a CORS (withCredentials)26{{ CompatGeckoDesktop("11.0") }}{{CompatUnknown}}12{{CompatUnknown}}
Disponível em workers compartilhados e dedicados[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("53.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatAndroid("4.4") }}{{ CompatGeckoMobile("6.0") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Suporte a CORS (withCredentials){{CompatUnknown}}{{ CompatGeckoMobile("11.0") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponível em workers compartilhados e dedicados[1]{{CompatUnknown}}{{CompatGeckoMobile("53.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Masin ainda não em service workers.

+ +

See also

+ + diff --git a/files/pt-br/web/api/eventsource/index.html b/files/pt-br/web/api/eventsource/index.html new file mode 100644 index 0000000000..9b9efaaf46 --- /dev/null +++ b/files/pt-br/web/api/eventsource/index.html @@ -0,0 +1,175 @@ +--- +title: EventSource +slug: Web/API/EventSource +tags: + - API + - Interface + - eventos +translation_of: Web/API/EventSource +--- +

{{APIRef("Websockets API")}}

+ +

A interface EventSource é usada para receber eventos enviados pelo servidor (server-sent events). Ele se conecta via HTTP em um servidor e recebe eventos com o formato text/event-stream. A conexão permanece aberta até ser fechada chamando {{domxref("EventSource.close()")}}.

+ +

Assim que a conexão estiver aberta, mensagens recebidas do servidor são entregues para o seu código na forma de eventos {{event("message")}}.

+ +

Ao contrário dos WebSockets, server-sent events são unidirecionais; ou seja, mensagens são entregues em uma direção, do servidor para o cliente (por exemplo, um navegador web). Isso torna-os uma excelente escolha quando não há necessidade de enviar mensagens do cliente para o servidor. Por exemplo, EventSource é uma abordagem útil para lidar com atualizações de status de mídias sociais, feeds de notícias, or entregar dados para um mecanismo de armazenamento do lado cliente como o IndexedDB ou o web storage.

+ +

Construtor

+ +
+
{{domxref("EventSource.EventSource", "EventSource()")}}
+
Cria um novo EventSource para receber enventos enviados pelo servidor de uma URL específica, opcionalmente no modo de credenciais.
+
+ +

Propriedades

+ +

 

+ +

Essa interface também herda propriedades do seu pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("EventSource.readyState")}} {{readonlyinline}}
+
Um número representando o estado da conexão. Valores possíveis são CONNECTING (0), OPEN (1), ou CLOSED (2).
+
{{domxref("EventSource.url")}} {{readonlyinline}}
+
Uma {{domxref("DOMString")}} representando a URL da origem.
+
{{domxref("EventSource.withCredentials")}} {{readonlyinline}}
+
Um {{domxref("Boolean")}} indicando se a EventSource foi instanciada com credenciais cross-origin (CORS) definidas (true) ou não (false, o padrão).
+
+

Eventos

+
+
{{domxref("EventSource.onerror")}}
+
É um {{domxref("EventHandler")}} chamado quando um erro ocorre e o evento {{event("error")}} é despachado para o objeto EventSource.
+
{{domxref("EventSource.onmessage")}}
+
É um {{domxref("EventHandler")}} chamado quando um evento {{event("message")}} é recebido, ou seja, quando uma mensagem está sendo recebida da origem.
+
{{domxref("EventSource.onopen")}}
+
É um {{domxref("EventHandler")}} chamado quando um evento {{event("open")}} é recebido, ou seja, logo após a abertura da conexão.
+
+ +

Métodos

+ +

Essa interface herda métodos de seu pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("EventSource.close()")}}
+
Fecha a conexão, se houver, e define o atributo readyState como CLOSED. Se a conexão já estiver fechada, esse método não faz nada.
+
+ +

Exemplos

+ +

Nesse exemplo básico, um EventSource é criado para receber eventos do servidor; a página com o nome "sse.php" é responsável por gerar os eventos.

+ +
var evtSource = new EventSource('sse.php');
+var eventList = document.querySelector('ul');
+
+evtSource.onmessage = function(e) {
+  var newElement = document.createElement("li");
+
+  newElement.textContent = "message: " + e.data;
+  eventList.appendChild(newElement);
+}
+ +

Cada evento recebido faz com que o handler do evento onmessage no objeto EventSource seja executado. Ele, em contrapartida, cria um novo elemento {{HTMLElement("li")}} e escreve os dados da mensagem nele, e em seguida concatena o novo elemento na lista já presente no documento.

+ +
+

Nota: Você pode encontrar um exemplo completo no GitHub — veja Simple SSE demo using PHP.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "comms.html#the-eventsource-interface", "EventSource")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade de Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte a EventSource6{{CompatNo}}{{CompatGeckoDesktop("6.0")}}{{CompatNo}}{{CompatVersionUnknown}}5
Disponível em workers compartilhados e dedicados[1]{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte a EventSource4.445{{CompatNo}}124.1
Disponível em workers compartilhados e dedicados[1]{{CompatVersionUnknown}}{{CompatGeckoMobile("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Mas ainda não em service workers.

+ +

 

+ +

Veja também

+ + + +

 

diff --git a/files/pt-br/web/api/eventsource/onerror/index.html b/files/pt-br/web/api/eventsource/onerror/index.html new file mode 100644 index 0000000000..09b996e967 --- /dev/null +++ b/files/pt-br/web/api/eventsource/onerror/index.html @@ -0,0 +1,121 @@ +--- +title: EventSource.onerror +slug: Web/API/EventSource/onerror +translation_of: Web/API/EventSource/onerror +--- +
{{APIRef('WebSockets API')}}
+ +
 
+ +

A propriedade onerror da interface {{domxref("EventSource")}} é um {{domxref("EventHandler")}} chamado quando um erro ocorre e um evento {{event("error")}} é despachado para o objeto EventSource.

+ +

Sintaxe

+ +
eventSource.onerror = function
+ +

Exemplos

+ +
evtSource.onerror = function() {
+  console.log("EventSource failed.");
+};
+ +
+

Nota: Você pode encontrar um exemplo completo no GitHub — veja Simple SSE demo using PHP.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "comms.html#handler-eventsource-onerror", "onerror")}}{{Spec2('HTML WHATWG')}}Definição inicial
+ + + +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte a EventSource6{{CompatNo}}{{CompatGeckoDesktop("6.0")}}{{CompatNo}}{{CompatVersionUnknown}}5
Disponibilidade em workers compartilhados e dedicados[1]{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte a EventSource4.445{{CompatNo}}124.1
Disponibilidade em workers compartilhados e dedicados[1]{{CompatVersionUnknown}}{{CompatGeckoMobile("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Mas ainda não em service workers.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/eventtarget/dispatchevent/index.html b/files/pt-br/web/api/eventtarget/dispatchevent/index.html new file mode 100644 index 0000000000..75b633642b --- /dev/null +++ b/files/pt-br/web/api/eventtarget/dispatchevent/index.html @@ -0,0 +1,43 @@ +--- +title: EventTarget.dispatchEvent() +slug: Web/API/EventTarget/dispatchEvent +tags: + - API + - DOM + - Gecko + - Method + - events +translation_of: Web/API/EventTarget/dispatchEvent +--- +

{{APIRef("DOM Events")}}

+ +

Dispara um {{domxref("Event")}} para o {{domxref("EventTarget")}} especificado, invocando os {{domxref("EventListener")}}s especificados, em uma ordem apropriada. O processamento normal das regras (including the capturing and optional bubbling phase) aplica-se a eventos disparados manualmente com dispatchEvent().

+ +

Sintaxe

+ +
cancelled = !target.dispatchEvent(event)
+
+ + + +

O método dispatchEvent joga UNSPECIFIED_EVENT_TYPE_ERR se o tipo do evento não foi especificado pela inicialização do evento antes do método ser chamado, ou se o tipo do evento for is null ou uma string vazia. Exceções jogadas por event handlers são reportadas  como exceções não-capturáveis; os event handlers são executados em uma callstack aninhada; eles bloqueiam o chamador até que a rotina tenha sido totalmente executada, mas as execeções não se propagam para o chamador.

+ +

Notas

+ +

dispatchEvent é a última fase do processo create-init-dispatch, a qual é usada para disparar eventos na implementação do event model. O evento pode ser criado utilizando o método document.createEvent e pode ser inicializado com initEvent ou outro método de inicialização mais específico, como initMouseEvent ou initUIEvent.

+ +

Veja também a referência Event object.

+ +

Exemplo

+ +

Veja Creating and triggering events.

+ +

Especificações

+ + diff --git a/files/pt-br/web/api/eventtarget/eventtarget/index.html b/files/pt-br/web/api/eventtarget/eventtarget/index.html new file mode 100644 index 0000000000..0ce5aa4363 --- /dev/null +++ b/files/pt-br/web/api/eventtarget/eventtarget/index.html @@ -0,0 +1,70 @@ +--- +title: EventTarget() +slug: Web/API/EventTarget/EventTarget +translation_of: Web/API/EventTarget/EventTarget +--- +
{{APIRef("DOM Events")}}
+ +

O construtor EventTarget() cria uma nova instância do objeto {{domxref("EventTarget")}}.

+ +

Sintaxe

+ +
var myEventTarget = new EventTarget();
+ +

Parâmetros

+ +

Nenhum.

+ +

Retorno de valor

+ +

Uma instância do objeto {{domxref("EventTarget")}}.

+ +

Exemplos

+ +
class MyEventTarget extends EventTarget {
+  constructor(mySecret) {
+    super();
+    this._secret = mySecret;
+  }
+
+  get secret() { return this._secret; }
+};
+
+let myEventTarget = new MyEventTarget(5);
+let value = myEventTarget.secret;  // == 5
+myEventTarget.addEventListener("foo", function(e) {
+  this._secret = e.detail;
+});
+
+let event = new CustomEvent("foo", { detail: 7 });
+myEventTarget.dispatchEvent(event);
+let newValue = myEventTarget.secret; // == 7
+ +

Specificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-eventtarget-eventtarget', 'EventTarget() constructor')}}{{Spec2('DOM WHATWG')}}
+ +

Compatibilidade de navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/eventtarget/index.html b/files/pt-br/web/api/eventtarget/index.html new file mode 100644 index 0000000000..c1eb84c9f0 --- /dev/null +++ b/files/pt-br/web/api/eventtarget/index.html @@ -0,0 +1,124 @@ +--- +title: EventTarget +slug: Web/API/EventTarget +tags: + - API + - DOM + - DOM Events + - Interface +translation_of: Web/API/EventTarget +--- +

{{ ApiRef("DOM Events") }}

+ +

Resumo

+ +

EventTarget é uma interface DOM implementada por objetos que podem receber eventos DOM e tem que ouvir estes.

+ +

{{domxref("Element")}}, {{domxref("document")}}, e {{domxref("window")}} são os mais comuns disparadores de eventos, mas outros objetos podem disparar eventos também, por exemplo {{domxref("XMLHttpRequest")}}, {{domxref("AudioNode")}}, {{domxref("AudioContext")}} e outros.

+ +

Muitos disparadores de eventos (incluindo elements, documents,  e windows) também suportam definir event handlers através on... propriedades e atributos.

+ +

Métodos

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
Registra um tratamento para um tipo específico de evento sobre o EventTarget.
+
{{domxref("EventTarget.removeEventListener()")}}
+
Remove um event listener do EventTarget.
+
{{domxref("EventTarget.dispatchEvent()")}}
+
Dispatch an event to this EventTarget.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#interface-eventtarget', 'EventTarget')}}{{Spec2('DOM WHATWG')}}Sem mundanças.
{{SpecName('DOM3 Events', 'DOM3-Events.html#interface-EventTarget', 'EventTarget')}}{{Spec2('DOM3 Events')}}Alguns parâmetros agora são opcionais (listener), ou aceitam o valor null (useCapture).
{{SpecName('DOM2 Events', 'events.html#Events-EventTarget', 'EventTarget')}}{{Spec2('DOM2 Events')}}Definição inicial.
+ +

Compatibilidade entre navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico1.0{{ CompatGeckoDesktop("1") }}9.071.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico1.0{{ CompatGeckoMobile("1") }}9.06.01.0
+
+ +

Additional methods for Mozilla chrome code

+ +

Mozilla extensions for use by JS-implemented event targets to implement on* properties. See also WebIDL bindings.

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/eventtarget/removeeventlistener/index.html b/files/pt-br/web/api/eventtarget/removeeventlistener/index.html new file mode 100644 index 0000000000..dc558d006f --- /dev/null +++ b/files/pt-br/web/api/eventtarget/removeeventlistener/index.html @@ -0,0 +1,138 @@ +--- +title: EventTarget.removeEventListener() +slug: Web/API/EventTarget/removeEventListener +tags: + - API + - DOM + - Gecko + - JavaScript + - Method + - events +translation_of: Web/API/EventTarget/removeEventListener +--- +

{{APIRef("DOM Events")}}

+ +

Remove o event listener anteriormente registrado com {{domxref("EventTarget.addEventListener()")}}.

+ +

Sintaxe

+ +
target.removeEventListener(type, listener[, useCapture])
+ +
+
type
+
Uma string indicando o tipo de evento a ser removido.
+
listener
+
A função {{ domxref("EventListener") }}  a ser removida do event target.
+
useCapture {{ optional_inline() }}
+
Indica quando o {{ domxref("EventListener") }} a ser removido foi registrado ou não como capturing listener. Caso este parâmetro seja omitido, o valor false será assumido por padrão.
+
Se um listener foi registrado duas vezes, uma com o parâmetro capture especificado e outra sem, cada um deve ser removido separadamente. A remoção de um capturing listener não afeta a versão non-capturing do mesmo listener, e vice versa.
+
+ +
Nota: useCapture era obrigatório em versões mais antigas dos navegadores. Para ampla compatibilidade, sempre informe o parâmetro useCapture.
+ +

Notas

+ +

Se um {{ domxref("EventListener") }} é removido de um {{ domxref("EventTarget") }} enquanto este está processando um evento, esse não será disparado pelas current actions. Um {{ domxref("EventListener") }} não será invocado para o evento o qual foi registrado depois de ter sido removido, porém pode ser registrado novamente.

+ +

Chamar removeEventListener() com argumentos que não identifiquem nenhum {{ domxref("EventListener") }} registrado no EventTarget não tem qualquer efeito.

+ +

Exemplo

+ +

Este é um exemplo de como associar e remover um event listener.

+ +
var div = document.getElementById('div');
+var listener = function (event) {
+  /* faça alguma coisa... */
+};
+div.addEventListener('click', listener, false);
+div.removeEventListener('click', listener, false);
+
+ +

Compatibilidade entre navegadores

+ +

{{Compat("api.EventTarget.removeEventListener", 3)}}

+ + + +

Notas para Gecko

+ + + +

Notas para Opera

+ + + +

Notas para WebKit

+ + + +

Veja também

+ +

{{ domxref("EventTarget.addEventListener()") }}.

+ +

Especificação

+ + + +

Polyfill para oferecer suporte aos navegadores antigos

+ +

addEventListener() e removeEventListener() não estão presentes em navegadores antigos. Isto pode ser contornado se você inserir o código abaixo no início dos seus scripts, permitindo o uso de addEventListener() e removeEventListener()  em implementações as quais não oferecem suporte nativo. Entretanto, este método não funciona para o Internet Explorer 7 ou versões anteriores, uma vez que não era possível extender o Element.prototype até o Internet Explorer 8.

+ +
if (!Element.prototype.addEventListener) {
+  var oListeners = {};
+  function runListeners(oEvent) {
+    if (!oEvent) { oEvent = window.event; }
+    for (var iLstId = 0, iElId = 0, oEvtListeners = oListeners[oEvent.type]; iElId < oEvtListeners.aEls.length; iElId++) {
+      if (oEvtListeners.aEls[iElId] === this) {
+        for (iLstId; iLstId < oEvtListeners.aEvts[iElId].length; iLstId++) { oEvtListeners.aEvts[iElId][iLstId].call(this, oEvent); }
+        break;
+      }
+    }
+  }
+  Element.prototype.addEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {
+    if (oListeners.hasOwnProperty(sEventType)) {
+      var oEvtListeners = oListeners[sEventType];
+      for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
+        if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }
+      }
+      if (nElIdx === -1) {
+        oEvtListeners.aEls.push(this);
+        oEvtListeners.aEvts.push([fListener]);
+        this["on" + sEventType] = runListeners;
+      } else {
+        var aElListeners = oEvtListeners.aEvts[nElIdx];
+        if (this["on" + sEventType] !== runListeners) {
+          aElListeners.splice(0);
+          this["on" + sEventType] = runListeners;
+        }
+        for (var iLstId = 0; iLstId < aElListeners.length; iLstId++) {
+          if (aElListeners[iLstId] === fListener) { return; }
+        }
+        aElListeners.push(fListener);
+      }
+    } else {
+      oListeners[sEventType] = { aEls: [this], aEvts: [ [fListener] ] };
+      this["on" + sEventType] = runListeners;
+    }
+  };
+  Element.prototype.removeEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {
+    if (!oListeners.hasOwnProperty(sEventType)) { return; }
+    var oEvtListeners = oListeners[sEventType];
+    for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
+      if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }
+    }
+    if (nElIdx === -1) { return; }
+    for (var iLstId = 0, aElListeners = oEvtListeners.aEvts[nElIdx]; iLstId < aElListeners.length; iLstId++) {
+      if (aElListeners[iLstId] === fListener) { aElListeners.splice(iLstId, 1); }
+    }
+  };
+}
+
diff --git a/files/pt-br/web/api/fetch_api/basic_concepts/index.html b/files/pt-br/web/api/fetch_api/basic_concepts/index.html new file mode 100644 index 0000000000..c9845e75aa --- /dev/null +++ b/files/pt-br/web/api/fetch_api/basic_concepts/index.html @@ -0,0 +1,66 @@ +--- +title: Conceitos básicos de Fetch +slug: Web/API/Fetch_API/Basic_concepts +translation_of: Web/API/Fetch_API/Basic_concepts +--- +

{{DefaultAPISidebar("Fetch API")}}{{draft}}

+ +
+

Fetch API fornece uma interface para buscar recursos (inclusive pela rede). Parecerá familiar para alguém que já tenha usado {{domxref("XMLHttpRequest")}}, mas ela fornece um conjunto de recursos mais poderoso e flexível . Este artigo expõe alguns conceitos básicos da API Fetch.

+
+ +
+

Este artigo será incrementado ao longo do tempo. Se você achar um conceito em Fetch que parece precisar de uma explicação melhor, informe alguém em fórum de discussãMDN, or Mozilla IRC (#mdn room.)

+
+ +

Em poucas palavras

+ +

O coração do Fetch são as abstrações da Interface do HTTP {{domxref("Request")}}, {{domxref("Response")}}, {{domxref("Headers")}}, e {{domxref("Body")}} payloads, juntamente com {{domxref("GlobalFetch.fetch","global fetch")}} método para iniciar requisições de recursos assíncronos. Como os componentes principais do HTTP são abstraidos como objetos de JavaScript, torna-se fácil APIs fazer uso das funcionalidades.

+ +

Service Workers é um exemplo de uma API que faz um grande uso de Fecth.

+ +

Fetch leva a assincronicidade um passo além. A API é completamente baseada em {{jsxref("Promise")}}.

+ +

Guard

+ +

Guard é uma novidade de objetos {{domxref("Headers")}}, podendo assumir os valores de immutable, request, request-no-cors, response, ou none, dependendo de onde o cabeçalho é utilizado.

+ +

Quando um novo objeto {{domxref("Headers")}} é criado usando o {{domxref("Headers.Headers","Headers()")}} {{glossary("constructor")}}, seu guard é configurado como none (o padrão). Quando um objeto {{domxref("Request")}} ou {{domxref("Response")}} é criado, tem um objeto {{domxref("Headers")}}  associado cujo guard é resumido a seguir:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Novo tipo de objetoConstrutor criadoConfiguração guard associada ao objeto {{domxref("Headers")}}
{{domxref("Request")}}{{domxref("Request.Request","Request()")}}request
{{domxref("Request.Request","Request()")}} com {{domxref("Request.mode","mode")}} de no-corsrequest-no-cors
{{domxref("Response")}}{{domxref("Response.Response","Response()")}}response
Métodos {{domxref("Response.error","error()")}} ou {{domxref("Response.redirect","redirect()")}}immutable
+ +

Um cabeçalho guard afeta os métodos {{domxref("Headers.set","set()")}}, {{domxref("Headers.delete","delete()")}}, e {{domxref("Headers.append","append()")}} os quais mudam o conteúdo do cabeçalho. UmTypeError é lançado se você tentar modificar um objeto {{domxref("Headers")}} objeto cujo "guard" é immutable. De qualquer maneira, a operação vai funcionar se

+ + diff --git a/files/pt-br/web/api/fetch_api/index.html b/files/pt-br/web/api/fetch_api/index.html new file mode 100644 index 0000000000..6409994ae7 --- /dev/null +++ b/files/pt-br/web/api/fetch_api/index.html @@ -0,0 +1,85 @@ +--- +title: Fetch API +slug: Web/API/Fetch_API +tags: + - API + - Experimental + - Fetch + - Referência(2) + - XMLHttpRequest + - request +translation_of: Web/API/Fetch_API +--- +

{{DefaultAPISidebar("Fetch API")}}{{ SeeCompatTable() }}

+ +

A Fetch API fornece uma interface para buscar recursos (por exemplo, em toda a rede). Parecerá familiar para qualquer pessoa que tenha usado XMLHttpRequest, porém a nova API oferece um conjunto de recursos mais poderoso e flexível.

+ +

Conceitos e uso

+ +

O Fetch fornece uma definição genérica de objetos de {{domxref("Request")}} e {{domxref("Response")}}  (e outras coisas envolvidas com solicitações de rede). Isso permitirá que eles sejam usados onde quer que sejam necessários no futuro, seja para service workers, Cache API e outras coisas similares que manipulam ou modifiquem pedidos e respostas ou qualquer tipo de caso de uso que possa exigir que você gere suas próprias responses programaticamente.

+ +

Ele também fornece uma definição para conceitos relacionados como CORS e a semântica de cabeçalho de origem HTTP, suplantando suas definições separadas em outro lugar.

+ +

Para fazer uma solicitação e buscar um recurso, use o método {{domxref("GlobalFetch.fetch")}} . Ele é implementado em várias interfaces, especificamente {{domxref("Window")}} e {{domxref("WorkerGlobalScope")}}. Isso torna disponível em praticamente qualquer contexto em que você possa querer obter recursos.

+ +

O método fetch () tem um argumento obrigatório, o caminho para o recurso que deseja obter. Ele retorna uma promessa que resolve a {{domxref("Response")}} para esta requisição, seja ele bem-sucedido ou não. Você também pode, opcionalmente, passar um objeto de opções de inicialização como o segundo argumento (consulte {{domxref("Request")}}).

+ +

Uma vez que uma {{domxref("Response")}} é recuperada, há uma série de métodos disponíveis para definir o conteúdo do corpo e como ele deve ser tratado (veja {{domxref("Body")}}.)

+ +


+ Você pode criar um pedido e uma resposta diretamente usando os construtores {{domxref("Request.Request","Request()")}} e {{domxref("Response.Response","Response()")}}, mas é improvável que você faça isso diretamente. Em vez disso, é mais provável que sejam criados como resultados de outras ações da API (por exemplo,  {{domxref("FetchEvent.respondWith")}} de service workers).

+ +
+

Note: Encontre mais informações sobre os recursos do Fetch API em Using Fetch,  e conceitos para estudos em Fetch basic concepts.

+
+ +

Fetch Interfaces

+ +
+
{{domxref("GlobalFetch")}}
+
Contém o método fetch() usado para buscar um recurso.
+
{{domxref("Headers")}}
+
Representa cabeçalhos response/request, permitindo que você os consulte e faça diferentes ações dependendo dos resultados.
+
{{domxref("Request")}}
+
Representa um pedido de recursos.
+
{{domxref("Response")}}
+
Representa a resposta de uma requisição.
+
+ +

Fetch mixin

+ +
+
{{domxref("Body")}}
+
Providencia métodos relacionados ao corpo da resposta/requisição, permitindo que você declare qual seu tipo de conteúdo e como ele deve ser tratado.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('Fetch')}}{{Spec2('Fetch')}}Definição inicial
+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/fetch_api/using_fetch/index.html b/files/pt-br/web/api/fetch_api/using_fetch/index.html new file mode 100644 index 0000000000..0b951f7461 --- /dev/null +++ b/files/pt-br/web/api/fetch_api/using_fetch/index.html @@ -0,0 +1,311 @@ +--- +title: Usando Fetch +slug: Web/API/Fetch_API/Using_Fetch +translation_of: Web/API/Fetch_API/Using_Fetch +--- +
+

A API Fetch fornece uma interface JavaScript para acessar e manipular partes do pipeline HTTP, tais como os pedidos e respostas. Ela também fornece o método global {{domxref("GlobalFetch.fetch","fetch()")}} que fornece uma maneira fácil e lógica para buscar recursos de forma assíncrona através da rede.

+
+ +

Este tipo de funcionalidade era obtida anteriormente utilizando {{domxref("XMLHttpRequest")}}. Fetch fornece uma alternativa melhor que pode ser facilmente utilizada por outras tecnologias como {{domxref("ServiceWorker_API", "Service Workers")}}. Fetch também provê um lugar lógico único para definir outros conceitos relacionados ao protocolo HTTP como CORS e extensões ao HTTP.

+ +

Note que a especificação fetch() difere de jQuery.ajax(), principalmente, de três formas:

+ + + +

Situação do suporte por navegadores

+ +

Os suportes para Fetch ainda estão em uma fase bastante precoce, mas começa a ter progresso. Se tornou um padrão no Firefox 39 e Chrome 42 até as versões mais atuais.

+ +

Caso tenha interesse no uso da ferramenta, há também uma Fetch Polyfill disponivel que recria as funcionalidade para outros navegadores que ainda não o suporta. Fique ciente que está em estado experimental e ainda não há uma versão completa.

+ +
+

Nota: There have been some concerns raised that the Fetch spec is at odds with the Streams spec; however, future plans show an intention to integrate Streams with Fetch: read Fetch API integrated with Streams for more information.

+
+ +

Detecção de Recursos

+ +

Fetch API support pode ser detectada na existência do escopo {{domxref("Headers")}}, {{domxref("Request")}}, {{domxref("Response")}} ou {{domxref("GlobalFetch.fetch","fetch()")}} no {{domxref("Window")}} ou {{domxref("Worker")}} . Por exemplo, faça o seguinte teste no seu código:

+ +
if(self.fetch) {
+    // execute minha solicitação do fetch aqui
+} else {
+    // faça alguma coisa com XMLHttpRequest?
+}
+ +

Fazendo as requisições Fetch

+ +

Uma requisição fetch é realizada para configuração. Temos um exemplo no seguinte código:

+ +
var myImage = document.querySelector('img');
+
+fetch('flowers.jpg')
+.then(function(response) {
+  return response.blob();
+})
+.then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+});
+
+
+ +

Aqui estamos procurando uma imagem e inserindo em um elemento {{htmlelement("img")}}. O uso mais básico dofetch() acarreta em um argumento — a pasta do recurso que você deseja buscar — e retorna uma promessa contendo a resposta (a {{domxref("Response")}} object).

+ +

Esta é apenas uma resposta HTTP, não a imagem em sí. Para extrairmos a imagem da resposta, nós usamos o método {{domxref("Body.blob","blob()")}} (definido no mixin do {{domxref("Body")}}, que são implementados por ambos os objetos {{domxref("Request")}} e {{domxref("Response")}}.)

+ +
+

Nota: O Body mixin além disso possui métodos similares para extrair outros tipos de conteúdo do body; Veja a sessão {{anch("Body")}} para mais detalhes.

+
+ +

Um objectURL é criado na extração de {{domxref("Blob")}}, que então é inserido no {{domxref("img")}}.

+ +

Requisições Fetch são controladas pela directiva connect-src do Content Security Policy ao invés da directiva do recurso retornado.

+ +

Fornecendo opções de request

+ +

O método fetch() pode receber um segundo parametro opcional, que consiste em um objeto init que permite setar várias configurações:

+ +
var myHeaders = new Headers();
+
+var myInit = { method: 'GET',
+               headers: myHeaders,
+               mode: 'cors',
+               cache: 'default' };
+
+fetch('flowers.jpg',myInit)
+.then(function(response) {
+  return response.blob();
+})
+.then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+});
+
+
+ +

See {{domxref("GlobalFetch.fetch","fetch()")}} for the full options available, and more descriptions.

+ +

Verificando se o fetch foi bem sucedido

+ +

Uma promise {{domxref("GlobalFetch.fetch","fetch()")}} será rejeitada com um {{jsxref("TypeError")}} quando um erro de rede é encontrado, embora isso geralmente signifique problemas de permissão ou similar — um 404 não constitui um erro de rede, por exemplo. Uma verificação precisa de um fetch()  bem-sucedido incluiria a verificação de que a promessa foi resolvida e, em seguida, a verificação de que a propriedade {{domxref("Response.ok")}} tem o valor de true. O código seria parecido com o abaixo:

+ +
fetch('flowers.jpg').then(function(response) {
+  if(response.ok) {
+    response.blob().then(function(myBlob) {
+      var objectURL = URL.createObjectURL(myBlob);
+      myImage.src = objectURL;
+    });
+  } else {
+    console.log('Network response was not ok.');
+  }
+})
+.catch(function(error) {
+  console.log('There has been a problem with your fetch operation: ' + error.message);
+});
+ +

Fornecendo seu próprio objeto de solicitação

+ +

Em vez de passar um caminho, para o recurso que você deseja solicitar, dentro da rquisição fetch(), você pode criar um objeto de solicitação usando o construtor {{domxref("Request.Request","Request()")}}, e então passar a solicitação como um argumento do método fetch() :

+ +
var myHeaders = new Headers();
+
+var myInit = { method: 'GET',
+               headers: myHeaders,
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg', myInit);
+
+fetch(myRequest)
+.then(function(response) {
+  return response.blob();
+})
+.then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+});
+ +

Request() aceita exatamente os mesmos parâmetros do método fetch(). Você pode até mesmo passar um objeto de solicitação existente para criar uma cópia dele:​​​​​​

+ +
var anotherRequest = new Request(myRequest,myInit);
+ +

Isso é muito útil, pois os conteúdos de cada solicitação e resposta tem apenas um uso. Fazer uma cópia como essa permite que você use a solicitação / resposta novamente, variando as opções de inicialização, se desejar.

+ +
+

Nota: Também existe um método que cria uma cópia: {{domxref ("Request.clone", "clone ()")}}. Isso tem uma semântica ligeiramente diferente do outro método de cópia: o primeiro dirá se o conteúdo, da solicitação anterior, já tiver sido lido (ou copiado), enquanto o segundo, clone() não.

+
+ +

Headers

+ +

A interface {{domxref("Headers")}} permite que você crie seus proprios objetos headers por meio do construtor {{domxref("Headers.Headers","Headers()")}}. Um objeto headers é um  mapa multidimensional simples de nomes para o valor? 

+ +
var content = "Hello World";
+var myHeaders = new Headers();
+myHeaders.append("Content-Type", "text/plain");
+myHeaders.append("Content-Length", content.length.toString());
+myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
+ +

O mesmo pode ser feito passando um array de arrays ou um objeto literal para o construtor:

+ +
myHeaders = new Headers({
+  "Content-Type": "text/plain",
+  "Content-Length": content.length.toString(),
+  "X-Custom-Header": "ProcessThisImmediately",
+});
+ +

O conteúdo pode ser consultado e recuperado:

+ +
console.log(myHeaders.has("Content-Type")); // true
+console.log(myHeaders.has("Set-Cookie")); // false
+myHeaders.set("Content-Type", "text/html");
+myHeaders.append("X-Custom-Header", "AnotherValue");
+
+console.log(myHeaders.get("Content-Length")); // 11
+console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]
+
+myHeaders.delete("X-Custom-Header");
+console.log(myHeaders.getAll("X-Custom-Header")); // [ ]
+ +

Some of these operations are only useful in {{domxref("ServiceWorker_API","ServiceWorkers")}}, but they provide a much nicer API for manipulating headers.

+ +

All of the Headers methods throw a TypeError if a header name is used that is not a valid HTTP Header name. The mutation operations will throw a TypeError if there is an immutable guard (see below). Otherwise they fail silently. For example:

+ +
var myResponse = Response.error();
+try {
+  myResponse.headers.set("Origin", "http://mybank.com");
+} catch(e) {
+  console.log("Cannot pretend to be a bank!");
+}
+ +

A good use case for headers is checking whether the content type is correct before you process it further. For example:

+ +
fetch(myRequest).then(function(response) {
+  var contentType = response.headers.get("content-type");
+  if(contentType && contentType.indexOf("application/json") !== -1) {
+    return response.json().then(function(json) {
+      // process your JSON further
+    });
+  } else {
+    console.log("Oops, we haven't got JSON!");
+  }
+});
+ +

Guard

+ +

Since headers can be sent in requests and received in responses, and have various limitations about what information can and should be mutable, headers objects have a guard property. This is not exposed to the Web, but it affects which mutation operations are allowed on the headers object.

+ +

Possible guard values are:

+ + + +
+

Note: You may not append or set a request guarded Headers’ Content-Length header. Similarly, inserting Set-Cookie into a response header is not allowed: ServiceWorkers are not allowed to set cookies via synthesized responses.

+
+ +

Response objects

+ +

As you have seen above, {{domxref("Response")}} instances are returned when fetch() promises are resolved.

+ +

They can also be created programmatically via JavaScript, but this is only really useful in {{domxref("ServiceWorker_API", "ServiceWorkers")}}, when you are providing a custom response to a received request using a {{domxref("FetchEvent.respondWith","respondWith()")}} method:

+ +
var myBody = new Blob();
+
+addEventListener('fetch', function(event) {
+  event.respondWith(
+    new Response(myBody, {
+      headers: { "Content-Type" : "text/plain" }
+    })
+  );
+});
+ +

The {{domxref("Response.Response","Response()")}} constructor takes two optional arguments — a body for the response, and an init object (similar to the one that {{domxref("Request.Request","Request()")}} accepts.)

+ +

The most common response properties you'll use are:

+ + + +
+

Note: The static method {{domxref("Response.error","error()")}} simply returns an error response. Similarly, {{domxref("Response.redirect","redirect()")}} returns a response resulting in
+ a redirect to a specified URL. These are also only relevant to Service Workers.

+
+ +

Body

+ +

Both requests and responses may contain body data. A body is an instance of any of the following types.

+ + + +

The {{domxref("Body")}} mixin defines the following methods to extract a body (implemented by both {{domxref("Request")}} and {{domxref("Response")}}). These all return a promise that is eventually resolved with the actual content.

+ + + +

This makes usage of non-textual data much easier than it was with XHR.

+ +

Request bodies can be set by passing body parameters:

+ +
var form = new FormData(document.getElementById('login-form'));
+fetch("/login", {
+  method: "POST",
+  body: form
+});
+ +

Both request and response (and by extension the fetch() function), will try to intelligently determine the content type. A request will also automatically set a Content-Type header if none is set in the dictionary.

+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch')}}{{Spec2('Fetch')}}Initial definition
+ +

Compatibilidade com os browsers

+ +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +
+ + diff --git a/files/pt-br/web/api/fetch_api/uso_de_busca_cross-global/index.html b/files/pt-br/web/api/fetch_api/uso_de_busca_cross-global/index.html new file mode 100644 index 0000000000..c569966b5a --- /dev/null +++ b/files/pt-br/web/api/fetch_api/uso_de_busca_cross-global/index.html @@ -0,0 +1,35 @@ +--- +title: Uso de busca Cross-global +slug: Web/API/Fetch_API/Uso_de_busca_Cross-global +translation_of: Web/API/Fetch_API/Cross-global_fetch_usage +--- +

 

+ +

Este artigo explica um "edge case" (um problema ou situação que ocorre apenas em um parâmetro operacional extremo) que ocorre ao utilizar fetch (e potencialmente outras APIs que exibem o mesmo tipo de comportamento de recuperação de recurso). Quando uma busca de cross-origin envolvendo uma URL relativa é iniciada a partir de um {{htmlelement ("iframe")}}, a URL relativa costumava ser resolvida na localização global atual, em vez da localização do iframe.

+ +

O "edge case"

+ +

Muitos sites nunca se deparam com este caso extremo. Para que isso aconteça:

+ + + +

O problema

+ +

No passado, resolveríamos o URL relativo contra o global atual, por exemplo:

+ +
let absolute = new URL(relative, window.location.href)
+ +

Isto não é um problema como tal. É que diferentes APIs que exibem esse tipo de comportamento estavam fazendo isso de maneira inconsistente com o comportamento definido na especificação, o que poderia levar a problemas mais adiante.

+ +

A solução

+ +

No Firefox 60 em diante, o Mozilla resolve a URL relativa contra o global que possui a função fetch() que está sendo usada (veja {{bug (1432272)}}). Portanto, no caso descrito acima, ele é resolvido em relação à localização do iframe:

+ +
let absolute = new URL(relative, frame.contentWindow.location.href)
+ +

Há muita discussão em andamento sobre a obtenção de novas especificações para se alinhar a essa mudança de comportamento, a fim de mitigar possíveis problemas no futuro.

diff --git a/files/pt-br/web/api/file/index.html b/files/pt-br/web/api/file/index.html new file mode 100644 index 0000000000..471cf7bbda --- /dev/null +++ b/files/pt-br/web/api/file/index.html @@ -0,0 +1,146 @@ +--- +title: File +slug: Web/API/File +tags: + - API + - Arquivos + - DOM + - Files + - Referencia +translation_of: Web/API/File +--- +
{{gecko_minversion_header("1.9")}}
+ +
{{APIRef("File API")}}
+ +

Sumário

+ +

A interface File provê informações sobre arquivos e permite ao JavaScript  a acessar seu conteúdo.

+ +

São geralmente recuperados a partir de um objeto {{domxref("FileList")}} que é retornado como resultado da seleção, pelo usuário, de arquivos através do elemento {{ HTMLElement("input") }}, a partir do objeto {{domxref("DataTransfer")}} utilizado em operações de arrastar e soltar, ou a partir da API mozGetAsFile() em um {{ domxref("HTMLCanvasElement") }}. Em Gecko, códigos com privilégiios podem criar objetos File representando qualquer arquivo local sem a intereção do usuário (veja {{anch("Implementation notes")}} para mais informações.)

+ +

Um objeto File é um tipo específico de  {{domxref("Blob")}}, e podem ser utilizados em qualquer contexto que um Blob pode. Em particular, {{domxref("FileReader")}}, {{domxref("URL.createObjectURL()")}}, {{domxref("ImageBitmapFactories.createImageBitmap()", "createImageBitmap()")}}, e {{domxref("XMLHttpRequest", "", "send()")}} aceitam ambos, Blobs e Files.

+ +

Veja Using files from web applications (usando arquivos através de uma aplicação web) para mais informações e exemplos.

+ +

A referência ao arquivo pode ser salva quando o formulário é submetido enquanto o usuário está offline, de forma que os dados possam ser recuperados e enviados quando a conexão com a internet for reestabelecida,

+ +

Propriedades

+ +
+
{{domxref("File.lastModifiedDate")}} {{readonlyinline}} {{gecko_minversion_inline("15.0")}}
+
A Data da última modificação do arquivo referenciado pelo objeto File.
+
{{domxref("File.name")}} {{readonlyinline}} {{gecko_minversion_inline("1.9.2")}}
+
O nome do arquivo referenciado pelo objeto File.
+
{{domxref("File.fileName")}} {{non-standard_inline}} {{readonlyinline}} {{obsolete_inline("7.0")}}
+
O nome do arquivo referenciado pelo objeto File.
+
{{domxref("File.fileSize")}} {{non-standard_inline}} {{readonlyinline}} {{obsolete_inline("7.0")}}
+
O tamanho do arquivo referenciado, em bytes.
+
+ +

A interface File herda as propriedades da interface {{domxref("Blob")}}.

+ +

{{page("/en-US/docs/Web/API/Blob","Properties")}}

+ +

Métodos

+ +
+
{{domxref("File.getAsBinary()")}} {{non-standard_inline}} {{obsolete_inline("7.0")}}
+
Retorna uma string contendo os dados do arquivo em formato binário.
+
{{domxref("File.getAsDataURL()")}} {{non-standard_inline}} {{obsolete_inline("7.0")}}
+
Uma string contendo os dados do arquivo codificados como data: URL.
+
{{domxref("File.getAsText()","File.getAsText(string encoding)")}} {{non-standard_inline}} {{obsolete_inline("7.0")}}
+
Retorna o conteúdo do arquivo como uma string em que os dados do arquivo são interpretados como texto, usando a codificação passada por parâmetro.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('File API')}}{{Spec2('File API')}}Definição Inicial.
+ +

Compatibilidade com os Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13{{CompatGeckoDesktop("1.9")}} (non standard)
+ {{CompatGeckoDesktop("7")}} (standard)
10.016.06.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatNo}}25{{CompatNo}}11.16.0
+
+ +

Notas de Implementação

+ +

Notas no Gecko

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/file/using_files_from_web_applications/index.html b/files/pt-br/web/api/file/using_files_from_web_applications/index.html new file mode 100644 index 0000000000..cba8315001 --- /dev/null +++ b/files/pt-br/web/api/file/using_files_from_web_applications/index.html @@ -0,0 +1,351 @@ +--- +title: Using files from web applications +slug: Web/API/File/Using_files_from_web_applications +translation_of: Web/API/File/Using_files_from_web_applications +--- +

Usando a File API adicionada ao DOM em HTML5, agora é possível para conteúdo web solicitar ao usuário para selecionar arquivos locais, e então ler o conteúdo desses arquivos. Essa seleção pode ser feita usando um elemento HTML {{HTMLElement("input") }} ou por arrastar e soltar.  

+

Se você quiser usar a DOM File API através de extensões ou outro código chrome, você pode; Na verdade, há algumas funcionalidades adicionais para se estar ciente. Veja Usando a DOM File API em código chrome para detalhes.

+

Selecionando arquivos usando HTML

+

Selecionar um único arquivo para uso com a File API é simples:

+
<input type="file" id="input" onchange="handleFiles(this.files)">
+

Quando um usuário seleciona um arquivo, a função handleFiles() é chamada com um objeto {{ domxref("FileList") }} contendo o objeto {{ domxref("File") }} representando o arquivo selecionado pelo usuário.

+

If you want to let the user select multiple files, simply use the multiple attribute on the input element:

+
<input type="file" id="input" multiple onchange="handleFiles(this.files)">
+

In this case, the file list passed to the handleFiles() function contains one {{ domxref("File") }} object for each file the user selected.

+

Using hidden file input elements using the click() method

+

Starting in Gecko 2.0 {{ geckoRelease("2.0") }}, you can hide the admittedly ugly file {{ HTMLElement("input") }} element and present your own interface for opening the file picker and displaying which file or files the user has selected. You can do this by styling the input element with display:none and calling the {{ domxref("element.click","click()") }} method on the {{ HTMLElement("input") }} element.

+

Consider this HTML:

+
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
+<a href="#" id="fileSelect">Select some files</a>
+

The code that handles the click event can look like this:

+
var fileSelect = document.getElementById("fileSelect"),
+  fileElem = document.getElementById("fileElem");
+
+fileSelect.addEventListener("click", function (e) {
+  if (fileElem) {
+    fileElem.click();
+  }
+  e.preventDefault(); // prevent navigation to "#"
+}, false);
+
+

Obviously you can style the new button for opening the file picker as you wish.

+

Dynamically adding a change listener

+

If your input field was created using a JavaScript library such as jQuery, you'll need to use {{ domxref("element.addEventListener()") }} to add the change event listener, like this:

+
var inputElement = document.getElementById("inputField");
+inputElement.addEventListener("change", handleFiles, false);
+
+function handleFiles() {
+  var fileList = this.files;
+
+  /* now you can work with the file list */
+}
+
+

Note that in this case, the handleFiles() function looks up the file list instead of accepting a parameter, since event listeners added in this way can't accept an input parameter.

+

Using object URLs

+

Gecko 2.0 {{ geckoRelease("2.0") }} introduces support for the DOM {{ domxref("window.URL.createObjectURL()") }} and {{ domxref("window.URL.revokeObjectURL()") }} methods. These let you create simple URL strings that can be used to reference any data that can be referred to using a DOM {{ domxref("File") }} object, including local files on the user's computer.

+

When you have a {{ domxref("File") }} object you'd like to reference by URL from HTML, you can create an object URL for it like this:

+
var objectURL = window.URL.createObjectURL(fileObj);
+

The object URL is a string identifying the {{ domxref("File") }} object. Each time you call {{ domxref("window.URL.createObjectURL()") }}, a unique object URL is created, even if you've created an object URL for that file already. Each of these must be released. While they are released automatically when the document is unloaded, if your page uses them dynamically, you should release them explicitly by calling {{ domxref("window.URL.revokeObjectURL()") }}:

+
window.URL.revokeObjectURL(objectURL);
+

Selecting files using drag and drop

+

You can also let the user drag and drop files into your web application.

+

The first step is to establish a drop zone. Exactly what part of your content will accept drops may vary depending on the design of your application, but making an element receive drop events is easy:

+
var dropbox;
+
+dropbox = document.getElementById("dropbox");
+dropbox.addEventListener("dragenter", dragenter, false);
+dropbox.addEventListener("dragover", dragover, false);
+dropbox.addEventListener("drop", drop, false);
+
+

In this example, we're turning the element with the ID dropbox into our drop zone. This is done by adding listeners for the dragenter, dragover, and drop events.

+

We don't actually need to do anything with the dragenter and dragover events in our case, so these functions are both simple. They just stop propagation of the event and prevent the default action from occurring:

+
function dragenter(e) {
+  e.stopPropagation();
+  e.preventDefault();
+}
+
+function dragover(e) {
+  e.stopPropagation();
+  e.preventDefault();
+}
+
+

The real magic happens in the drop() function:

+
function drop(e) {
+  e.stopPropagation();
+  e.preventDefault();
+
+  var dt = e.dataTransfer;
+  var files = dt.files;
+
+  handleFiles(files);
+}
+
+

Here, we retrieve the dataTransfer field from the event, then pull the file list out of it, passing that to handleFiles(). From this point on, handling the files is the same whether the user used the input element or drag and drop.

+

Getting information about selected files

+

The {{ domxref("FileList") }} object provided by the DOM lists all the files selected by the user, each specified as a {{ domxref("File") }} object. You can determine how many files the user selected by checking the value of the file list's length attribute:

+
var numFiles = files.length;
+

Individual {{ domxref("File") }} objects can be retrieved by simply accessing the list as an array:

+
for (var i = 0, numFiles = files.length; i < numFiles; i++) {
+  var file = files[i];
+  ..
+}
+
+

This loop iterates over all the files in the file list.

+

There are three attributes provided by the {{ domxref("File") }} object that contain useful information about the file.

+
+
+ name
+
+ The file's name as a read-only string. This is just the file name, and does not include any path information.
+
+ size
+
+ The size of the file in bytes as a read-only 64-bit integer.
+
+ type
+
+ The MIME type of the file as a read-only string, or "" if the type couldn't be determined.
+
+

Example: Showing file(s) size

+

The following example shows a possible use of the size property:

+
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8">
+<title>File(s) size</title>
+<script>
+function updateSize() {
+  var nBytes = 0,
+      oFiles = document.getElementById("uploadInput").files,
+      nFiles = oFiles.length;
+  for (var nFileId = 0; nFileId < nFiles; nFileId++) {
+    nBytes += oFiles[nFileId].size;
+  }
+  var sOutput = nBytes + " bytes";
+  // optional code for multiples approximation
+  for (var aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
+    sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)";
+  }
+  // end of optional code
+  document.getElementById("fileNum").innerHTML = nFiles;
+  document.getElementById("fileSize").innerHTML = sOutput;
+}
+</script>
+</head>
+
+<body onload="updateSize();">
+<form name="uploadForm">
+<p><input id="uploadInput" type="file" name="myFiles" onchange="updateSize();" multiple> selected files: <span id="fileNum">0</span>; total size: <span id="fileSize">0</span></p>
+<p><input type="submit" value="Send file"></p>
+</form>
+</body>
+</html>
+
+

Example: Showing thumbnails of user-selected images

+

Let's say you're developing the next great photo-sharing web site, and want to use HTML5 to display thumbnail previews of images before the user actually uploads them. Simply establish your input element or drop zone as discussed previously, and have them call a function such as the handleFiles() function below.

+
function handleFiles(files) {
+  for (var i = 0; i < files.length; i++) {
+    var file = files[i];
+    var imageType = /image.*/;
+
+    if (!file.type.match(imageType)) {
+      continue;
+    }
+
+    var img = document.createElement("img");
+    img.classList.add("obj");
+    img.file = file;
+    preview.appendChild(img);
+
+    var reader = new FileReader();
+    reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
+    reader.readAsDataURL(file);
+  }
+}
+
+

Here our loop handling the user-selected files looks at each file's type attribute to see if it's an image file (by doing a regular expression match on the string "image.*"). For each file that is an image, we create a new img element. CSS can be used to establish any pretty borders, shadows, and to specify the size of the image, so that doesn't even need to be done here.

+

Each image has the CSS class obj added to it, to make them easy to find in the DOM tree. We also add a file attribute to each image specifying the {{ domxref("File") }} for the image; this will let us fetch the images for actually uploading later. Finally, we use {{ domxref("Node.appendChild()") }} to add the new thumbnail to the preview area of our document.

+

Then we establish the {{ domxref("FileReader") }} to handle actually asynchronously loading the image and attaching it to the img element. After creating the new FileReader object, we set up its onload function, then call readAsDataURL() to start the read operation in the background. When the entire contents of the image file are loaded, they are converted into a data: URL, which is passed to the onload callback. Our implementation of this routine simply sets the img element's src attribute to the loaded image, which results in the image appearing in the thumbnail on the user's screen.

+

Example: Using object URLs to display images

+

This example uses object URLs to display image thumbnails. In addition, it displays other file information including their names and sizes. You can view the example live.

+

The HTML that presents the interface looks like this:

+
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
+<a href="#" id="fileSelect">Select some files</a>
+<div id="fileList">
+  <p>No files selected!</p>
+</div>
+
+

This establishes our file {{ HTMLElement("input") }} element, as well as a link that invokes the file picker, since we keep the file input hidden to prevent that less-than-attractive UI from being displayed. This is explained above in the section {{ anch("Using hidden file input elements using the click() method") }}, as is the method that invokes the file picker.

+

The handleFiles() method follows:

+
window.URL = window.URL || window.webkitURL;
+
+var fileSelect = document.getElementById("fileSelect"),
+    fileElem = document.getElementById("fileElem"),
+    fileList = document.getElementById("fileList");
+
+fileSelect.addEventListener("click", function (e) {
+  if (fileElem) {
+    fileElem.click();
+  }
+  e.preventDefault(); // prevent navigation to "#"
+}, false);
+
+function handleFiles(files) {
+  if (!files.length) {
+    fileList.innerHTML = "<p>No files selected!</p>";
+  } else {
+    var list = document.createElement("ul");
+    for (var i = 0; i < files.length; i++) {
+      var li = document.createElement("li");
+      list.appendChild(li);
+
+      var img = document.createElement("img");
+      img.src = window.URL.createObjectURL(files[i]);
+      img.height = 60;
+      img.onload = function(e) {
+        window.URL.revokeObjectURL(this.src);
+      }
+      li.appendChild(img);
+
+      var info = document.createElement("span");
+      info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
+      li.appendChild(info);
+    }
+    fileList.appendChild(list);
+  }
+}
+
+

This starts by fetching the URL of the {{ HTMLElement("div") }} with the ID fileList. This is the block into which we'll insert out file list, including thumbmails.

+

If the {{ domxref("FileList") }} object passed to handleFiles() is null, we simply set the inner HTML of the block to display "No files selected!". Otherwise, we start building our file list, as follows:

+
    +
  1. A new unordered list ({{ HTMLElement("ul") }}) element is created.
  2. +
  3. The new list element is inserted into the {{ HTMLElement("div") }} block by calling its {{ domxref("element.appendChild()") }} method.
  4. +
  5. For each {{ domxref("File") }} in the {{ domxref("FileList") }} represented by files: +
      +
    1. Create a new list item ({{ HTMLElement("li") }}) element and insert it into the list.
    2. +
    3. Create a new image ({{ HTMLElement("img") }}) element.
    4. +
    5. Set the image's source to a new object URL representing the file, using {{ domxref("window.URL.createObjectURL()") }} to create the blob URL.
    6. +
    7. Set the image's height to 60 pixels.
    8. +
    9. Set up the image's load event handler to release the object URL, since it's no longer needed once the image has been loaded. This is done by calling the {{ domxref("window.URL.revokeObjectURL()") }} method, passing in the object URL string as specified by img.src.
    10. +
    11. Append the new list item to the list.
    12. +
    +
  6. +
+

Example: Uploading a user-selected file

+

Another thing you might want to do is let the user upload the selected file or files (such as the images selected using the previous example) to a server. This can be done asynchronously very easily.

+

Creating the upload tasks

+

Continuing with the code that builds the thumbnails in the previous example, recall that every thumbnail image is in the CSS class obj, with the corresponding {{ domxref("File") }} attached in a file attribute. This lets us very easily select all the images the user has chosen for uploading using {{ domxref("Document.querySelectorAll()") }}, like this:

+
function sendFiles() {
+  var imgs = document.querySelectorAll(".obj");
+
+  for (var i = 0; i < imgs.length; i++) {
+    new FileUpload(imgs[i], imgs[i].file);
+  }
+}
+
+

Line 2 creates an array, called imgs, of all the elements in the document with the CSS class obj. In our case, these will be all the image thumbnails. Once we have that list, it's trivial to go through the list, creating a new FileUpload instance for each. Each of these handles uploading the corresponding file.

+

Handling the upload process for a file

+

The FileUpload function accepts two inputs: an image element and a file from which to read the image data.

+
function FileUpload(img, file) {
+  var reader = new FileReader();
+  this.ctrl = createThrobber(img);
+  var xhr = new XMLHttpRequest();
+  this.xhr = xhr;
+
+  var self = this;
+  this.xhr.upload.addEventListener("progress", function(e) {
+        if (e.lengthComputable) {
+          var percentage = Math.round((e.loaded * 100) / e.total);
+          self.ctrl.update(percentage);
+        }
+      }, false);
+
+  xhr.upload.addEventListener("load", function(e){
+          self.ctrl.update(100);
+          var canvas = self.ctrl.ctx.canvas;
+          canvas.parentNode.removeChild(canvas);
+      }, false);
+  xhr.open("POST", "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php");
+  xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
+  reader.onload = function(evt) {
+    xhr.sendAsBinary(evt.target.result);
+  };
+  reader.readAsBinaryString(file);
+}
+
+

The FileUpload() function shown above creates a throbber, which is used to display progress information, then creates an {{ domxref("XMLHttpRequest") }} to handle uploading the data.

+

Before actually transferring the data, several preparatory steps are taken:

+
    +
  1. The XMLHttpRequest's upload progress listener is set to update the throbber with new percentage information, so that as the upload progresses, the throbber will be updated based on the latest information.
  2. +
  3. The XMLHttpRequest's upload load event handler is set to update the throbber with 100% as the progress information (to ensure the progress indicator actually reaches 100%, in case of granularity quirks during the process). It then removes the throbber, since it's no longer needed. This causes the throbber to disappear once the upload is complete.
  4. +
  5. The request to upload the image file is opened by calling XMLHttpRequest's open() method to start generating a POST request.
  6. +
  7. The MIME type for the upload is set by calling the XMLHttpRequest function overrideMimeType(). In this case, we're using a generic MIME type; you may or may not need to set the MIME type at all, depending on your use case.
  8. +
  9. The FileReader object is used to convert the file to a binary string.
  10. +
  11. Finally, when the content is loaded the XMLHttpRequest function sendAsBinary() is called to upload the file's content.
  12. +
+

Handling the upload process for a file, asynchronously

+
<?php
+if (isset($_FILES['myFile'])) {
+    // Example:
+    move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
+    exit;
+}
+?><!DOCTYPE html>
+<html>
+<head>
+    <title>dnd binary upload</title>
+    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+    <script type="text/javascript">
+        function sendFile(file) {
+            var uri = "/index.php";
+            var xhr = new XMLHttpRequest();
+            var fd = new FormData();
+
+            xhr.open("POST", uri, true);
+            xhr.onreadystatechange = function() {
+                if (xhr.readyState == 4 && xhr.status == 200) {
+                    // Handle response.
+                    alert(xhr.responseText); // handle response.
+                }
+            };
+            fd.append('myFile', file);
+            // Initiate a multipart/form-data upload
+            xhr.send(fd);
+        }
+
+        window.onload = function() {
+            var dropzone = document.getElementById("dropzone");
+            dropzone.ondragover = dropzone.ondragenter = function(event) {
+                event.stopPropagation();
+                event.preventDefault();
+            }
+
+            dropzone.ondrop = function(event) {
+                event.stopPropagation();
+                event.preventDefault();
+
+                var filesArray = event.dataTransfer.files;
+                for (var i=0; i<filesArray.length; i++) {
+                    sendFile(filesArray[i]);
+                }
+            }
+    </script>
+</head>
+<body>
+    <div>
+        <div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
+    </div>
+</body>
+</html>
+
+

See also

+ +

{{ HTML5ArticleTOC() }}

+

{{ languages( { "zh-cn": "zh-cn/Using_files_from_web_applications", "ja": "ja/Using_files_from_web_applications" } ) }}

diff --git a/files/pt-br/web/api/filelist/index.html b/files/pt-br/web/api/filelist/index.html new file mode 100644 index 0000000000..3c5e32b6cd --- /dev/null +++ b/files/pt-br/web/api/filelist/index.html @@ -0,0 +1,134 @@ +--- +title: FileList +slug: Web/API/FileList +translation_of: Web/API/FileList +--- +
{{APIRef("File API")}}{{gecko_minversion_header("1.9")}}
+ +

Um objeto desse tipo é retornado pela propriedade files do elemento HTML {{HTMLElement("input")}}; isso permite acessar a lista de arquivos selecionados com o elemento <input type="file">. Também é usado para uma lista de arquivos soltos no conteúdo web usando a API drag and drop; consulte o objeto DataTransfer para detalhes de seu uso.

+ +
+

Nota: Antes do {{Gecko("1.9.2")}}, o elemento input suportava apenas um arquivo selecionado por vez, ou seja, o array FileList conteria apenas um arquivo. A partir do {{Gecko("1.9.2")}}, se o atributo multiple do elemento for definido, FileList pode conter múltiplos arquivos.

+
+ +

Utilizando a lista de arquivos

+ +

Todo elemento <input> possui um array files que permite o acesso aos seus arquivos. Por exemplo, se o HTML inclui o seguinte elemento:

+ +
<input id="fileItem" type="file">
+
+ +

O código a seguir acessa o primeiro elemento da lista de arquivos como um objeto File:

+ +
var file = document.getElementById('fileItem').files[0];
+
+ +

Visão geral dos métodos

+ + + + + + + +
File item(index);
+ +

Propriedades

+ + + + + + + + + + + + + + +
AtributoTipoDescrição
lengthintegerValor somente-leitura que indica o número de arquivos na lista.
+ +

Métodos

+ +

item()

+ +

Retorna um objeto File representando o arquivo no índice especificado na lista.

+ +
 File item(
+   index
+ );
+
+ +
Parâmetros
+ +
+
index
+
O índice (baseado em zero) do arquivo a ser recuperado da lista.
+
+ +
Valor de retorno
+ +

O objeto File representando o arquivo requisitado.

+ +

Exemplo

+ +

Este exemplo itera por todos os arquivos selecionados pelo usuário em um elemento input:

+ +
// fileInput é um elemento HTML input: <input type="file" id="myfileinput" multiple>
+var fileInput = document.getElementById("myfileinput");
+
+// files é um objeto FileList (similar ao NodeList)
+var files = fileInput.files;
+var file;
+
+// percorre os arquivos
+for (var i = 0; i < files.length; i++) {
+
+    // obtém o item
+    file = files.item(i);
+    // ou
+    file = files[i];
+
+    alert(file.name);
+}
+
+ +

A seguir, um exemplo completo.

+ +
<!DOCTYPE HTML>
+<html>
+
+<head>
+</head>
+
+<body>
+<!--multiple é definido para que múltiplos arquivos possam ser selecionados-->
+
+<input id="myfiles" multiple type="file">
+
+</body>
+
+<script>
+var puxarArquivos = function() {
+    var fileInput = document.querySelector("#myfiles");
+    var files = fileInput.files;
+
+    for (var i = 0; i < files.length; i++) {
+        var file = files[i];
+        alert(file.name);
+    }
+}
+
+// seta o 'onchange' do elemento input para chamar a função puxarArquivos
+document.querySelector("#myfiles").onchange = puxarArquivos;
+</script>
+
+</html>
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/filereader/filereader/index.html b/files/pt-br/web/api/filereader/filereader/index.html new file mode 100644 index 0000000000..49b3bd389e --- /dev/null +++ b/files/pt-br/web/api/filereader/filereader/index.html @@ -0,0 +1,54 @@ +--- +title: FileReader() +slug: Web/API/FileReader/FileReader +translation_of: Web/API/FileReader/FileReader +--- +

O construtor FileReader() cria um novo FileReader.

+ +

Para mais detalhes de como usar o FileReader, veja Using files from web applications.

+ +

Sintaxe

+ +
var reader = new FileReader();
+ +

Parâmetros

+ +

Nenhum.

+ +

Exemplo

+ +

O seguinte trecho de código ilustra a criação de um objeto FileReader usando o construtor FileReader() e depois utilizando o objeto:

+ +
function printFile(file) {
+  var reader = new FileReader();
+  reader.onload = function(evt) {
+    console.log(evt.target.result);
+  };
+  reader.readAsText(file);
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('File API')}}{{Spec2('File API')}}Initial definition
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/filereader/index.html b/files/pt-br/web/api/filereader/index.html new file mode 100644 index 0000000000..772159fd36 --- /dev/null +++ b/files/pt-br/web/api/filereader/index.html @@ -0,0 +1,162 @@ +--- +title: FileReader +slug: Web/API/FileReader +translation_of: Web/API/FileReader +--- +

{{ APIRef("File API")}}

+ +

Resumo

+ +

O objeto FileReader permite aplicações web ler assincronamente o conteúdo dos arquivos (ou buffers de dados puros) do computador do usuário, utilizando o objeto {{ domxref("File") }} ou {{ domxref("Blob") }} para especificar o arquivo ou os dados a serem lidos.

+ +

Objetos File podem ser obtidos a partir de um objeto {{ domxref("FileList") }} retornado como resultado da seleção de um usuário utilizando um elemento {{ HTMLElement("input") }}, a partir de uma operação de drag and drop DataTransfer, ou a partir de um mozGetAsFile() da api {{ domxref("HTMLCanvasElement") }}.

+ +

Construtor

+ +
FileReader FileReader();
+ +

Veja Using files from web applications para detalhes e exemplos.

+ +

Propriedades

+ +
+
{{domxref("FileReader.error")}} {{readonlyinline}}
+
Um {{domxref("DOMError")}} representa o erro que ocorreu durante a leitura do arquivo.
+
{{domxref("FileReader.readyState")}} {{readonlyinline}}
+
Um número indicando o estado do FileReader. Este poderá ser um dos seguintes estados {{ anch("State constants") }}.
+
{{domxref("FileReader.result")}} {{readonlyinline}}
+
O conteúdo do arquivo. Esta propriedade é válida apenas após a operação de leitura estar completa, e o formato dos dados dependem de qual método foi usado para iniciar a operação de leitura.
+
+ +

Manipuladores de eventos

+ +
+
{{domxref("FileReader.onabort")}}
+
Um manipulador para o evento {{event("abort")}}. Este evento é chamado cada vez que a operação de leitura é abortada.
+
{{domxref("FileReader.onerror")}}
+
Um manipulador para o evento {{event("error")}}. Este evento é chamado cada vez que a operação de leitura encontra um erro.
+
{{domxref("FileReader.onload")}}
+
Um manipulador para o evento {{event("load")}}. Este evento é chamado cada vez que a operação de leitura é completada com sucesso.
+
{{domxref("FileReader.onloadstart")}}
+
Um manipulador para o evento {{event("loadstart")}}. Este evento é chamado cada vez que a leitura começa.
+
{{domxref("FileReader.onloadend")}}
+
Um manipulador para o evento {{event("loadend")}}. Este evento é chamado cada vez que a operação de leitura é completada (tanto em caso de sucesso quanto de erro).
+
{{domxref("FileReader.onprogress")}}
+
Um manipulador para o evento {{event("progress")}}. Este evento é chamado durante a leitura do conteúdo de {{domxref("Blob")}}.
+
+ +
+

Nota: O FileReader herda de {{domxref("EventTarget")}}, todos estes eventos podem ser listados usando o método {{domxref("EventTarget.addEventListener()","addEventListener")}}.

+
+ +

Constantes de estado

+ + + +

Métodos

+ +
+
{{domxref("FileReader.abort()")}}
+
Aborta a operação de leitura. O retorno, no readyState será DONE.
+
{{domxref("FileReader.readAsArrayBuffer()")}} {{ gecko_minversion_inline("7.0") }}
+
Inicia a leitura do conteúdo do {{ domxref("Blob") }} espeficado, uma vez finalizado, o atributo result conterá um {{domxref("ArrayBuffer")}} representando os dados do arquivo.
+
{{domxref("FileReader.readAsBinaryString()")}}
+
Inicia a leitura do conteúdo do {{ domxref("Blob") }} especificado, uma vez finalizado, o atributo result conterá os dados raw binários do arquivo como  string.
+
{{domxref("FileReader.readAsDataURL()")}}
+
Inicia a leitura do conteúdo do {{ domxref("Blob") }} especificado, uma vez finalizado, o atributo result conterá um data: URL representando os dados do arquivo.
+
{{domxref("FileReader.readAsText()")}}
+
Inicia a leitura do conteúdo do {{ domxref("Blob") }} especificado, uma vez finalizado, o atributo result conterá o conteúdo do arquivo como string de  texto.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('File API','#FileReader-interface','FileReader')}}{{Spec2('File API')}}Definição inicial.
+ +

Compatibilidade

+ +

{{ 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
+
+ +

Notas de implementações

+ + + +

Notas específicas para Gecko

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/filereader/onload/index.html b/files/pt-br/web/api/filereader/onload/index.html new file mode 100644 index 0000000000..53b5774e88 --- /dev/null +++ b/files/pt-br/web/api/filereader/onload/index.html @@ -0,0 +1,29 @@ +--- +title: FileReader.onload +slug: Web/API/FileReader/onload +tags: + - Arquivo + - Event Handler + - FileReader + - Manipulador de eventos + - Propriedade +translation_of: Web/API/FileReader/onload +--- +

{{APIRef}}

+ +

A propriedade FileReader.onload contém um manipulador de eventos (event handler) executado quando o evento de carregamento ({{event('load')}})  é ativado, quando o conteúdo lido com  readAsArrayBuffer, readAsBinaryString, readAsDataURL ou readAsText fica disponível.

+ +

Exemplo

+ +
// Callback de um <input type="file" onchange="onChange(event)">
+function onChange(event) {
+  var file = event.target.files[0];
+  var reader = new FileReader();
+  reader.onload = function(event) {
+    // O arquivo de texto será impresso aqui
+    console.log(event.target.result)
+  };
+
+  reader.readAsText(file);
+}
+
diff --git a/files/pt-br/web/api/filereader/readasarraybuffer/index.html b/files/pt-br/web/api/filereader/readasarraybuffer/index.html new file mode 100644 index 0000000000..ed94bccf4b --- /dev/null +++ b/files/pt-br/web/api/filereader/readasarraybuffer/index.html @@ -0,0 +1,107 @@ +--- +title: FileReader.readAsArrayBuffer() +slug: Web/API/FileReader/readAsArrayBuffer +tags: + - API + - DOM + - File API + - FileReader + - Files + - Method + - Reference + - readAsArrayBuffer +translation_of: Web/API/FileReader/readAsArrayBuffer +--- +

{{APIRef("File API")}}

+ +

O método readAsArrayBuffer() do objeto {{domxref("FileReader")}} é utilizado para ler o conteúdo de um {{domxref("Blob")}} ou {{domxref("File")}} específico. Quando a operação de leitura é finalizada, o {{domxref("FileReader.readyState","readyState")}} torna-se DONE (finalizado), e o evento {{event("loadend")}} é acionado. Então, o atributo {{domxref("FileReader.result","result")}} retorna um {{domxref("ArrayBuffer")}} representando os dados do arquivo.

+ +

Sintaxe

+ +
instanceOfFileReader.readAsArrayBuffer(blob);
+ +

Parâmetros

+ +
+
blob
+
O {{domxref("Blob")}} ou {{domxref("File")}} que será lido.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("File API", "#readAsArrayBuffer", "FileReader.readAsArrayBuffer")}}{{Spec2("File API")}}Definição Inicial
+ +

Compatibilidade com Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Suporte Básico{{CompatGeckoDesktop("1.9.2")}}[1]710[2]12.02[3]6.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Suporte Básico3231011.56.1
+
+ +

[1] Antes da versão 2.0 beta 7 do Gecko (Firefox 4.0 beta 7), todos os parâmetros do {{domxref("Blob")}} abaixo eram parâmetros do {{domxref("File")}}; a atualização foi realizada pra corresponder corretamente à especificação. Antes da versão 13.0 do Gecko {{geckoRelease("13.0")}} A propriedade .error do FileReader retornava um objeto {{domxref("FileError")}}. Esta interface foi removida e FileReader.error agora retorna o objeto {{domxref("DOMError")}} como definido na última versão da documentação do FileAPI.

+ +

[2] IE9 possui File API Lab.

+ +

[3] Opera suporta parcialmente na versão 11.1.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/filereader/readasbinarystring/index.html b/files/pt-br/web/api/filereader/readasbinarystring/index.html new file mode 100644 index 0000000000..5d23087951 --- /dev/null +++ b/files/pt-br/web/api/filereader/readasbinarystring/index.html @@ -0,0 +1,120 @@ +--- +title: FileReader.readAsBinaryString() +slug: Web/API/FileReader/readAsBinaryString +tags: + - API + - API Arquivos + - Arquivos + - File API + - Métodos + - Referencias(2) +translation_of: Web/API/FileReader/readAsBinaryString +--- +
{{APIRef("File API")}} {{non-standard_header}}
+ +

O método readAsBinaryString é usado para iniciar a leitura do conteúdo de um {{domxref("Blob")}} especificado, ou {{domxref("File")}}. Quando a operação de leitura é finalizada, o {{domxref("FileReader.readyState","readyState")}} se torna "DONE", e o evento {{event("loadend")}} é acionado. Neste momento, o atributo {{domxref("FileReader.result","result")}} contém o dado binário bruto do arquivo.

+ +

Note que este método se tornou obsoleto desde 12 de Julho de 2012 Working Draft do W3C.

+ +

Sintaxe

+ +
instanciaDeFileReader.readAsBinaryString(blob);
+ +

Parametros

+ +
+
blob
+
O {{domxref("Blob")}} ou {{domxref("File")}} que deseja ler.
+
+ +

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

+ +

Este método foi removido dos padrões FileAPI {{domxref("FileReader.readAsArrayBuffer()")}} deve ser usado no lugar dele.

+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Suporte Básico{{CompatGeckoDesktop("1.9.2")}}[1]7{{CompatNo}}12.02[3]6.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Suporte Básico3231011.56.0
+
+ +

[1] Anteriormente ao Gecko 2.0 beta 7 (Firefox 4.0 beta 7), todos os parametros  {{domxref("Blob")}} inferiores eram parametros {{domxref("File")}}; Isso foi atualizado para combinar com as especifiações corretamente. Anteriormente ao Gecko 13.0 {{geckoRelease("13.0")}} a propriedade FileReader.error retornava um objeto {{domxref("FileError")}}. Essa interface foi removida e FileReader.error agora retorna o objeto domxref("DOMError")}} como foi definido no último draft do FileAPI.

+ +

[2] IE9 possui um File API Lab.

+ +

[3] Opera possui partial support in 11.1.

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/filereader/readasdataurl/index.html b/files/pt-br/web/api/filereader/readasdataurl/index.html new file mode 100644 index 0000000000..a922bf8bd0 --- /dev/null +++ b/files/pt-br/web/api/filereader/readasdataurl/index.html @@ -0,0 +1,111 @@ +--- +title: FileReader.readAsDataURL() +slug: Web/API/FileReader/readAsDataURL +tags: + - API + - File API + - Files + - Image Preview + - Method +translation_of: Web/API/FileReader/readAsDataURL +--- +

{{APIRef("File API")}}

+ +

O método readAsDataURL é usado para ler o conteúdo do tipo {{domxref("Blob")}} ou {{domxref("File")}}.
+ Quando a operação de leitura acaba, a flag {{domxref("FileReader.readyState","readyState")}} muda para DONE e o evento {{event("loadend")}} é disparado.
+ Então o atributo {{domxref("FileReader.result","result")}} irá conter a URL codificada em base64 do arquivo.

+ +

Sintaxe

+ +
instanceOfFileReader.readAsDataURL(blob);
+ +

Parametros

+ +
+
blob
+
O conteúdo do tipo {{domxref("Blob")}} ou {{domxref("File")}} que queremos ler.
+
+ +

Exemplo

+ +

HTML

+ +
<input type="file" onchange="previewFile()"><br>
+<img src="" height="200" alt="Prévia da imagem...">
+ +

JavaScript

+ +
function previewFile() {
+  var preview = document.querySelector('img');
+  var file    = document.querySelector('input[type=file]').files[0];
+  var reader  = new FileReader();
+
+  reader.onloadend = function () {
+    preview.src = reader.result;
+  }
+
+  if (file) {
+    reader.readAsDataURL(file);
+  } else {
+    preview.src = "";
+  }
+}
+ +

Demo

+ +

{{EmbedLiveSample("Example", "100%", 240)}}

+ +

Exemplo de leitura com múltiplos arquivos

+ +

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 do FileReader() não é suportado  por versões anteriores à 10 do Internet Explorer. Para uma maior compatibilidade você pode ver os exemplos prévia de imagem básica ou prévia de imagem avançada.
+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/FileReader","Specifications")}}

+ +

Compatibilidade

+ +

{{page("/pt-BR/docs/Web/API/FileReader","Browser compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/filereader/readastext/index.html b/files/pt-br/web/api/filereader/readastext/index.html new file mode 100644 index 0000000000..eb0f1582a7 --- /dev/null +++ b/files/pt-br/web/api/filereader/readastext/index.html @@ -0,0 +1,104 @@ +--- +title: FileReader.readAsText() +slug: Web/API/FileReader/readAsText +translation_of: Web/API/FileReader/readAsText +--- +
{{APIRef("File API")}}
+ +

O método readAsText é usado para ler conteúdos de um {{domxref("Blob")}} ou {{domxref("File")}} especificados. Quando a operação de leitura é concluida, o {{domxref("FileReader.readyState","readyState")}} é alterado para DONE, o {{event("loadend")}} é disparado, e o atributo {{domxref("FileReader.result","result")}} passa a conter o conteúdo do arquivo como um texto em formato string.

+ +

Sintaxe

+ +
instanceOfFileReader.readAsText(blob[, encoding]);
+ +

Parâmetros

+ +
+
blob
+
O {{domxref("Blob")}} ou {{domxref("File")}} a ser lido.
+
encoding {{optional_inline}}
+
Uma string especificando a codificação a ser usada para o dado retornado. Por padrão, UTF-8 é assumido se o parâmetro não for especificado.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("File API", "#FileReader-interface", "FileReader")}}{{Spec2("File API")}}Definição inicial
+ +

Compatibilidade em navedadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Suporte básico{{CompatGeckoDesktop("1.9.2")}}[1]7{{CompatVersionUnknown}}10[2]12.02[3]6.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Suporte básico323{{CompatVersionUnknown}}1011.56.1
+
+ +

[1] Antes do Gecko 2.0 beta 7 (Firefox 4.0 beta 7), todos os parâmetros {{domxref("Blob")}} abaixo eram parâmetros de {{domxref("File")}}; isso desde então foi atualizado para coincidir com a especificação corretamente. Antes do Gecko 13.0 {{geckoRelease("13.0")}} a propriedade FileReader.error retornava um objeto {{domxref("FileError")}}. Essa interface foi removida e agora FileReader.error está retornando um objeto {{domxref("DOMError")}} conforme definido no último rascunho da FileAPI.

+ +

[2] IE9 tem uma File API Lab.

+ +

[3] Opera tem suporte parcial em 11.1.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/formdata/append/index.html b/files/pt-br/web/api/formdata/append/index.html new file mode 100644 index 0000000000..d181310952 --- /dev/null +++ b/files/pt-br/web/api/formdata/append/index.html @@ -0,0 +1,177 @@ +--- +title: FormData.append() +slug: Web/API/FormData/append +translation_of: Web/API/FormData/append +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O método append()  da Interface {{domxref("FormData")}}  adiciona um novo valor dentro de uma chave existente dentro do objeto FormData ou  adiciona a  chave caso ainda não exista.

+ +

A diferença entre  {{domxref("FormData.set")}} e append() é que se uma  chave específica já exista, {{domxref("FormData.set")}} irá substituir o valor existente com um novo valor, já o append() irá adicionar um novo valor no fim do conjunto de valores.

+ +
+

Nota: Este  metodo esta desponivel no Web Workers.

+
+ +

Sintaxe

+ +

Existe duas versoes deste metodo: um de dois e um outro de tres:

+ +
formData.append(name, value);
+formData.append(name, value, filename);
+ +

Parametros

+ +
+
name
+
O nome do campo cujos dados estão contidas em value.
+
value
+
O valor deste campo . Nas duas versões este é a {{domxref("USVString")}}, ou  caso não seja , este é convertido em string. Na versão de tres parametros este pode ser {{domxref("Blob")}}, {{domxref("File")}}, ou  {{domxref("USVString")}}, de novo, caso nenhum deses forem especificados  este valor é convertido em uma string.
+
filename {{optional_inline}}
+
O filename reporta para o servidor (a {{domxref("USVString")}}), quando a {{domxref("Blob")}} ou {{domxref("File")}} é passado como o segundo parametro. O default filename para  {{domxref("Blob")}} o objecto é "blob".
+
+ +
+

Nota: Se espisificares  {{domxref("Blob")}} como a data append  para o objecto FormData , o filename a ser reportado para o servidor  no "Content-Disposition" header usado para mudar de browser em browser.

+
+ +

Retorna

+ +

Void.

+ +

Exemplo

+ +

As seguintes linhas criam um Objecto FormData vazio:

+ +
var formData = new FormData(); // Corrente vazio
+ +

Podes adicionar chaves/valores pares para usar (domxref("FormData.append")}}:

+ +
formData.append('username', 'Chris');
+formData.append('userpic', myFileInput.files[0], 'chris.jpg');
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesEstatoComentario
{{SpecName('XMLHttpRequest','#dom-formdata-append','append()')}}{{Spec2('Fetch')}} 
+ +

Compatibilidade do Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracteristicasChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Basico7+{{CompatGeckoDesktop("2.0")}}10+12+5+
append com filename{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponivel para Desenvolvedores Web{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracteristicasAndroidChrome para AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}1.0.1{{CompatUnknown}} +

12+

+
{{CompatUnknown}}
append com filename{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}}1.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponivel para Desenvolvedores Web{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+

Nota: XHR em  Android 4.0 envia conteudo vazio  para FormData com blob.

+
+ +

Notas Gecko

+ +

Antis do Gecko 7.0 {{geckoRelease("7.0")}}, se especificares {{domxref("Blob")}} como a conteudo a ser  adicionado ao objecto, o filename reportado no "Content-Disposition" HTTP header era um string vazio; este resulta em  erros sendo reportados por alguns servidores. Começando com Gecko 7.0, o filename "blob" é enviado.

+ +

Veja Tambem

+ + diff --git a/files/pt-br/web/api/formdata/delete/index.html b/files/pt-br/web/api/formdata/delete/index.html new file mode 100644 index 0000000000..042c16f083 --- /dev/null +++ b/files/pt-br/web/api/formdata/delete/index.html @@ -0,0 +1,138 @@ +--- +title: FormData.delete() +slug: Web/API/FormData/delete +translation_of: Web/API/FormData/delete +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O metodo delete() da  interface {{domxref("FormData")}} deleta uma chave/valor pares do Objecto FormData .

+ +
+

Nota: Este metodo esta Disponivel em Web Workers.

+
+ +

Sintaxe

+ +
formData.delete(name);
+ +

Parametros

+ +
+
name
+
O name da chave que desejas apagar.
+
+ +

Retorna

+ +

Void.

+ +

Exemplo

+ +

Esta linha cria um objecto FormData vazio e subistitui com a chave/valor pares de  form:

+ +
var formData = new FormData(myForm);
+ +

Podes deletar chave/valor pares usando delete():

+ +
formData.delete('username');
+
+ +

Specificasões

+ + + + + + + + + + + + + + +
SpecificasõesStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata-delete','delete()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Compatibilidade do Browser 

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CarracteristicasChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Basico{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
Disponivel em Web Workes{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracteristicasAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Basico{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}} +

{{CompatVersionUnknown}}

+
{{CompatNo}}
Disponivel em web workers{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +

Veja Tambem

+ + diff --git a/files/pt-br/web/api/formdata/entries/index.html b/files/pt-br/web/api/formdata/entries/index.html new file mode 100644 index 0000000000..911c269074 --- /dev/null +++ b/files/pt-br/web/api/formdata/entries/index.html @@ -0,0 +1,77 @@ +--- +title: FormData.entries() +slug: Web/API/FormData/entries +tags: + - API + - FormData + - Iterador + - Referencia + - XMLHttpRequest API + - metodo +translation_of: Web/API/FormData/entries +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O método FormData.entries() retorna um {{jsxref("Iteration_protocols",'iterator')}} permitindo percorrer todos os valores de chave/valor contidos nesse objeto. A chave de cada par é um objeto {{domxref("USVString")}}; o valor é {{domxref("USVString")}}, ou um {{domxref("Blob")}}.

+ +
+

Note: This method is available in Web Workers.

+
+ +

Sintaxe

+ +
formData.entries();
+ +

Valor retornado

+ +

Retorna um {{jsxref("Iteration_protocols","iterator")}}.

+ +

Exemplo

+ +
// Criação de um objeto teste de FormData
+var formData = new FormData();
+formData.append('key1', 'value1');
+formData.append('key2', 'value2');
+
+// Exibição dos valores chave/valor
+for(var pair of formData.entries()) {
+   console.log(pair[0]+ ', '+ pair[1]);
+}
+
+ +

O resultado é:

+ +
key1, value1
+key2, value2
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest','#dom-formdata','entries() (as iterator<>)')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.FormData.entries")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/formdata/formdata/index.html b/files/pt-br/web/api/formdata/formdata/index.html new file mode 100644 index 0000000000..2202cac454 --- /dev/null +++ b/files/pt-br/web/api/formdata/formdata/index.html @@ -0,0 +1,184 @@ +--- +title: FormData() +slug: Web/API/FormData/FormData +translation_of: Web/API/FormData/FormData +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O FormData() construtor cria um novo objeto {{domxref("FormData")}}.

+ +
+

Nota: Este recurso está disponível em Web Workers.

+
+ +

Sintaxe

+ +
var formData = new FormData(form)
+ +

Parâmetros

+ +
+
form {{optional_inline}}
+
Um elemento HTML {{HTMLElement("form")}} — quando especifico, o objeto {{domxref("FormData")}} será preenchido com as chaves/valores atuais do formulário usando a propriedade name de cada elemento para as chaves e seu valor enviado para os valores. Também condificará conteúdo de entrada do arquivo.
+
+ +

Exemplo

+ +

A linha a seguir cria um objeto FormData vázio:

+ +
var formData = new FormData(); // Currently empty
+ +

Você poderia adicionar uma chave/valor usando {{domxref("FormData.append")}}:

+ +
formData.append('username', 'Chris');
+
+ +

Ou você pode especificicar o opcional form argument ao criar o objeto FormData, para o popular com valores de forma especifica:

+ +
<form id="myForm" name="myForm">
+  <div>
+    <label for="username">Enter name:</label>
+    <input type="text" id="username" name="username">
+  </div>
+  <div>
+    <label for="useracc">Enter account number:</label>
+    <input type="text" id="useracc" name="useracc">
+  </div>
+  <div>
+    <label for="userfile">Upload file:</label>
+    <input type="file" id="userfile" name="userfile">
+  </div>
+<input type="submit" value="Submit!">
+</form>
+
+ +
+

Nota: Todos os elementos de entrada têm um atributo 'name'. Para que possa acessar seus valores mais tarde.

+
+ +
var myForm = document.getElementById('myForm');
+formData = new FormData(myForm);
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest','#dom-formdata','FormData()')}}{{Spec2('XMLHttpRequest')}}Definição inicial
+ +

Compatibilidade dos navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7{{CompatGeckoDesktop("2.0")}}10125
append with filename{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
available in web workers{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}} +

12

+
{{CompatUnknown}}
append with filename{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("22.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in web workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("39.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ +

 

+ +
+

Note: XHR in Android 4.0 sends empty content for FormData with blob.

+
+ +

Gecko notes

+ +

Prior to Gecko 7.0 {{geckoRelease("7.0")}}, if you specified a {{domxref("Blob")}} as the data to append to the object, the filename reported in the "Content-Disposition" HTTP header was an empty string; this resulted in errors being reported by some servers. Starting in Gecko 7.0, the filename "blob" is sent.

+ +

Veja também

+ + +
diff --git a/files/pt-br/web/api/formdata/get/index.html b/files/pt-br/web/api/formdata/get/index.html new file mode 100644 index 0000000000..6e4c11caad --- /dev/null +++ b/files/pt-br/web/api/formdata/get/index.html @@ -0,0 +1,142 @@ +--- +title: FormData.get() +slug: Web/API/FormData/get +translation_of: Web/API/FormData/get +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O método get() da interface {{domxref("FormData")}} retorna o primeiro valor associado com a chave fornecida de um objeto do tipo FormData.

+ +
+

Nota: Este método está disponível em Web Workers.

+
+ +

Sintaxe

+ +
formData.get(nome);
+ +

Parâmetros

+ +
+
nome
+
Um {{domxref("USVString")}} representando o nome da chave que queira retornar.
+
+ +

Retorno

+ +

Um {{domxref("FormDataEntryValue")}} contendo o valor.

+ +

Exemplo

+ +

A linha abaixo cria um objeto vazio do tipo FormData.

+ +
var formData = new FormData();
+ +

Se adicionarmos dois valores usuario_nome usando {{domxref("FormData.append")}}:

+ +
formData.append('usuario_nome', 'Sabrina');
+formData.append('usuario_nome', 'Antônio');
+ +

A função get() abaixo apenas irá retornar o primeiro valor usuario_nome incluido:

+ +
formData.get('usuario_nome'); // Retorna "Sabrina"
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest','#dom-formdata-get','get()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatNo}}{{CompatGeckoDesktop('39.0')}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
Available in web workers{{CompatNo}}{{CompatGeckoDesktop('39.0')}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}} +

{{CompatVersionUnknown}}

+
{{CompatNo}}
Available in web workers{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/formdata/getall/index.html b/files/pt-br/web/api/formdata/getall/index.html new file mode 100644 index 0000000000..5a9b51611c --- /dev/null +++ b/files/pt-br/web/api/formdata/getall/index.html @@ -0,0 +1,74 @@ +--- +title: FormData.getAll() +slug: Web/API/FormData/getAll +translation_of: Web/API/FormData/getAll +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O metodo getAll() do {{domxref("FormData")}} retorna todos os valores associados com a chave dentro de um objeto FormData.

+ +
+

Nota: Este metodo esta disponivel no Web Workers.

+
+ +

Syntax

+ +
formData.getAll(name);
+ +

Parametros

+ +
+
nome
+
O {{domxref("USVString")}} representa o mome da chave que você quer pegar.
+
+ +

Retorno

+ +

Um array de {{domxref("FormDataEntryValue")}}s.

+ +

Examplo

+ +

A seguinte linha cria um objeto FormData vazio:

+ +
var formData = new FormData();
+ +

Se nos adicionarmos dois valores oara username {{domxref("FormData.append")}}:

+ +
formData.append('username', 'Chris');
+formData.append('username', 'Bob');
+ +

A seguinte função getAll() retornara um arrat com os valore dentro de username:

+ +
formData.getAll('username'); // Returns ["Chris", "Bob"]
+ +

Especificação

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata-getall','getAll()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Compatibilidade de Browsers

+ + + +

{{Compat("api.FormData.getAll")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/formdata/has/index.html b/files/pt-br/web/api/formdata/has/index.html new file mode 100644 index 0000000000..d9cdeff60b --- /dev/null +++ b/files/pt-br/web/api/formdata/has/index.html @@ -0,0 +1,81 @@ +--- +title: FormData.has() +slug: Web/API/FormData/has +tags: + - API + - FormData + - Referencia + - XHR + - XMLHttlRequest + - has + - metodo +translation_of: Web/API/FormData/has +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O método has() da interface {{domxref("FormData")}} retorna um booleano declarando se o objeto FormData contém uma certa chave.

+ +
+

Note: This method is available in Web Workers.

+
+ +

Sintaxe

+ +
formData.has(name);
+ +

Parâmetros

+ +
+
name
+
Uma {{domxref("USVString")}} que representa o nome da chave que você que testar.
+
+ +

Retorna

+ +

Um {{domxref("Boolean")}}.

+ +

Exemplo

+ +

A linha a seguir cria um objeto FormData vazio:

+ +
var formData = new FormData();
+ +

O trecho a seguir mostra os resultados de testar a existência de username no objeto FormData, antes e depois de acrescentar um valor de username no objeto usando {{domxref("FormData.append")}}:

+ +
formData.has('username'); // Retorna false
+formData.append('username', 'Chris');
+formData.has('username'); // Retorna true
+
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest','#dom-formdata-has','has()')}}{{Spec2('XMLHttpRequest')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("api.FormData.has")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/formdata/index.html b/files/pt-br/web/api/formdata/index.html new file mode 100644 index 0000000000..30ba7ccb6a --- /dev/null +++ b/files/pt-br/web/api/formdata/index.html @@ -0,0 +1,170 @@ +--- +title: FormData +slug: Web/API/FormData +translation_of: Web/API/FormData +--- +

{{APIRef("XMLHttpRequest")}}

+ +

A interface FormData fornece uma maneira fácil de construir um conjunto de pares chave/valor representando campos de um elemento form e seus valores, os quais podem ser facilmente enviados utilizado o método send() do XMLHttpRequest. Essa interface utiliza o mesmo formato que um form utilizaria se o tipo de codificação estivesse configurado como "multipart/form-data".

+ +

Um objeto FormData pode ser usado diretamente em uma estrutura {{jsxref("Statements/for...of", "for...of")}} em vez de {{domxref('FormData.entries()', 'entries()')}}: for (var p of myFormData) é o mesmo que for (var p of myFormData.entries()).

+ +
+

Nota: Esse recurso está disponível em https://developer.mozilla.org/pt-BR/docs/Web/API/Web_Workers_API

+
+ +

Construtor

+ +
+
{{domxref("FormData.FormData","FormData()")}}
+
Cria um novo objeto FormData.
+
+ +

Métodos

+ +
+
{{domxref("FormData.append")}}
+
Acrescenta um novo valor em uma chave existente dentro de um objeto FormData, ou adiciona a chave se ela ainda não existir.
+
{{domxref("FormData.delete")}}
+
Apaga um par chave/valor de um objeto FormData.
+
{{domxref("FormData.get")}}
+
Retorna o primeiro valor associado com uma dada chave de dentro de um objeto FormData.
+
{{domxref("FormData.getAll")}}
+
Retorna uma matriz de todos os valores associados a uma determinada chave de dentro de um FormData.
+
{{domxref("FormData.has")}}
+
Retorna um valor boleano indicando se um objeto FormData contém um certo par chave/valor.
+
{{domxref("FormData.set")}}
+
Define um novo valor para uma chave existente dentro de um objeto FormData, ou adiciona a chave/valor se ele ainda não existir.
+
+ +
+

Nota: Para ser claro, a diferença entre {{domxref("FormData.set()")}} e {{domxref("FormData.append()")}} é que, se a chave especificada não existir, {{domxref("FormData.set()")}} irá substituir o valor existente por um novo, enquanto {{domxref("FormData.append()")}} irá acrescentar um novo valor no final dos valores existentes. Veja as suas páginas dedicadas para código de exemplo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest','#interface-formdata','FormData')}}{{Spec2('XMLHttpRequest')}}FormData definido na especificação XHR
+ +

Compatibilidade com navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico7+{{CompatGeckoDesktop("2.0")}}10+12+5+
append com filename{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}10+{{CompatUnknown}}{{CompatUnknown}}
delete, get, getAll, has, setBehind Flag{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico3.0{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}1.0.1{{CompatUnknown}} +

12+

+
{{CompatUnknown}}
append com filename{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}}1.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
delete, get, getAll, has, set{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+

Nota: XHR in Android 4.0 envia conteúdo vazio para o FormData com blob.

+ +

Nota: Suporte do Chrome aos métodos que não seja append está atualmente atrás da bandeira "Enable Experimental Web Platform Features".

+
+ +

Notas da Gecko

+ +

Antes do Gecko 7.0 {{geckoRelease("7.0")}}, se você especificasse um {{domxref("Blob")}} como o dado a ser anexado ao objeto, o nome do arquivo relatado no cabeçalho HTTP "Content-Disposition" era uma string vazia; isso resultou em erros sendo relatados por alguns servidores. Começando em Gecko 7.0, o nome do arquivo "blob" é enviado.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/formdata/set/index.html b/files/pt-br/web/api/formdata/set/index.html new file mode 100644 index 0000000000..a6b7dccb69 --- /dev/null +++ b/files/pt-br/web/api/formdata/set/index.html @@ -0,0 +1,150 @@ +--- +title: FormData.set() +slug: Web/API/FormData/set +translation_of: Web/API/FormData/set +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O método set() da interface {{domxref("FormData")}} adiciona o novo valor para um chave existente em um objeto FormData, ou adicionar a combinação chave/valor caso ela não exista.

+ +

A diferença entre  set() e {{domxref("FormData.append")}} é que, se a chave especificada já existir, set() irá sobrescrever todos os valores existentes pelo novo valor, enquanto o {{domxref("FormData.append")}} apenas acrescenta o novo valor ao conjunto de valores existentes.

+ +
+

Nota: Esse método está disponível em Web Workers.

+
+ +

Sintaxe

+ +

Existem duas versões desse método: uma com dois e outra com três parâmetros:

+ +
formData.set(name, value);
+formData.set(name, value, filename);
+ +

Parâmetros

+ +
+
name
+
O nome do campo cujo dado está em value.
+
value
+
O valor do campo. Na versão de dois parâmetros, esse é um {{domxref("USVString")}}, e caso não seja, ele é convertido para uma string. Na versão de três parâmetros ele pode ser um {domxref("Blob")}}, {{domxref("File")}}, ou um {{domxref("USVString")}}. Se nenhum desses valores forem especificados, o valor será convertido para string.
+
filename {{optional_inline}}
+
O nome do arquivo a ser enviado (um {{domxref("USVString")}}), quando um {{domxref("Blob")}} ou um {{domxref("File")}} é passdo como o segundo parâmetro. O nome de arquivo padrão para objetos do tipo {{domxref("Blob")}} é "blob".
+
+ +
+

Nota: Se você especificar um {{domxref("Blob")}} como o dado a ser acrescentado ao objeto FormData, o nome do arquivo que será enviado para o servidor, enviado no atributo "Content-Disposition" no cabeçalho varia de navegador para navegador.

+
+ +

Exemplo

+ +

A linha a seguir cria um objeto FormData vazio:

+ +
var formData = new FormData(); // Currently empty
+ +

Você pode adicionar os pares chave/valor usando (domxref("FormData.set")}}:

+ +
formData.set('username', 'Chris');
+formData.set('userpic', myFileInput.files[0], 'chris.jpg');
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest','#dom-formdata-set','set()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Compatibilidade de navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatChrome(50.0)}}{{CompatGeckoDesktop("39.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
DIsponível para web workers{{CompatChrome(50.0)}}{{CompatGeckoDesktop("39.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Suporte básico{{CompatNo}}{{CompatChrome(50.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}} +

{{CompatNo}}

+
{{CompatNo}}{{CompatChrome(50.0)}}
DIsponível para web workers{{CompatNo}}{{CompatChrome(50.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(50.0)}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/fullscreenoptions/index.html b/files/pt-br/web/api/fullscreenoptions/index.html new file mode 100644 index 0000000000..9a85830521 --- /dev/null +++ b/files/pt-br/web/api/fullscreenoptions/index.html @@ -0,0 +1,29 @@ +--- +title: FullscreenOptions +slug: Web/API/FullscreenOptions +translation_of: Web/API/FullscreenOptions +--- +

{{APIRef("Fullscreen API")}}

+ +

O dicionário FullscreenOptions é usado para prover configurações quando chamado {{DOMxRef("Element.requestFullscreen", "requestFullscreen()")}} em um elemento para colocar este elmento em modo full-screen (tela inteira).

+ +

Propriedades

+ +
+
{{DOMxRef("FullscreenOptions.navigationUI", "navigationUI")}}{{Optional_Inline}}
+
Uma string controlando se deve ou não manter elementos da interface do usuário do navegador visíveis enquanto estiver no modo full-screen. O modo padrão, "auto", deixa que o navegador faça esta decisão.
+
+ +

Compatibilidade dos Navegadores

+ + + +

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

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/gamepad_api/index.html b/files/pt-br/web/api/gamepad_api/index.html new file mode 100644 index 0000000000..fe026468d8 --- /dev/null +++ b/files/pt-br/web/api/gamepad_api/index.html @@ -0,0 +1,90 @@ +--- +title: Gamepad API +slug: Web/API/Gamepad_API +translation_of: Web/API/Gamepad_API +--- +
{{DefaultAPISidebar("Gamepad API")}}
+ +

A Gamepad API é uma maneira dos desenvolvedores acessarem e responderem à sinais oriundos de gamepads e outros controladores de games de forma simples e consistente. A API contém três interfaces, dois eventos e uma função especialista, para responder aos gamepads sendo conectados e desconectados, e acessar outras informações sobre o próprio gamepad, e quais botões e outros controles estão sendo de fato passados.

+ +

Interfaces

+ +
+
Gamepad
+
Representa o gamepad/controlador conectado ao computador.
+
GamepadButton
+
Representa um botão num dos controles conectados.
+
GamepadEvent
+
O objeto de evento representando eventos disparados que são relacionados ao gamepad.
+
+ +

Experimental Gamepad extensions

+ +
+
GamepadHapticActuator
+
Representa o hardware no controlador designado à prover feedbacks táteis ao usuário (Se disponível), mais comumente um hardware de vibração.
+
GamepadPose
+
Representa a "localização" de um controle (ex. posição e orientação no espaço 3D) no caso de um controlador WebVR.
+
+ +

Veja também as extensões para a interface de Gamepad, para funcionalidades que permitem você acessar as informações acima.

+ +

Extensions to other interfaces

+ + + +
+
{{domxref("Navigator.getGamepads()")}}
+
Uma extensão para o objeto {{domxref("Navigator")}} que retorna um array  de objetos {{domxref("Gamepad")}}, um para cada controlador conectado.
+
+ +

Window events

+ +
+
{{domxref("Window.ongamepadconnected")}}
+
Representa um controlador de evento que irá rodar quando o gamepad é conectado (quando o evento {{event('gamepadconnected')}} for disparado).
+
{{domxref("Window.ongamepaddisconnected")}}
+
Representa um controlador de evento que irá rodar quando o gamepad é desconectado (quando o evento {{event('gamepaddisconnected')}} for disparado).
+
+ +

Guias e tutorias

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçõesEstatusComentários
{{SpecName("GamepadExtensions")}}{{Spec2("GamepadExtensions")}}Defines the {{anch("Experimental Gamepad extensions")}}.
{{SpecName("Gamepad", "", "The Gamepad API specification")}}{{Spec2("Gamepad")}}Initial definition
+ +

Compatibilidade de navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/geolocation/clearwatch/index.html b/files/pt-br/web/api/geolocation/clearwatch/index.html new file mode 100644 index 0000000000..2aaa1d6658 --- /dev/null +++ b/files/pt-br/web/api/geolocation/clearwatch/index.html @@ -0,0 +1,84 @@ +--- +title: Geolocation.clearWatch() +slug: Web/API/Geolocation/clearWatch +translation_of: Web/API/Geolocation/clearWatch +--- +

{{securecontext_header}}{{ APIref("Geolocation API") }}

+ +

O método Geolocation.clearWatch() é usado para cancelar o registro dos manipuladores de monitoramento de localização / erro instalados anteriormente usando {{domxref("Geolocation.watchPosition()")}}.

+ +

Syntax

+ +
navigator.geolocation.clearWatch(id);
+ +

Parameters

+ +
+
id
+
O número do ID retornado pelo método {{domxref("Geolocation.watchPosition()")}} ao instalar o manipulador que você deseja remover.
+
+ +

Exemplo

+ +
var id, target, option;
+
+function success(pos) {
+  var crd = pos.coords;
+
+  if (target.latitude === crd.latitude && target.longitude === crd.longitude) {
+    console.log('Congratulation, you reach the target');
+    navigator.geolocation.clearWatch(id);
+  }
+};
+
+function error(err) {
+  console.warn('ERROR(' + err.code + '): ' + err.message);
+};
+
+target = {
+  latitude : 0,
+  longitude: 0,
+}
+
+options = {
+  enableHighAccuracy: false,
+  timeout: 5000,
+  maximumAge: 0
+};
+
+id = navigator.geolocation.watchPosition(success, error, options);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Initial specification.
+ +

Compatibiliade dos Navegadores

+ + + +

{{Compat("api.Geolocation.clearWatch")}}

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/geolocation/getcurrentposition/index.html b/files/pt-br/web/api/geolocation/getcurrentposition/index.html new file mode 100644 index 0000000000..c5aa7919f6 --- /dev/null +++ b/files/pt-br/web/api/geolocation/getcurrentposition/index.html @@ -0,0 +1,127 @@ +--- +title: Geolocation.getCurrentPosition() +slug: Web/API/Geolocation/getCurrentPosition +translation_of: Web/API/Geolocation/getCurrentPosition +--- +

{{ APIRef("Geolocation API") }}

+ +

O método Geolocation.getCurrentPosition() é utilizado para capturar a posição atual do dispositivo.

+ +

Sintaxe

+ +
navigator.geolocation.getCurrentPosition(success, error, options)
+ +

Parâmetros

+ +
+
success
+
Uma função de retorno que captura um objeto {{domxref("Position")}} como seu parâmetro de entrada.
+
error {{optional_inline}}
+
Uma função de retorno opcional que captura um objeto {{domxref ("PositionError")}} como seu parâmetro de entrada.
+
options {{optional_inline}}
+
Um objeto opcional {{domxref("PositionOptions")}}.
+
+ +

Exemplo

+ +
var options = {
+  enableHighAccuracy: true,
+  timeout: 5000,
+  maximumAge: 0
+};
+
+function success(pos) {
+  var crd = pos.coords;
+
+  console.log('Sua posição atual é:');
+  console.log('Latitude : ' + crd.latitude);
+  console.log('Longitude: ' + crd.longitude);
+  console.log('Mais ou menos ' + crd.accuracy + ' metros.');
+};
+
+function error(err) {
+  console.warn('ERROR(' + err.code + '): ' + err.message);
+};
+
+navigator.geolocation.getCurrentPosition(success, error, options);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Especificação inicial.
+ + + +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico5{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removido no 15.0
+ Reintroduzido no 16.0
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/geolocation/index.html b/files/pt-br/web/api/geolocation/index.html new file mode 100644 index 0000000000..4ca0efa69a --- /dev/null +++ b/files/pt-br/web/api/geolocation/index.html @@ -0,0 +1,75 @@ +--- +title: Geolocation +slug: Web/API/Geolocation +tags: + - API + - Geolocalização + - Geolocation + - Geolocation API +translation_of: Web/API/Geolocation +--- +
{{APIRef("Geolocation API")}}
+ +

A interface Geolocation representa um objeto ábil de programaticamente obter a posição do aparelho. Dá ao conteúdo web acesso à localização do aparelho. Isto permite com que o website ou a aplicação ofereça resultados customizados baseados na localização do usuário.

+ +

Um objeto com tal interface é obtido utilizando a propriedade {{domxref("NavigatorGeolocation.geolocation")}} implementada pelo objeto {{domxref("Navigator")}}.

+ +
+

Nota: Por questões de segurança, quando uma página tenta obter acesso às informações de localização o usuário é notificado e uma requisição é feita para o mesmo fornecesser a permissão. Saiba que cada navegaor possui suas próprias políticas e métodos para requisitar tal permissão.

+
+ +

Propriedades

+ +

A interface Geolocation não implementa nem herda qualquer propriedade.

+ +

Métodos

+ +

A interface Geolocation não herda qualquer métodos.

+ +
+
{{domxref("Geolocation.getCurrentPosition()")}}
+
Determina a posição atual do aparelho e retorna um objeto {{domxref("Position")}} com os dados.
+
{{domxref("Geolocation.watchPosition()")}}
+
Retorna um valor long representando a nova função de callback estabelecida para ser invocada a qualquer momento que o localização do aparelho alterar-se.
+
{{domxref("Geolocation.clearWatch()")}}
+
Remove qualquer encarregado previamente instalado usando watchPosition().
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Especificação Inicial
+ +

Compatibilidade dos navegadores

+ +

 

+ + + +

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

+ +

 

+ +
 
+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/geolocation/watchposition/index.html b/files/pt-br/web/api/geolocation/watchposition/index.html new file mode 100644 index 0000000000..ffabaa2c76 --- /dev/null +++ b/files/pt-br/web/api/geolocation/watchposition/index.html @@ -0,0 +1,140 @@ +--- +title: Geolocation.watchPosition() +slug: Web/API/Geolocation/watchPosition +translation_of: Web/API/Geolocation/watchPosition +--- +

{{ APIref("Geolocation API") }}

+ +

O método Geolocation.watchPosition() é usado para registrar uma função manipuladora (handler function) que irá ser chamada automáticamente  cada vez que a posição no dispositivo mudar. Você pode, opcionalemnte, especificar uma função de retorno que manipulará qualquer erro.

+ +

Este método retorna um valor para o watch ID que pode ser usado para desregistrar o manipulador passando isto para o método {{domxref("Geolocation.clearWatch()")}}.

+ +

Síntaxe

+ +
id = navigator.geolocation.watchPosition(success, error, options)
+ +

Parâmetros

+ +
+
success
+
AUma função de retorno (callback) que pega um objeto {{domxref("Position")}} como parametro de entrada.  
+
error {{optional_inline}}
+
Uma função de retorno opcional que pega um objeto {{domxref("PositionError")}} como parametro de entrada.  
+
options {{optional_inline}}
+
Um objeto opcional {{domxref("PositionOptions")}}.
+
+ +

Exemplo

+ +
var id, target, options;
+
+function success(pos) {
+  var crd = pos.coords;
+
+  if (target.latitude === crd.latitude && target.longitude === crd.longitude) {
+    console.log('Parabéns, você alcançou o destino');
+    navigator.geolocation.clearWatch(id);
+  }
+}
+
+function error(err) {
+  console.warn('ERRO(' + err.code + '): ' + err.message);
+}
+
+target = {
+  latitude : 0,
+  longitude: 0
+};
+
+options = {
+  enableHighAccuracy: false,
+  timeout: 5000,
+  maximumAge: 0
+};
+
+id = navigator.geolocation.watchPosition(success, error, options);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Geolocation', '#watch-position', 'Geolocation.watchPosition()')}}{{Spec2('Geolocation')}}Especificação Inicial.
+ +

Compatibillidade de Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico5{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removido no 15.0
+ Reintroduzido no 16.0
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
+
+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/geolocationcoordinates/altitude/index.html b/files/pt-br/web/api/geolocationcoordinates/altitude/index.html new file mode 100644 index 0000000000..b4b7850bf9 --- /dev/null +++ b/files/pt-br/web/api/geolocationcoordinates/altitude/index.html @@ -0,0 +1,45 @@ +--- +title: Coordinates.altitude +slug: Web/API/GeolocationCoordinates/altitude +translation_of: Web/API/GeolocationCoordinates/altitude +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

A propriedade Coordinates.altitude somente-leitura é uma representação do tipo double da altitude em metros, relativo ao nível do mar. O valor é nulo se a implementação não pode fornecer este dado.

+ +

Sintaxe

+ +
alt = coordinates.altitude
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#altitude', 'Coordinates.altitude')}}{{Spec2('Geolocation')}}Initial definition
+ +

Compatibilidade entre os navegadores

+ + + +

{{Compat("api.Coordinates.altitude")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/geolocationcoordinates/index.html b/files/pt-br/web/api/geolocationcoordinates/index.html new file mode 100644 index 0000000000..2263a8117a --- /dev/null +++ b/files/pt-br/web/api/geolocationcoordinates/index.html @@ -0,0 +1,141 @@ +--- +title: Coordinates +slug: Web/API/GeolocationCoordinates +translation_of: Web/API/GeolocationCoordinates +--- +
+
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

Coordinates iinterface representa a posição e a altitude do dispositivo na Terra, bem como a precisão com que essas propriedades são calculadas.

+ +

Propriedades

+ +

A interface do Coordinates não herda nenhuma propiedade.

+ +
+
{{domxref("Coordinates.latitude")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um double representando a latitude da posição em graus decimais.
+
{{domxref("Coordinates.longitude")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um double representando a longitude da posição em graus decimais.
+
{{domxref("Coordinates.altitude")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um double representando a altitude da posição em metros, em relação ao nível do mar. Esse valor pode ser null se a implementação não puder fornecer os dados.
+
{{domxref("Coordinates.accuracy")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um double representação da precisão das propriedades em latitude e longitude, expressa em metros.
+
{{domxref("Coordinates.altitudeAccuracy")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um double representação da precisão da altitude expressa em metros. Esse valor pode ser null.
+
{{domxref("Coordinates.heading")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um double representação da direção na qual o dispositivo está viajando. Esse valor, especificado em graus, indica o quão longe do título verdadeiro do norte do dispositivo. 0 representam o verdadeiro norte e a direção é determinada no sentido horário (o que significa que o leste é 90graus e oeste é 270graus). Se speedé 0headingé NaNSe o dispositivo não conseguir fornecer headinginformações, esse valor é null.
+
{{domxref("Coordinates.speed")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um doublerepresentação da velocidade do dispositivo em metros por segundo. Esse valor pode ser null.
+
+ +

Métodos

+ +

A interface da Coordinates não implementa, nem herda nenhum método.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#coordinates', 'Coordinates')}}{{Spec2('Geolocation')}}Especificação inicial.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico5{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removed in 15.0
+ Reintroduced in 16.0
5
Apenas contexto seguro47{{CompatUnknown()}}{{CompatGeckoDesktop("55")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown()}}{{CompatUnknown()}}{{CompatVersionUnknown}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
Apenas contexto seguro{{CompatNo}}47{{CompatUnknown()}}{{CompatGeckoDesktop("55")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + +
+ + diff --git a/files/pt-br/web/api/geolocationposition/coords/index.html b/files/pt-br/web/api/geolocationposition/coords/index.html new file mode 100644 index 0000000000..d14cbc59a7 --- /dev/null +++ b/files/pt-br/web/api/geolocationposition/coords/index.html @@ -0,0 +1,116 @@ +--- +title: Position.coords +slug: Web/API/GeolocationPosition/coords +translation_of: Web/API/GeolocationPosition/coords +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

A propriedade Position.coords é somente leitura. É um objeto de {{domxref("Coordinates")}} que contém uma representação geográfica: a localização, que é a latitude e longitude na Terra, a altitude e a velocidade do objeto em questão. Também contempla a precisão da informação sobre estes valores.

+ +

Sintaxe

+ +
coord = position.coords
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Geolocation', '#coords', 'Position.coords')}}{{Spec2('Geolocation')}}Especificação inicial.
+ +

Compatibilidade com navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico5{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removido em 15.0
+ Reintroduzido em 16.0
5
Somente em contexto seguro47{{CompatUnknown()}}{{CompatGeckoDesktop("55")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown()}}{{CompatUnknown()}}{{CompatVersionUnknown}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
Somente em contexto seguro{{CompatNo}}47{{CompatUnknown()}}{{CompatGeckoDesktop("55")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/geolocationposition/index.html b/files/pt-br/web/api/geolocationposition/index.html new file mode 100644 index 0000000000..1fb810305d --- /dev/null +++ b/files/pt-br/web/api/geolocationposition/index.html @@ -0,0 +1,61 @@ +--- +title: Position +slug: Web/API/GeolocationPosition +translation_of: Web/API/GeolocationPosition +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

A interface Position representa a posição do dispositivo em questão em um dado momento. A posição, representada por um objeto {{domxref("Coordinates")}}, compreende a posição 2D do dispositivo, em um esferóide representando a Terra, e também inclui sua altitude e velocidade.

+ +

Propriedades

+ +

A interface Position não herda nenhuma propriedade.

+ +
+
{{domxref("Position.coords")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um objeto {{domxref("Coordinates")}} definindo a localização atual.
+
{{domxref("Position.timestamp")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um {{domxref("DOMTimeStamp")}} representando o momento em que a localização foi detectada.
+
+ +

Métodos

+ +

A inteface Position não implementa ou herda nenhum método.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Geolocation', '#position', 'Position')}}{{Spec2('Geolocation')}}Especificação inicial.
+ +

Compatibilidade com navegadores

+ +

 

+ + + +

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

+ +
 
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/geolocationpositionerror/index.html b/files/pt-br/web/api/geolocationpositionerror/index.html new file mode 100644 index 0000000000..d5f5ec0f96 --- /dev/null +++ b/files/pt-br/web/api/geolocationpositionerror/index.html @@ -0,0 +1,128 @@ +--- +title: PositionError +slug: Web/API/GeolocationPositionError +translation_of: Web/API/GeolocationPositionError +--- +
{{APIRef("Geolocation API")}}
+ +

A interface PositionError representa a rasão de um erro ocorrer quando usando o dispositivo de geolocalização.

+ +

Propriedades

+ +

A interface PositionError não herda nenhuma propriedade.

+ +
+
{{domxref("PositionError.code")}} {{readonlyInline}}
+
Retorna um tipo unsigned short representando o código de erro. Os valores possíveis são os seguintes: + + + + + + + + + + + + + + + + + + + + + + + +
ValorConstante associadaDescrição
1PERMISSION_DENIEDNão foi possível obter a informação sobre geolocalização por que a página não possuía permissão para fazê-lo.
2POSITION_UNAVAILABLEA obtenção da geolocalização falhou por que pelo menos uma fonte interna de posicionamento retornou um erro interno.
3TIMEOUTO tempo máximo permitido para obter a geolocalização, definido por {{domxref("PositionOptions.timeout")}} foi atingido antes de se obter a informação.
+
+
{{domxref("PositionError.message")}} {{readonlyInline}}
+
Retorna um {{domxref("DOMString")}} humanamente legível descrevendo os detalhes do erro. A especificação observa que esta informação é primariamente projetada para propósitos de debug e não deve ser exibida diretamente na interface com o usuário.
+
+ +

Métodos

+ +

A interface PositionError não implementa nem herda qualquer método.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Geolocation', '#positionerror', 'PositionError')}}{{Spec2('Geolocation')}}Especificação inicial.
+ +

Compatibilidade com navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico5{{CompatGeckoDesktop("1.9.1")}}910.60
+ {{CompatNo}} 15.0
+ 16.0
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("4")}}{{CompatUnknown}}10.60{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/globaleventhandlers/index.html b/files/pt-br/web/api/globaleventhandlers/index.html new file mode 100644 index 0000000000..1801888d2b --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/index.html @@ -0,0 +1,536 @@ +--- +title: GlobalEventHandlers +slug: Web/API/GlobalEventHandlers +tags: + - API + - DOM + - HTML-DOM + - Mixin + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/GlobalEventHandlers +--- +
{{ApiRef("HTML DOM")}}
+ +

The GlobalEventHandlers mixin describes the event handlers common to several interfaces like {{domxref("HTMLElement")}}, {{domxref("Document")}}, or {{domxref("Window")}}. Each of these interfaces can implement more event handlers.

+ +

GlobalEventHandlers is a mixin and not an interface and no object of this type can be created.

+ +

Properties

+ +

The events properties, of the form onXYZ, are defined on the {{domxref("GlobalEventHandlers")}}, and implemented by {{domxref("HTMLElement")}}, {{domxref("Document")}}, {{domxref("Window")}}, and {{domxref("WorkerGlobalScope")}} for Web Workers.

+ +
+
{{domxref("GlobalEventHandlers.onabort")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("abort")}} event is raised.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("blur")}} event is raised.
+
{{domxref("GlobalEventHandlers.onerror")}}
+
Is an {{domxref("OnErrorEventHandler")}} representing the code to be called when the {{event("error")}} event is raised.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("focus")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncancel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cancel")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncanplay")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplay")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncanplaythrough")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplaythrough")}} event is raised.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("change")}} event is raised.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("click")}} event is raised.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("close")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("contextmenu")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncuechange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cuechange")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dblclick")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondrag")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drag")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragend")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragend")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragenter")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragexit")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragexit")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragover")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragstart")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondrop")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drop")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondurationchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("durationchange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onemptied")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("emptied")}} event is raised.
+
{{domxref("GlobalEventHandlers.onended")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("ended")}} event is raised.
+
{{domxref("GlobalEventHandlers.oninput")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("input")}} event is raised.
+
{{domxref("GlobalEventHandlers.oninvalid")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("invalid")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keydown")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keypress")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keyup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onload")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("load")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadeddata")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadeddata")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadedmetadata")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadedmetadata")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadstart")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousedown")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseenter")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousemove")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseout")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseover")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousewheel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousewheel")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpause")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pause")}} event is raised.
+
{{domxref("GlobalEventHandlers.onplay")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("play")}} event is raised.
+
{{domxref("GlobalEventHandlers.onplaying")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("playing")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerdown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerdown")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointermove")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointermove")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointercancel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointercancel")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerover")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerout")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerout")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerevent")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerlockchange")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerlockchange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerlockerror")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerlockerror")}} event is raised.
+
{{domxref("GlobalEventHandlers.onprogress")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("progress")}} event is raised.
+
{{domxref("GlobalEventHandlers.onratechange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("ratechange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onreset")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("reset")}} event is raised.
+
{{domxref("GlobalEventHandlers.onscroll")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("scroll")}} event is raised.
+
{{domxref("GlobalEventHandlers.onseeked")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("seeked")}} event is raised.
+
{{domxref("GlobalEventHandlers.onseeking")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("seeking")}} event is raised.
+
{{domxref("GlobalEventHandlers.onselect")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("select")}} event is raised.
+
{{domxref("GlobalEventHandlers.onselectionchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onshow")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("show")}} event is raised.
+
{{domxref("GlobalEventHandlers.onsort")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("sort")}} event is raised.
+
{{domxref("GlobalEventHandlers.onstalled")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("stalled")}} event is raised.
+
{{domxref("GlobalEventHandlers.onsubmit")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("submit")}} event is raised.
+
{{domxref("GlobalEventHandlers.onsuspend")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("suspend")}} event is raised.
+
{{domxref("GlobalEventHandlers.ontimeupdate")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("timeupdate")}} event is raised.
+
{{domxref("GlobalEventHandlers.onvolumechange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("volumechange")}} event is raised.
+
{{domxref("GlobalEventHandlers.ontouchcancel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("touchcancel")}} event is raised.
+
{{domxref("GlobalEventHandlers.ontouchend")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("touchend")}} event is raised.
+
{{domxref("GlobalEventHandlers.ontouchmove")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("touchmove")}} event is raised.
+
{{domxref("GlobalEventHandlers.ontouchstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("touchstart")}} event is raised.
+
{{domxref("GlobalEventHandlers.onwaiting")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("waiting")}} event is raised.
+
+ +

Methods

+ +

This interface defines no method.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Selection API",'', 'Extension to GlobalEventHandlers')}}{{Spec2('Selection API')}}Adds onselectionchange.
{{SpecName('Pointer Lock', '#extensions-to-the-document-interface', 'Extension of Document')}}{{Spec2('Pointer Lock')}}Adds onpointerlockchange and onpointerlockerror on {{domxref("Document")}}. It is experimentally implemented on GlobalEventHandlers.
{{SpecName('HTML WHATWG', '#globaleventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#globaleventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. Added onsort since the {{SpecName("HTML5 W3C")}} snapshot.
{{SpecName("HTML5 W3C", "#globaleventhandlers", "GlobalEventHandlers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of GlobalEventHandlers (properties where on the target before it).
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncanplay, oncanplaythrough, ondurationchange, onemptied, onended, onloadeddata, onloadedmetadata, onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, ontimeupdate, onvolumechange, onwaiting{{CompatGeckoDesktop(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsuspend{{CompatGeckoDesktop(1.9.2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop{{CompatGeckoDesktop(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmouseenter, onmouseleave{{CompatGeckoDesktop(10)}}30.05.517{{CompatUnknown}}
ondragexit{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncancel{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onclose{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncuechange{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondragexit{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmousewheel{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsort {{experimental_inline}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmozfullscreenchange, onmozfullscreenerror {{non-standard_inline}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
onpointerlockchange, onpointerlockerror{{CompatGeckoDesktop(10)}}[1]{{CompatVersionUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onpointercancel, onpointerdown, onpointerup, onpointermove, onpointerout, onpointerover, onpointerenter, onpointerleave{{CompatVersionUnknown}}[3]{{CompatNo}}10{{CompatUnknown}}{{CompatUnknown}}
onselectionchange{{CompatGeckoDesktop(43)}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ontouchend, ontouchcancel, ontouchmove, ontouchstart{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop{{CompatGeckoMobile(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncanplay, oncanplaythrough, ondurationchange, onemptied, onended, onloadeddata, onloadedmetadata, onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, ontimeupdate, onvolumechange, onwaiting{{CompatGeckoMobile(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmouseenter, onmouseleave{{CompatGeckoMobile(10)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsuspend{{CompatGeckoMobile(1.9.2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondragexit{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncancel{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onclose{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncuechange{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondragexit{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmousewheel{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsort{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmozfullscreenchange, onmozfullscreenerror {{non-standard_inline}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
onpointerlockchange, onpointerlockerror{{CompatGeckoMobile(10)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onpointercancel, onpointerdown, onpointerup, onpointermove, onpointerout, onpointerover, onpointerenter, onpointerleave{{CompatVersionUnknown}}[3]{{CompatNo}}10{{CompatNo}}{{CompatNo}}
onselectionchange{{CompatGeckoMobile(43)}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ontouchend, ontouchcancel, ontouchmove, ontouchstart{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] In Gecko this is implemented as onmozpointerlockchange, onmozpointerlockerror.

+ +

[2] In Blink this is implemented as onwebkitpointerlockchange, onwebkitpointerlockerror.

+ +

[3] This is implemented behind the dom.w3c_pointer_events.enabled preference, defaulting to false.

+ +

[4] This is implemented behind the dom.select_events.enabled preference, that default to false, except on Nightly.

+ +

See also

+ + diff --git a/files/pt-br/web/api/globaleventhandlers/onabort/index.html b/files/pt-br/web/api/globaleventhandlers/onabort/index.html new file mode 100644 index 0000000000..9882a8b82d --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onabort/index.html @@ -0,0 +1,44 @@ +--- +title: GlobalEventHandlers.onabort +slug: Web/API/GlobalEventHandlers/onabort +translation_of: Web/API/GlobalEventHandlers/onabort +--- +
{{ ApiRef("HTML DOM") }}
+ +

Sumário

+ +

Um manipulador de eventos que aborta eventos enviados para a janela. (Não disponível para o Firefox 2 ou Safari)

+ +

TODO define what "abort" is. Closing the window via window manager? Stopping the load of the page? By which means and reasons (user, network/server)? At which stages would it fire / be catched? For IE, onabort is only available with img tags.

+ +

Sintaxe

+ +
window.onabort =funcRef
+
+ + + +

Exemplo

+ +
window.onabort = function() {
+  alert("Load aborted.");
+}
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','webappapis.html#handler-onabort','onabort')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/pt-br/web/api/globaleventhandlers/onblur/index.html b/files/pt-br/web/api/globaleventhandlers/onblur/index.html new file mode 100644 index 0000000000..ee4133a0da --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onblur/index.html @@ -0,0 +1,94 @@ +--- +title: GlobalEventHandlers.onblur +slug: Web/API/GlobalEventHandlers/onblur +tags: + - API + - HTML DOM + - Propriedade + - Referencia +translation_of: Web/API/GlobalEventHandlers/onblur +--- +
{{ApiRef("HTML DOM")}}
+ +

The onblur property returns the onBlur event handler code, if any, that exists on the current element.

+ +

Sintaxe

+ +
element.onblur = function;
+
+ + + +
element.onblur = function() { console.log("evento onblur detectado!"); };
+
+ +

Exemplo

+ +
<html>
+
+<head>
+<title>exemplo de evento onblur</title>
+
+<script type="text/javascript">
+
+var elem = null;
+
+function initElement()
+{
+  elem = document.getElementById("foo");
+  // NOTA: doEvent(); ou doEvent(param); NÃO irão funcionar aqui.
+  // Deve ser uma referência ao nome da função, não à chamada da função.
+  elem.onblur = doEvent;
+};
+
+function doEvent()
+{
+  elem.value = 'Tchauzinho';
+  console.log("Evento onblur detectado!")
+}
+</script>
+
+<style type="text/css">
+<!--
+#foo {
+border: solid blue 2px;
+}
+-->
+</style>
+</head>
+
+<body onload="initElement();">
+<form>
+<input type="text" id="foo" value="Olá!" />
+</form>
+
+<p>Clique no elemento acima para dá-lo focus, depois clique fora do elemento.<br /> Recarregue a pagina através do NavBar.</p>
+
+</body>
+</html>
+
+ +

Notas

+ +

O evento blur aparece quando um elemento perde o focus.

+ +

Em contraste cp, MSIE--O qual faz quase todos os elementos receberem o evento blur--quase todos os elementos em navegadores baseados no Gecko NÃO funcionam com este evento.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','webappapis.html#handler-onblur','onblur')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/pt-br/web/api/globaleventhandlers/onchange/index.html b/files/pt-br/web/api/globaleventhandlers/onchange/index.html new file mode 100644 index 0000000000..c2dab3f1d8 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onchange/index.html @@ -0,0 +1,46 @@ +--- +title: GlobalEventHandlers.onchange +slug: Web/API/GlobalEventHandlers/onchange +tags: + - API + - HTML DOM + - Propriedade + - Referencia +translation_of: Web/API/GlobalEventHandlers/onchange +--- +
+
{{ ApiRef("HTML DOM") }}
+
+ +

A propriedade onchange determina e retorna o manipulador de eventos para o evento {{event("change")}}.

+ +

Syntax

+ +
element.onchange = handlerFunction;
+var handlerFunction = element.onchange;
+
+ +

handlerFunction deve ser ou null ou uma função JavaScript especificando o manipulador para o evento.

+ +

Notas

+ +

Veja a página do manipulador de eventos do DOM para informações sobre como trabalhar com manipuladores on... 

+ +

Veja a documentação do evento {{event("change")}} para informações sobre o evento.

+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('HTML WHATWG','webappapis.html#handler-onchange','onchange')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/pt-br/web/api/globaleventhandlers/onclick/index.html b/files/pt-br/web/api/globaleventhandlers/onclick/index.html new file mode 100644 index 0000000000..ea91496ac9 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onclick/index.html @@ -0,0 +1,83 @@ +--- +title: GlobalEventHandlers.onclick +slug: Web/API/GlobalEventHandlers/onclick +translation_of: Web/API/GlobalEventHandlers/onclick +--- +
{{ ApiRef("HTML DOM") }}
+ +

A propriedade onclick do mixin {{domxref("GlobalEventHandlers")}} é o {{domxref("EventHandler")}} para o processamento de eventos de {{event("click")}} em um dado elemento.

+ +

O evento click acontece quando o usuário clica em um elemento. É disparado após os eventos {{event("mousedown")}} e{{event("mouseup")}} na respectiva ordem.

+ +
Note: Ao usar o evento click para disparar uma ação, considere também adicionar essa mesma ação ao evento {{event("keydown")}}, para permitir o uso dessa mesma ação a pessoas que não usam um mouse ou uma touchscreen.
+ +

Sintaxe

+ +
elemento.onclick = refDeFuncao;
+
+ +

Value

+ +

refDeFuncao é o nome de uma função ou uma expressão de função. Essa função recebe um objeto {{domxref("MouseEvent")}} como único argumento. Dentro da função, this será o elemento de qual o evento foi disparado.

+ +

Apenas um manipulador onclick pode estar associado a um objeto em um momento. Em vez disso, você talvez prefira usar o método {{domxref("EventTarget.addEventListener()")}}, já que ele é mais flexível.

+ +

Exemplo

+ +

Esse evento registra a posição dos cliques.

+ +

HTML

+ +
<p>Clique em qualquer lugar nesse exemplo.</p>
+<p id="log"></p>
+ +

JavaScript

+ +
let log = document.getElementById('log');
+
+document.onclick = inputChange;
+
+function inputChange(e) {
+  log.textContent = `Posição: (${e.clientX}, ${e.clientY})`;
+}
+ +

Result

+ +

{{EmbedLiveSample("Example")}}

+ +

Especificação

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-onclick','onclick')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade de Navegador

+ +
+ + +

{{Compat("api.GlobalEventHandlers.onclick")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/globaleventhandlers/oncontextmenu/index.html b/files/pt-br/web/api/globaleventhandlers/oncontextmenu/index.html new file mode 100644 index 0000000000..5649c6671f --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/oncontextmenu/index.html @@ -0,0 +1,48 @@ +--- +title: GlobalEventHandlers.oncontextmenu +slug: Web/API/GlobalEventHandlers/oncontextmenu +tags: + - API + - HTML DOM + - Propriedade + - Referencia +translation_of: Web/API/GlobalEventHandlers/oncontextmenu +--- +
{{ ApiRef("HTML DOM") }}
+ +

Um uma propriedade do manipulador de eventos da janela para eventos com o botão direito do mouse. A menos que o comportamento padrão do navegador seja bloqueado (veja exemplos abaixo sobre como fazer isso), o menu de contexto do navegador irá ser ativado (apesar do IE8 ter um bug com ele e não irá ativar o menu de contexto se o manipulador de eventos contextmenu for definido). Note que este evento irá acontecer com qualquer evento não-desabilitado do botão direito do mouse e não depende de um elemento que contenha o atributo "contextmenu".

+ +

Sintaxe

+ +
window.oncontextmenu = funcRef;
+//funcRef se refere à função a ser chamada
+ +

Exemplo

+ +

Os exemplos abaixo irão desabilitar o clique com botão direito na página:

+ +
document.oncontextmenu = function () { // Usa o document ao invés de window para compatibilidade com o IE8
+   return false;
+};
+
+window.addEventListener('contextmenu', function (e) { // Não compatível com IE < 9
+    e.preventDefault();
+}, false);
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','webappapis.html#handler-oncontextmenu','oncontextmenu')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/pt-br/web/api/globaleventhandlers/onerror/index.html b/files/pt-br/web/api/globaleventhandlers/onerror/index.html new file mode 100644 index 0000000000..95fdc08ce3 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onerror/index.html @@ -0,0 +1,97 @@ +--- +title: GlobalEventHandlers.onerror +slug: Web/API/GlobalEventHandlers/onerror +tags: + - API + - HTML DOM + - Propriedade + - Referencia +translation_of: Web/API/GlobalEventHandlers/onerror +--- +
{{ApiRef("HTML DOM")}}
+ +

Um event handler para o evento error . Eventos de erro são disparados contra diversos tipos de alvos, para diferentes tipos de erros: 

+ + + +

Instalando um manipulador de eventos de erro global é útil para compilação automatizada de relatórios de erro. 

+ +

Sintaxe

+ +

Por questões históricas, diferentes argumentos são passados para os manipuladores window.onerror e element.onerror;

+ +

window.onerror

+ +
window.onerror = function(message, source, lineno, colno, error) { ... }
+
+ +

Parâmetros da função:

+ + + +

 

+ +

Quando a função retorna verdadeira, ela evita o disparo do manipulador de evento padrão 

+ +

element.onerror

+ +
element.onerror = function(event) { ... }
+
+ +

element.onerror aceita uma função dom um único argumento do tipo {{domxref("Event")}}.

+ +

Notas

+ +

Quando um erro de sintaxe(?) ocorre em um script, carregado de uma origem diferente, os detalhes do erro de sintaxe não são reportados para previnir vazamento de informações (veja {{bug("363897")}}). Ao invés de exibir simplesmente "Script error." (erro de script), este comportamento pode ser sobrescrito em alguns navegadores usando o atributo  {{htmlattrxref("crossorigin","script")}} no {{HTMLElement("script")}} e tendo o servidor enviado os cabeçalhos HTTP CORS apropriados.  Uma solução alternativa é isolar o "Script error." e manipulá-lo sabendo que o detalhe do erro é visível somente no console do navegador e não acessível através do JavaScript.

+ +
window.onerror = function (msg, url, lineNo, columnNo, error) {
+    var string = msg.toLowerCase();
+    var substring = "script error";
+    if (string.indexOf(substring) > -1){
+        alert('Script Error: See Browser Console for Detail');
+    } else {
+        alert(msg, url, lineNo, columnNo, error);
+    }
+  return false;
+};
+ +

Quando usamos a marcação HTML inline (<body onerror="alert('an error occurred')">), a especificação HTML requer argumentos passados para o onerror identificados como event, source, lineno, colno, error. Os navegadors que não implementam este requerimento, podem ainda serem obtidos por arguments[0] até arguments[2].

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','webappapis.html#handler-onerror','onerror')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade de navegadores

+ +

Antes do Firefox 14, quando um {{HTMLElement("script")}} falhava na inicialização, window.onerror era invocada com a mensagem "Error loading script"(erro de leitura de script). Isto foi corrigido no {{bug("737087")}}, agora scriptElement.onerror é chamado ao invés disto.

+ +

Desde o Firefox 31, os últimos 2 argumentos (colno and error) foram adicionados, o que significa que você tem acesso a pilha de rastreamento de um erro de script através do window.onerror por intermédio do Error object ({{bug("355430")}}.)

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/globaleventhandlers/onfocus/index.html b/files/pt-br/web/api/globaleventhandlers/onfocus/index.html new file mode 100644 index 0000000000..3d27899ec3 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onfocus/index.html @@ -0,0 +1,36 @@ +--- +title: GlobalEventHandlers.onfocus +slug: Web/API/GlobalEventHandlers/onfocus +translation_of: Web/API/GlobalEventHandlers/onfocus +--- +
{{ApiRef("HTML DOM")}}
+ +

A propriedade onfocus retorna o código de manipulador de eventos onFocus no elemento atual.

+ +

Sintaxe

+ +
element.onfocus = código de manipulação de eventos
+
+ +

Notas

+ +

O evento Focus é gerado quando o usuario define o foco no elemento.

+ +

Oposta à MSIE, em que quase todos os tipos de elementos recebem o evento focus, em navegadores Gecko quase todos os tipos de elementos não funcionam com este evento.

+ +

Especificações

+ + + + + + + + + + + + + + +
especificaçãosStatusComentario
{{SpecName('HTML WHATWG','webappapis.html#handler-onfocus','onfocus')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/pt-br/web/api/globaleventhandlers/onkeyup/index.html b/files/pt-br/web/api/globaleventhandlers/onkeyup/index.html new file mode 100644 index 0000000000..394aa886b2 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onkeyup/index.html @@ -0,0 +1,61 @@ +--- +title: GlobalEventHandlers.onkeyup +slug: Web/API/GlobalEventHandlers/onkeyup +tags: + - API + - HTML DOM + - Propriedade + - Referencia +translation_of: Web/API/GlobalEventHandlers/onkeyup +--- +
{{ApiRef("HTML DOM")}}
+ +

A propriedade onkeyup retorna o código de manipulador de eventos onKeyUp no elemento atual.

+ +

Sintaxe

+ +
element.onkeyup = código do manipulador do eventos
+
+ +

Exemplo

+ +
 <input type="text" onKeyUp="teclaPressionada(event)">
+ <script>
+    function teclaPressionada(evt) {
+       console.log(evt.keyCode)
+    }
+ </script>
+
+ +

Notas

+ +

O evento keyup é iniciado quando o usuário libera a tecla é pressionada.

+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-onkeyup','onkeyup')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade

+ +
+ + +

{{Compat("api.GlobalEventHandlers.onkeyup")}}

+
+ +
 
diff --git a/files/pt-br/web/api/globaleventhandlers/onload/index.html b/files/pt-br/web/api/globaleventhandlers/onload/index.html new file mode 100644 index 0000000000..2de2fb11c4 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onload/index.html @@ -0,0 +1,74 @@ +--- +title: GlobalEventHandlers.onload +slug: Web/API/GlobalEventHandlers/onload +translation_of: Web/API/GlobalEventHandlers/onload +--- +
{{ApiRef("HTML DOM")}}
+ +

Um manipulador de eventos para o evento de carregamento do objeto {{domxref("window")}}.

+ +

Syntax

+ +
window.onload = funcRef;
+
+ + + +

Exemplos

+ +
window.onload = function() {
+  init();
+  doSomethingElse();
+};
+
+ +
<!doctype html>
+<html>
+  <head>
+    <title>onload test</title>
+    <script>
+      function load() {
+        console.log("Evento de carregamento detectado!");
+      }
+      window.onload = load;
+    </script>
+  </head>
+  <body>
+    <p>O evento de carregamento dispara quando o documento acabou de ser carregado!</p>
+  </body>
+</html>
+
+ +

Notas

+ +

O evento de carregamento dispara no final do processo de carregamento do documento. Neste ponto, todos os objetos do documento estão no DOM, e todas as imagens, scripts, links e sub-frames terminaram de carregar.

+ +

Existe também os Gecko-Specific DOM Events, como o DOMContentLoaded e o DOMFrameContentLoaded (que pode ser manipulado utilizando o {{domxref("EventTarget.addEventListener()")}}) que são disparados após o DOM para a página ser construído, mas não espera outros recursos serem carregados.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("HTML WHATWG", "webappapis.html#handler-onload", "onload")}}{{Spec2("HTML WHATWG")}}Definição inicial
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/globaleventhandlers/onlostpointercapture/index.html b/files/pt-br/web/api/globaleventhandlers/onlostpointercapture/index.html new file mode 100644 index 0000000000..8df6a32e69 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onlostpointercapture/index.html @@ -0,0 +1,70 @@ +--- +title: GlobalEventHandlers.onlostpointercapture +slug: Web/API/GlobalEventHandlers/onlostpointercapture +tags: + - API + - DOM + - Event Handler + - GlobalEventHandlers + - HTML + - Propriedade + - Referencia + - events + - onlostpointercapture +translation_of: Web/API/GlobalEventHandlers/onlostpointercapture +--- +
{{ApiRef("HTML DOM")}}
+ +

A propriedade onlostpointercapture do mixin {{domxref("GlobalEventHandlers")}} é uma {{domxref("EventHandler")}} que processa eventos {{event("lostpointercapture")}}.

+ +

Sintaxe

+ +
target.onlostpointercapture = functionRef;
+ +

Value

+ +

functionRef é o nome de uma função ou uma expressão de função. A função recebe um objeto {{domxref("PointerEvent")}} como seu único argumento.

+ +

Exemplo

+ +
function overHandler(event) {
+  // Determinar o manipulador lostpointercapture para o evento alvo (target event).
+  let lostCaptureHandler = event.target.onlostpointercapture;
+}
+
+function init() {
+  let el = document.getElementById('target');
+  el.onlostpointercapture = overHandler;
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Events 2', '#the-lostpointercapture-event', 'onlostpointercapture')}}{{Spec2('Pointer Events 2')}}
+ +

Compatibilidade de Navegador

+ + + +

{{Compat("api.GlobalEventHandlers.onlostpointercapture")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/globaleventhandlers/onscroll/index.html b/files/pt-br/web/api/globaleventhandlers/onscroll/index.html new file mode 100644 index 0000000000..1156bfb2f7 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onscroll/index.html @@ -0,0 +1,94 @@ +--- +title: GlobalEventHandlers.onscroll +slug: Web/API/GlobalEventHandlers/onscroll +translation_of: Web/API/GlobalEventHandlers/onscroll +--- +
{{ApiRef("HTML DOM")}}
+ +

A propriedade onscroll do {{domxref("GlobalEventHandlers")}} é uma mistura de eventos {{domxref("EventHandler")}} que processam eventos scroll.

+ +

O evento scroll é disparado quando uma visão do documento ou um elemento foi rolado, seja por um usuário, uma API Web, ou o {{glossary("user agent")}}.

+ +
+

Nota: Não confunda onscroll com {{domxref("GlobalEventHandlers.onwheel", "onwheel")}}: onwheel manipula a rotação da roda do mouse, enquanto onscroll manipula rolagem do conteúdo do objeto.

+
+ +

Sintaxe

+ +
target.onscroll = functionRef;
+
+ +

Valor

+ +

functionRef é o nome de uma função ou uma  expressão de função. A função recebe um  {{domxref("UIEvent")}} objeto com um único argumento.

+ +

Apenas um manipulador onscroll pode ser associado à um objeto por vez. Para uma maior flexibilidade, você pode passar um {{event("scroll")}} evento para o {{domxref("EventTarget.addEventListener()")}} metódo ao invés disso.

+ +

Exemplo

+ +

Este exemplo monitora rolagens sobre o elemento {{HtmlElement("textarea")}}, e registra a posição vertical adequadamente.

+ +

HTML

+ +
<textarea>1 2 3 4 5 6 7 8 9</textarea>
+<p id="log"></p>
+ +

CSS

+ +
textarea {
+  width: 4rem;
+  height: 8rem;
+  font-size: 3rem;
+}
+ +

JavaScript

+ +
const textarea = document.querySelector('textarea');
+const log = document.getElementById('log');
+
+textarea.onscroll = logScroll;
+
+function logScroll(e) {
+  log.textContent = `Posição do scroll: ${e.target.scrollTop}`;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Exemplo", 700, 200)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','#handler-onscroll','onscroll')}}{{Spec2('HTML WHATWG')}}
{{SpecName("DOM3 Events", "#event-type-scroll", "onscroll")}}{{Spec2("DOM3 Events")}}Initial definition
+ +

Compatibilidade com o Navegador

+ + + +

{{Compat("api.GlobalEventHandlers.onscroll")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/history/index.html b/files/pt-br/web/api/history/index.html new file mode 100644 index 0000000000..8541516f41 --- /dev/null +++ b/files/pt-br/web/api/history/index.html @@ -0,0 +1,89 @@ +--- +title: History +slug: Web/API/History +translation_of: Web/API/History +--- +
{{APIRef ("HTML DOM")}}
+ +

A interface History permite a manipulação do histórico da sessão do navegador, ou seja, as páginas visitadas na guia ou quadro em que a página atual está carregada.

+ +

Propriedades

+ + + +

A interface History não herda nenhuma propriedade.

+ +
+
{{domxref("History.length")}} {{readOnlyInline}}
+
Returns an Integer representing the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1.
+
{{domxref("History.current")}} {{readOnlyInline}} {{ non-standard_inline() }} {{ obsolete_inline(26) }}
+
Returns a {{domxref("DOMString")}} representing the URL of the active item of the session history. This property was never available to web content and is no more supported by any browser. Use {{domxref("Location.href")}} instead.
+
{{domxref("History.next")}} {{readOnlyInline}} {{ non-standard_inline() }} {{ obsolete_inline(26) }}
+
Returns a {{domxref("DOMString")}} representing the URL of the next item in the session history. This property was never available to web content and is not supported by other browsers.
+
{{domxref("History.previous")}} {{readOnlyInline}} {{ non-standard_inline() }} {{ obsolete_inline(26) }}
+
Returns a {{domxref("DOMString")}} representing the URL of the previous item in the session history. This property was never available to web content and is not supported by other browsers.
+
{{domxref("History.scrollRestoration")}} {{experimental_inline}}
+
Allows web applications to explicitly set default scroll restoration behavior on history navigation. This property can be either auto or manual.
+
{{domxref("History.state")}} {{readOnlyInline}} {{ gecko_minversion_inline("2.0") }}
+
Returns an any value representing the state at the top of the history stack. This is a way to look at the state without having to wait for a {{event("popstate")}} event.
+
+ +

Methods

+ +

The History interface doesn't inherit any methods.

+ +
+
{{domxref("History.back()")}}
+
Goes to the previous page in session history, the same action as when the user clicks the browser's Back button. Equivalent to history.go(-1). +
Calling this method to go back beyond the first page in the session history has no effect and doesn't raise an exception.
+
+
{{domxref("History.forward()")}}
+
Goes to the next page in session history, the same action as when the user clicks the browser's Forward button; this is equivalent to history.go(1). +
Calling this method to go forward beyond the most recent page in the session history has no effect and doesn't raise an exception.
+
+
{{domxref("History.go()")}}
+
Loads a page from the session history, identified by its relative location to the current page, for example -1 for the previous page or 1  for the next page. If you specify an out-of-bounds value (for instance, specifying -1 when there are no previously-visited pages in the session history), this method silently has no effect. Calling go() without parameters or a value of 0 reloads the current page. Internet Explorer lets you specify a string, instead of an integer, to go to a specific URL in the history list.
+
{{domxref("History.pushState()")}} {{ gecko_minversion_inline("2.0") }}
+
Pushes the given data onto the session history stack with the specified title and, if provided, URL. The data is treated as opaque by the DOM; you may specify any JavaScript object that can be serialized.  Note that Firefox currently ignores the title parameter; for more information, see manipulating the browser history.
+
{{domxref("History.replaceState()")}} {{ gecko_minversion_inline("2.0") }}
+
Updates the most recent entry on the history stack to have the specified data, title, and, if provided, URL. The data is treated as opaque by the DOM; you may specify any JavaScript object that can be serialized.  Note that Firefox currently ignores the title parameter; for more information, see manipulating the browser history.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "browsers.html#the-history-interface", "History")}}{{Spec2('HTML WHATWG')}}Adds the scrollRestoration attribute.
{{SpecName('HTML5 W3C', "browsers.html#the-history-interface", "History")}}{{Spec2('HTML5 W3C')}}Initial definition.
{{SpecName('Custom Scroll Restoration', '#web-idl', "History")}}{{Spec2('Custom Scroll Restoration')}}Adds the scrollRestoration attribute.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/history_api/exemplo/index.html b/files/pt-br/web/api/history_api/exemplo/index.html new file mode 100644 index 0000000000..a4dfc4b68f --- /dev/null +++ b/files/pt-br/web/api/history_api/exemplo/index.html @@ -0,0 +1,418 @@ +--- +title: Exemplo de navegação Ajax +slug: Web/API/History_API/Exemplo +tags: + - Exemplo navegação ajax +translation_of: Web/API/History_API/Example +--- +

Esse é um exemplo de um web site em AJAX web site composto por apenas três páginas (first_page.php, second_page.php e third_page.php). Para ver como funciona, crie os arquivos a seguir (ou git clone https://github.com/giabao/mdn-ajax-nav-example.git ):

+ +
Nota: Para integrar completamente os elementos {{HTMLElement("form")}} com esse mecanismo, porfavor dê uma olhada no parágrafo Enviando formulários e enviando arquivos.
+ +

first_page.php:

+ +
+
<?php
+    $page_title = "Primeira página";
+
+    $as_json = false;
+    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
+        $as_json = true;
+        ob_start();
+    } else {
+?>
+<!doctype html>
+<html>
+<head>
+<?php
+        include "include/header.php";
+        echo "<title>" . $page_title . "</title>";
+?>
+</head>
+
+<body>
+
+<?php include "include/before_content.php"; ?>
+
+<p>Esse parágrafo só é mostrado quando a navegação começa em <strong>first_page.php</strong>.</p>
+
+<div id="ajax-content">
+<?php } ?>
+
+    <p>Esse é o conteúdo de <strong>first_page.php</strong>.</p>
+
+<?php
+    if ($as_json) {
+        echo json_encode(array("page" => $page_title, "content" => ob_get_clean()));
+    } else {
+?>
+</div>
+
+<p>Esse parágrafo só é mostrado quando a navegação começa em <strong>first_page.php</strong>.</p>
+
+<?php
+        include "include/after_content.php";
+        echo "</body>\n</html>";
+    }
+?>
+
+
+ +

second_page.php:

+ +
+
<?php
+    $page_title = "Segunda página";
+
+    $as_json = false;
+    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
+        $as_json = true;
+        ob_start();
+    } else {
+?>
+<!doctype html>
+<html>
+<head>
+<?php
+        include "include/header.php";
+        echo "<title>" . $page_title . "</title>";
+?>
+</head>
+
+<body>
+
+<?php include "include/before_content.php"; ?>
+
+<p>Esse parágrafo só é mostrado quando a navegação começa em <strong>second_page.php</strong>.</p>
+
+<div id="ajax-content">
+<?php } ?>
+
+    <p>Esse é o conteúdo de <strong>second_page.php</strong>.</p>
+
+<?php
+    if ($as_json) {
+        echo json_encode(array("page" => $page_title, "content" => ob_get_clean()));
+    } else {
+?>
+</div>
+
+<p>Esse parágrafo só é mostrado quando a navegação começa em <strong>second_page.php</strong>.</p>
+
+<?php
+        include "include/after_content.php";
+        echo "</body>\n</html>";
+    }
+?>
+
+
+ +

third_page.php:

+ +
+
<?php
+    $page_title = "Terceira página";
+    $page_content = "<p>Esse é o conteúdo de <strong>third_page.php</strong>. This content is stored into a php variable.</p>";
+
+    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
+        echo json_encode(array("page" => $page_title, "content" => $page_content));
+    } else {
+?>
+<!doctype html>
+<html>
+<head>
+<?php
+        include "include/header.php";
+        echo "<title>" . $page_title . "</title>";
+?>
+</head>
+
+<body>
+
+<?php include "include/before_content.php"; ?>
+
+<p>Esse parágrafo só é mostrado quando a navegação começa em <strong>third_page.php</strong>.</p>
+
+<div id="ajax-content">
+<?php echo $page_content; ?>
+</div>
+
+<p>Esse parágrafo só é mostrado quando a navegação começa em <strong>third_page.php</strong>.</p>
+
+<?php
+        include "include/after_content.php";
+        echo "</body>\n</html>";
+    }
+?>
+
+
+ +

css/style.css:

+ +
#ajax-loader {
+    position: fixed;
+    display: table;
+    top: 0;
+    left: 0;
+    width: 100%;
+    height: 100%;
+}
+
+#ajax-loader > div {
+    display: table-cell;
+    width: 100%;
+    height: 100%;
+    vertical-align: middle;
+    text-align: center;
+    background-color: #000000;
+    opacity: 0.65;
+}
+
+ +

include/after_content.php:

+ +
<p>Esse é o rodapé. Ele é compartilhado entre todas as páginas ajax.</p>
+
+ +

include/before_content.php:

+ +
<p>
+[ <a class="ajax-nav" href="first_page.php">Primeiro exemplo</a>
+| <a class="ajax-nav" href="second_page.php">Segundo exemplo</a>
+| <a class="ajax-nav" href="third_page.php">Terceiro exemplo</a>
+| <a class="ajax-nav" href="unexisting.php">Página inexistente</a> ]
+</p>
+
+
+ +

include/header.php:

+ +
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<script type="text/javascript" src="js/ajax_nav.js"></script>
+<link rel="stylesheet" href="css/style.css" />
+
+ +

js/ajax_nav.js:

+ +

(antes de implementar em um ambiente de trabalho, porfavor leia a nota sobre a compatibilidade de declaração de const)

+ +
+
"use strict";
+
+const ajaxRequest = new (function () {
+
+    function closeReq () {
+        oLoadingBox.parentNode && document.body.removeChild(oLoadingBox);
+        bIsLoading = false;
+    }
+
+    function abortReq () {
+        if (!bIsLoading) { return; }
+        oReq.abort();
+        closeReq();
+    }
+
+    function ajaxError () {
+        alert("Unknown error.");
+    }
+
+    function ajaxLoad () {
+        var vMsg, nStatus = this.status;
+        switch (nStatus) {
+            case 200:
+                vMsg = JSON.parse(this.responseText);
+                document.title = oPageInfo.title = vMsg.page;
+                document.getElementById(sTargetId).innerHTML = vMsg.content;
+                if (bUpdateURL) {
+                    history.pushState(oPageInfo, oPageInfo.title, oPageInfo.url);
+                    bUpdateURL = false;
+                }
+                break;
+            default:
+                vMsg = nStatus + ": " + (oHTTPStatus[nStatus] || "Unknown");
+                switch (Math.floor(nStatus / 100)) {
+                    /*
+                    case 1:
+                        // Informational 1xx
+                        console.log("Information code " + vMsg);
+                        break;
+                    case 2:
+                        // Successful 2xx
+                        console.log("Successful code " + vMsg);
+                        break;
+                    case 3:
+                        // Redirection 3xx
+                        console.log("Redirection code " + vMsg);
+                        break;
+                    */
+                    case 4:
+                        /* Client Error 4xx */
+                        alert("Client Error #" + vMsg);
+                        break;
+                    case 5:
+                        /* Server Error 5xx */
+                        alert("Server Error #" + vMsg);
+                        break;
+                    default:
+                        /* Unknown status */
+                        ajaxError();
+                }
+        }
+        closeReq();
+    }
+
+    function filterURL (sURL, sViewMode) {
+        return sURL.replace(rSearch, "") + ("?" + sURL.replace(rHost, "&").replace(rView, sViewMode ? "&" + sViewKey + "=" + sViewMode : "").slice(1)).replace(rEndQstMark, "");
+    }
+
+    function getPage (sPage) {
+        if (bIsLoading) { return; }
+        oReq = new XMLHttpRequest();
+        bIsLoading = true;
+        oReq.onload = ajaxLoad;
+        oReq.onerror = ajaxError;
+        if (sPage) { oPageInfo.url = filterURL(sPage, null); }
+        oReq.open("get", filterURL(oPageInfo.url, "json"), true);
+        oReq.send();
+        oLoadingBox.parentNode || document.body.appendChild(oLoadingBox);
+    }
+
+    function requestPage (sURL) {
+        if (history.pushState) {
+            bUpdateURL = true;
+            getPage(sURL);
+        } else {
+            /* Ajax navigation is not supported */
+            location.assign(sURL);
+        }
+    }
+
+    function processLink () {
+        if (this.className === sAjaxClass) {
+            requestPage(this.href);
+            return false;
+        }
+        return true;
+    }
+
+    function init () {
+        oPageInfo.title = document.title;
+        history.replaceState(oPageInfo, oPageInfo.title, oPageInfo.url);
+        for (var oLink, nIdx = 0, nLen = document.links.length; nIdx < nLen; document.links[nIdx++].onclick = processLink);
+    }
+
+    const
+
+        /* customizable constants */
+        sTargetId = "ajax-content", sViewKey = "view_as", sAjaxClass = "ajax-nav",
+
+        /* not customizable constants */
+        rSearch = /\?.*$/, rHost = /^[^\?]*\?*&*/, rView = new RegExp("&" + sViewKey + "\\=[^&]*|&*$", "i"), rEndQstMark = /\?$/,
+        oLoadingBox = document.createElement("div"), oCover = document.createElement("div"), oLoadingImg = new Image(),
+        oPageInfo = {
+            title: null,
+            url: location.href
+        }, oHTTPStatus = /* http://www.iana.org/assignments/http-status-codes/http-status-codes.xml */ {
+            100: "Continue",
+            101: "Switching Protocols",
+            102: "Processing",
+            200: "OK",
+            201: "Created",
+            202: "Accepted",
+            203: "Non-Authoritative Information",
+            204: "No Content",
+            205: "Reset Content",
+            206: "Partial Content",
+            207: "Multi-Status",
+            208: "Already Reported",
+            226: "IM Used",
+            300: "Multiple Choices",
+            301: "Moved Permanently",
+            302: "Found",
+            303: "See Other",
+            304: "Not Modified",
+            305: "Use Proxy",
+            306: "Reserved",
+            307: "Temporary Redirect",
+            308: "Permanent Redirect",
+            400: "Bad Request",
+            401: "Unauthorized",
+            402: "Payment Required",
+            403: "Forbidden",
+            404: "Not Found",
+            405: "Method Not Allowed",
+            406: "Not Acceptable",
+            407: "Proxy Authentication Required",
+            408: "Request Timeout",
+            409: "Conflict",
+            410: "Gone",
+            411: "Length Required",
+            412: "Precondition Failed",
+            413: "Request Entity Too Large",
+            414: "Request-URI Too Long",
+            415: "Unsupported Media Type",
+            416: "Requested Range Not Satisfiable",
+            417: "Expectation Failed",
+            422: "Unprocessable Entity",
+            423: "Locked",
+            424: "Failed Dependency",
+            425: "Unassigned",
+            426: "Upgrade Required",
+            427: "Unassigned",
+            428: "Precondition Required",
+            429: "Too Many Requests",
+            430: "Unassigned",
+            431: "Request Header Fields Too Large",
+            500: "Internal Server Error",
+            501: "Not Implemented",
+            502: "Bad Gateway",
+            503: "Service Unavailable",
+            504: "Gateway Timeout",
+            505: "HTTP Version Not Supported",
+            506: "Variant Also Negotiates (Experimental)",
+            507: "Insufficient Storage",
+            508: "Loop Detected",
+            509: "Unassigned",
+            510: "Not Extended",
+            511: "Network Authentication Required"
+        };
+
+    var
+
+        oReq, bIsLoading = false, bUpdateURL = false;
+
+    oLoadingBox.id = "ajax-loader";
+    oCover.onclick = abortReq;
+    oLoadingImg.src = "data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==";
+    oCover.appendChild(oLoadingImg);
+    oLoadingBox.appendChild(oCover);
+
+    onpopstate = function (oEvent) {
+        bUpdateURL = false;
+        oPageInfo.title = oEvent.state.title;
+        oPageInfo.url = oEvent.state.url;
+        getPage();
+    };
+
+    window.addEventListener ? addEventListener("load", init, false) : window.attachEvent ? attachEvent("onload", init) : (onload = init);
+
+    // Public methods
+
+    this.open = requestPage;
+    this.stop = abortReq;
+    this.rebuildLinks = init;
+
+})();
+
+
+ +
Nota: A atual implementação de const (declaração de constante) não é parte do ECMAScript 5. É suportada no Firefox e no Chrome (V8) e parcialmente suportada no Opera 9+ e no Safari. Ela  não é suportada nas versões do Internet Explorer 6 ao 9, ou na versão preview do Internet Explorer 10. const será definida no ECMAScript 6, mas com semânticas diferentes. Similarmente ao que acontece com variáveis definidas como let, constantes declaradas com const serão block-scoped, limitando seu escopo no bloco. Nós só usamos isso com propósito didático. Se você quer total compatibilidade com os navegadores, substitua todas as declarações const por declarações var.
+ +

Para mais informações, veja: Manipulando o histórico do navegador.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/history_api/index.html b/files/pt-br/web/api/history_api/index.html new file mode 100644 index 0000000000..5b763f9a97 --- /dev/null +++ b/files/pt-br/web/api/history_api/index.html @@ -0,0 +1,257 @@ +--- +title: Manipulando o histórico do navegador +slug: Web/API/History_API +tags: + - Avançado + - DOM + - HTML5 + - Histórico +translation_of: Web/API/History_API +--- +

O objeto DOM {{ domxref("window") }} fornece acesso ao histórico do navegador através do objeto {{ domxref("window.history", "history") }}. Ele expõe métodos e propriedades úteis que permitem que você se mova para trás e para frente através do histórico de navegação do usuário, bem como -- iniciando com o HTML5 -- manipular o conteúdo da pilha de históricos.

+ + + +

Mover para trás e para a frente através do histórico do usuário é feito usando os métodos back(), forward() e go().

+ +

Movendo para frente e para trás

+ +

Para mover para trás no histórico, apenas faça:

+ +
window.history.back();
+
+ +

Isso funcionará exatamente como se o usuário clicasse no botão Voltar na barra de ferramentas do navegador.
+
+ Da mesma forma, você pode avançar (como se o usuário clicasse no botão Avançar), assim:

+ +
window.history.forward();
+
+ +

Movendo para um ponto específico no histórico

+ +

Você pode usar o método go() para carregar uma página específica do histórico. Cada página é identificada por sua posição relativa à página atual (sendo a página atual o indíce 0). 

+ +

Para retornar uma página (equivalente ao método back()):

+ +
window.history.go(-1);
+
+ +

Para avançar uma página (equivalente ao método forward()):

+ +
window.history.go(1);
+
+
+ +

O número de páginas do histórico pode ser determinado pela propriedade length:

+ +
const numberOfEntries = window.history.length;
+
+ +
Note: O Internet Explorer suporta URLs como argumento para o método go(); isso não é um comportamento padrão e não é suportado pelo Gecko.
+ +

Adicionando e modificando entradas

+ +

{{ gecko_minversion_header("2") }}

+ +

O HTML5 introduziu os métodos history.pushState() e history.replaceState(), que permitem adicionar e modificar entradas no histórico, respectivamente. Estes métodos funcionam em conjunto com o evento {{ domxref("window.onpopstate") }}.

+ +

Usar history.pushState() modifica a referência que é utilizada no cabeçalho HTTP para objetos XMLHttpRequest criados após a utilização do método. A referência será a URL do documento cuja janela é o this no momento de criação do objeto XMLHttpRequest.

+ +

Exemplo do método pushState()

+ +

Suponha que http://mozilla.org/foo.html executa o seguinte JavaScript:

+ +
const stateObj = { foo: "bar" };
+history.pushState(stateObj, "page 2", "bar.html");
+
+ +

Isto fará com que a barra URL mostre http://mozilla.org/bar.html, porém não fará com que o navegador carregue bar.html ou verifique se bar.html existe. 

+ +

Agora suponha que o usuário navegue para http://google.com e logo em seguida clique no botão Voltar. Nesse momento, a barra de URL mostrará http://mozilla.org/bar.html, e a página receberá um evento popstate cujo objeto de estado contém uma copia de stateObj se você ler o history.state você receberá o stateObj. O evento popstate não será disparado pois a página foi recarregada. A página carregada será bar.html.

+ +

Se clicarmos no botão Voltar novamente, a URL modificará para http://mozilla.org/foo.html, e o documento receberá um evento popstate, dessa vez com objeto de estado sendo nulo. Nesse momento, o documento também não altera seu conteúdo em relação ao passo anterior, porém o documento pode atualizar seu conteúdo manualmente após o recebimento do evento popstate.

+ +

O método pushState()

+ +

pushState() recebe três parâmetros: um objeto de estado, um título (que atualmente é ignorado) e (opcionalmente) uma URL. Vamos examinar cada um dos argumentos com mais detalhes:

+ + + +
Nota: No Gecko 2.0 {{ geckoRelease("2.0") }} até Gecko 5.0 {{ geckoRelease("5.0") }}, o objeto passado é serializado utilizando JSON. A partir do Gecko 6.0 {{ geckoRelease("6.0") }}, o objeto é serializado usando  o algorítmo de clonagem estruturada. Isso permite que uma variedade maior de objetos possam ser serializados.
+ +

De certa forma, chamar o método pushState() é similar a executar window.location = "#foo",  no sentido de que ambos criarão e ativarão uma nova entrada no histórico associado com o documento atual. Porém pushState() tem algumas vantagens:

+ + + +

Note que pushState() nunca causa a ativação de um evento hashchange, mesmo se a nova URL diferir somente na hash,

+ +

Em um documento XUL é criado o elemento XUL especificado.

+ +

Em outros documentos, é criado um elemento com um namespace null de URI.

+ +

O método replaceState()

+ +

history.replaceState() opera exatamente igual à history.pushState() com exceção de modificar a atual entrada no histórico ao invés de criar uma nova. Note que isso não impede a criação de uma nova entrada no histórico global do navegador.

+ +

replaceState() é particularmente útil quando você quer atualiza o objeto de estado ou a URL da atual entrada do histórico como resposta a alguma ação do usuário.

+ +
Nota: Em Gecko 2.0 {{ geckoRelease("2.0") }} até Gecko 5.0 {{ geckoRelease("5.0") }}, o objeto passado é serializado utilizando JSON. Começando do Gecko 6.0 {{ geckoRelease("6.0") }}, o objeto é serializado usando  o algorítmo de clonagem estruturada. Isso permite que uma variedade maior de objetos possam ser serializados.
+ +

Exemplo do método replaceState()

+ +

Suponha que http://mozilla.org/foo.html execute o seguinte JavaScript:

+ +
const stateObj = { foo: "bar" };
+history.pushState(stateObj, "page 2", "bar.html");
+
+
+ +

A explicação destas duas linhas acima pode ser encontrada na seção "Exemplo do método pushState()". Suponha, então, que http://mozilla.org/bar.html execute o seguinte JavaScript:

+ +
history.replaceState(stateObj, "page 3", "bar2.html");
+
+ +

Isso fará com que a barra de URL do navegador exiba http://mozilla.org/bar2.html, mas não fará com que o navegador carregue bar2.html ou cheque se bar2.html existe.

+ +

Suponha agora que o usuário navegue até http://www.microsoft.com e, em seguida, clique no botão voltar. Neste momento, a barra de URL mostrará http://mozilla.org/bar2.html. Caso o usuário clique novamente no botão voltar, a barra de URL mostrará http://mozilla.org/foo.html e ignorará completamente bar.html.

+ +

O evento popstate

+ +

O evento popstate é disparado sempre que a entrada do histórico ativo é alterada. Se a entrada do histórico ativa foi criada por uma chamada pushState ou afetada por uma chamada replaceState, a propriedade state do evento popstate contém uma cópia do objeto de estado da entrada do histórico.

+ +

Veja {{ domxref("window.onpopstate") }} para exemplo de utilização.

+ +

Lendo o estado atual

+ +

Quando sua página é carregada, ela pode ter um objeto de estado não nulo. Isso pode acontecer, por exemplo, se a página definir um objeto de estado (usando pushState() ou replaceState()) e, em seguida, o usuário reiniciar seu navegador. Quando sua página é recarregada, ela receberá um evento onload, mas nenhum evento popstate. No entanto, se você ler a propriedade history.state, receberá o objeto de estado que teria obtido se um popstate tivesse sido disparado.

+ +

Você pode ler o estado da entrada do histórico atual sem esperar por um evento popstate usando a propriedade history.state como o exemplo abaixo:

+ +
var currentState = history.state;
+
+ +

Exemplos

+ +

Para um exemplo completo de um web site AJAX, veja: Exemplo de navegação Ajax.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "browsers.html#history", "History")}}{{Spec2('HTML WHATWG')}}Nenhuma alteração do {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#history", "History")}}{{Spec2('HTML5 W3C')}}Definição inicial
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
replaceState, pushState5{{CompatVersionUnknown}}{{ CompatGeckoDesktop("2.0") }}1011.505.0
history.state18{{CompatVersionUnknown}}{{ CompatGeckoDesktop("2.0") }}1011.506.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
replaceState, pushState{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
history.state{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + + +

{{ languages( { "ja": "ja/DOM/Manipulating_the_browser_history"} ) }}

diff --git a/files/pt-br/web/api/htmlcanvaselement/getcontext/index.html b/files/pt-br/web/api/htmlcanvaselement/getcontext/index.html new file mode 100644 index 0000000000..c50cd97abb --- /dev/null +++ b/files/pt-br/web/api/htmlcanvaselement/getcontext/index.html @@ -0,0 +1,292 @@ +--- +title: HTMLCanvasElement.getContext() +slug: Web/API/HTMLCanvasElement/getContext +tags: + - API + - Canvas + - HTMLCanvasElement + - Referencia + - metodo +translation_of: Web/API/HTMLCanvasElement/getContext +--- +
{{APIRef("Canvas API")}}
+ +

O metodo HTMLCanvasElement.getContext() retorna um contexto de desenho no canvas, ou {{jsxref("null")}} se o contexto identificado não é suportado.

+ +

Syntax

+ +
canvas.getContext(contextType, contextAttributes);
+
+ +

Parametros

+ +
+
contextType
+
É um {{domxref("DOMString")}} contendo o contexto identificador definindo o contexto de desenho associado ao canvas.        Os valores possiveis são: +
    +
  • "2d", levando a criação de um objeto {{domxref("CanvasRenderingContext2D")}} representando uma  renderização bidimensional.
  • +
  • "webgl" (or "experimental-webgl") que criará um objeto {{domxref("WebGLRenderingContext")}} representando uma renderização tridimensional. Esse contexto está disponivel somente em browsers que implementam WebGL versão 1 (OpenGL ES 2.0).
  • +
  • "webgl2" que criará um objeto {{domxref("WebGL2RenderingContext")}} representando uma renderização tridimensional. Esse contexto está disponivel somente em browsers que implementam WebGL versão 2 (OpenGL ES 3.0). {{experimental_inline}}
  • +
  • "bitmaprenderer" que criará um  {{domxref("ImageBitmapRenderingContext")}} que apenas provê a funcionalidade de substituir o conteúdo do canvas pelo de um {{domxref("ImageBitmap")}}.
  • +
+ +
+

Note: O identificador "experimental-webgl" é usado em novas implementações do WebGL. Essas implementações ou ainda não passaram nos casos de teste, ou os drivers gráficos na plataforma ainda não estão estáveis. O Khronos Group certifica as implementações do WebGL sob certas regas de conformidade.

+
+
+
contextAttributes
+
+

Você pode usar alguns atributos de contexto quando criar o seu contexto de renderização, por exemplo:

+ +
canvas.getContext('webgl',
+                 { antialias: false,
+                   depth: false });
+ Atributos de contexto 2d: + +
    +
  • alpha: Boleano que indica se o canvas contém um canal alfa. Se definido como false, o browser saberá que o resultado será sempre opaco, o que pode acelerar o desenho de conteudo transparente e imagens.
  • +
  • {{non-standard_inline}} (Gecko only) willReadFrequently: Boleano que indica quando uma série de operações read-back estão planejadas. Isso forçará o uso de renderização 2D no canvas via software (ao invés de utilizar GPU) o que pode salvar memoria quando {{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}} for chamado frequentemente. Essa opção está disponivel somente, se a flag gfx.canvas.willReadFrequently.enable está definida como true (o que, por padrão, é o caso do B2G/Firefox OS apenas).
  • +
  • {{non-standard_inline}} (Blink only) storage: String que indica qual storage é usado ("persistent" por padrão).
  • +
+ Atributos de contexto WebGL: + +
    +
  • alpha: Boleano que indica se o canvas contém um buffer alfa.
  • +
  • depth: Boleano que indica que o buffer do desenho tem um buffer de profundidade de pelo menos 16 bits.
  • +
  • stencil: Boleano que indica que o buffer do desenho tem um buffer de stencil de pelo menos 8 bits.
  • +
  • antialias: Boleano que indica se deve realizar o anti-aliasing ou não.
  • +
  • premultipliedAlpha: Boleano que indica se o compositor da página vai assumir que o buffer do desenho contendo cores com alfa pré-multiplicado.
  • +
  • preserveDrawingBuffer: Se o valor é true os buffers não serão limpos e preservarão seus valores até serem limpos ou subrescritos pelo autor.
  • +
  • +

    failIfMajorPerformanceCaveat: Boleano que indica se um contexto será criado se a performance do sistema for baixa.

    +
  • +
+
+
+ +

Return value

+ +

Um {{domxref("RenderingContext")}} que pode ser:

+ + + +

Se o contextType não bater com um possivel contexto de desenho,null é retornado.

+ +

Examples

+ +

Dado este elemento {{HTMLElement("canvas")}}:

+ +
<canvas id="canvas" width="300" height="300"></canvas>
+
+ +

Você pega um contexto 2d do canvas com o código a seguir:

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+console.log(ctx); // CanvasRenderingContext2D { ... }
+
+ +

Agora você tem contexto de renderização 2d para o canvas e você pode desenhar nele.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML WHATWG')}}Nenhuma mudança desde o ultimo snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5 W3C')}}Snapshot do {{SpecName('HTML WHATWG')}} contendo a definição inicial.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (2d context){{CompatChrome(4)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}}{{CompatIE(9)}}{{CompatOpera(9)}}{{CompatSafari(3.1)}}
webgl context{{CompatChrome(9)}}[1]
+ {{CompatChrome(33)}}
{{CompatVersionUnknown}}{{CompatGeckoDesktop('1.9.2')}}[1]
+ {{CompatGeckoDesktop('24')}}
11.0[2]9.0[3]5.1[2]
webgl2 context {{CompatChrome(56)}}{{CompatUnknown}}{{CompatGeckoDesktop('25')}}[4]{{CompatNo}}{{CompatNo}}{{CompatNo}}
2d alpha context attribute32{{CompatUnknown}}{{CompatGeckoDesktop(30)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+

failIfMajorPerformanceCaveat attribute

+
{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
bitmaprenderer context{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop(46)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (2d context){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.2")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
webgl context{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
webgl2 context {{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
2d alpha context attribute{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(30)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
failIfMajorPerformanceCaveat attribute{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
bitmaprenderer context{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(46)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Chrome 9 e Gecko 1.9.2 inicialmente implementaram isso como um experimental-webgl. Desde o Chrome 33 e Gecko 24 é implementado como definido pelo padrão: webgl.

+ +

[2] Internet Explorer 11, WebKit 5.1 e Firefox Mobile implementaram isso como um experimental-webgl.

+ +

[3] Opera 9 implementou isso como um experimental-webgl, ativado nas preferencias do usuario, na versão 15.0 a preferencia de usuario foi removida.

+ +

[4] Gecko 25 implementou isso como um "experimental-webgl2" ativado na preferencia do usuario webgl.enable-prototype-webgl2. Apartir do Gecko 42, a string "webgl2"é usada na mesma configuração e "experimental-webgl2" não é mais aceito.

+ +

See also

+ + diff --git a/files/pt-br/web/api/htmlcanvaselement/height/index.html b/files/pt-br/web/api/htmlcanvaselement/height/index.html new file mode 100644 index 0000000000..fd737da382 --- /dev/null +++ b/files/pt-br/web/api/htmlcanvaselement/height/index.html @@ -0,0 +1,79 @@ +--- +title: HTMLCanvasElement.height +slug: Web/API/HTMLCanvasElement/height +tags: + - API + - Canvas + - HTMLCanvasElement + - Propriedade + - altura +translation_of: Web/API/HTMLCanvasElement/height +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

A propriedade HTMLCanvasElement.height é um inteiro positivo que reflete o atributo {{htmlattrxref("height", "canvas")}} do elemento HTML {{HTMLElement("canvas")}} interpretado em pixels no CSS. Quando o atributo não é especificado, ou se for definido como um valor inválido, como um inteiro negativo, o valor padrão de 150 será usado.

+ +

Essa é uma de duas propriedades, que controla o tamanho do canvas, sendo a outra {{domxref("HTMLCanvasElement.width")}}.

+ +

Sintaxe

+ +
var pxl = canvas.height;
+canvas.height = pxl;
+
+ +

Exemplos

+ +

Dado este elemento {{HTMLElement("canvas")}}:

+ +
<canvas id="canvas" width="300" height="300"></canvas>
+
+ +

Você pode capturar a altura do canvas com o seguinte código:

+ +
var canvas = document.getElementById('canvas');
+console.log(canvas.height); // 300
+
+ +

Especificações

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

Compatibilidade entre os browsers

+ + + +

{{Compat("api.HTMLCanvasElement.height")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlcanvaselement/index.html b/files/pt-br/web/api/htmlcanvaselement/index.html new file mode 100644 index 0000000000..c2121aab9a --- /dev/null +++ b/files/pt-br/web/api/htmlcanvaselement/index.html @@ -0,0 +1,264 @@ +--- +title: HTMLCanvasElement +slug: Web/API/HTMLCanvasElement +tags: + - API + - Canvas + - HTML DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLCanvasElement +--- +
+
{{APIRef("Canvas API")}}
+
+ +

The HTMLCanvasElement interface provides properties and methods for manipulating the layout and presentation of canvas elements. The HTMLCanvasElement interface also inherits the properties and methods of the {{domxref("HTMLElement")}} interface.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

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

+ +
+
{{domxref("HTMLCanvasElement.height")}}
+
Is a positive integer reflecting the {{htmlattrxref("height", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 150 is used.
+
{{domxref("HTMLCanvasElement.mozOpaque")}} {{non-standard_inline}}
+
Is a {{jsxref("Boolean")}} reflecting the {{htmlattrxref("moz-opaque", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element. It lets the canvas know whether or not translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized.
+
{{domxref("HTMLCanvasElement.width")}}
+
Is a positive integer reflecting the {{htmlattrxref("width", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 300 is used.
+
{{domxref("HTMLCanvasElement.mozPrintCallback")}}{{non-standard_inline}}
+
Is a function that is Initially null, Web content can set this to a JavaScript function that will be called if the page is printed. This function can then redraw the canvas at a higher resolution that is suitable for the printer being used. See this blog post.
+
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLCanvasElement.captureStream()")}} {{experimental_inline}}
+
Returns a {{domxref("CanvasCaptureMediaStream")}} that is a real-time video capture of the surface of the canvas.
+
{{domxref("HTMLCanvasElement.getContext()")}}
+
Returns a drawing context on the canvas, or null if the context ID is not supported. A drawing context lets you draw on the canvas. Calling getContext with "2d" returns a {{domxref("CanvasRenderingContext2D")}} object, whereas calling it with "experimental-webgl" (or "webgl") returns a {{domxref("WebGLRenderingContext")}} object. This context is only available on browsers that implement WebGL.
+
{{domxref("HTMLCanvasElement.toDataURL()")}}
+
Returns a data-URL containing a representation of the image in the format specified by the type parameter (defaults to png). The returned image is in a resolution of 96dpi.
+
{{domxref("HTMLCanvasElement.toBlob()")}}
+
Creates a {{domxref("Blob")}} object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent.
+
{{domxref("HTMLCanvasElement.transferControlToOffscreen()")}} {{experimental_inline}}
+
Transfers control to an {{domxref("OffscreenCanvas")}} object, either on the main thread or on a worker.
+
{{domxref("HTMLCanvasElement.mozGetAsFile()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns a {{domxref("File")}} object representing the image contained in the canvas; this file is a memory-based file, with the specified name. If type is not specified, the image type is image/png.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture DOM Elements', '#html-media-element-media-capture-extensions', 'HTMLCanvasElement')}}{{Spec2('Media Capture DOM Elements')}}Adds the method captureStream().
{{SpecName('HTML WHATWG', "#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML WHATWG')}}The method getContext() now returns a {{domxref("RenderingContext")}} rather than an opaque object.
+ The methods probablySupportsContext(), setContext() and transferControlToProxy()have been added.
{{SpecName('HTML5.1', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (2D context)4.0{{CompatVersionUnknown}}{{CompatGeckoDesktop('1.9.2')}}9.09.0 [1]3.1
toBlob()50{{CompatNo}}{{CompatGeckoDesktop('19')}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}} (bug 71270)
probablySupportsContext(),
+ setContext(),
+ transferControlToProxy() {{obsolete_inline}}
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozGetAsFile() {{non-standard_inline}} {{deprecated_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop('2')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
captureStream() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop('41')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
transferControlToOffscreen() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop(44)}} [3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (2D context)2.1{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}10.0 [1]3.2
webgl context{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} as experimental-webgl{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
toBlob(){{CompatNo}} (bug 67587)50{{CompatNo}}{{CompatGeckoMobile('18')}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}} (bug 71270)
probablySupportsContext(),
+ setContext(),
+ transferControlToProxy() {{obsolete_inline}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozGetAsFile() {{non-standard_inline}} {{deprecated_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile('2')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
captureStream() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile('41')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
transferControlToOffscreen() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(44)}} [3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Opera Mini 5.0 and later has partial support.

+ +

[2] Support for the third parameter, has been added in Gecko 25 only: when used with the "image/jpeg" type, this argument specifies the image quality.

+ +

[3] This feature is behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true.

+ +

See also

+ + diff --git a/files/pt-br/web/api/htmlcanvaselement/todataurl/index.html b/files/pt-br/web/api/htmlcanvaselement/todataurl/index.html new file mode 100644 index 0000000000..503f9cb636 --- /dev/null +++ b/files/pt-br/web/api/htmlcanvaselement/todataurl/index.html @@ -0,0 +1,157 @@ +--- +title: HTMLCanvasElement.toDataURL() +slug: Web/API/HTMLCanvasElement/toDataURL +tags: + - API + - Canvas + - HTMLCanvasElement + - Imagens +translation_of: Web/API/HTMLCanvasElement/toDataURL +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

O método HTMLCanvasElement.toDataURL() retorna uma data URI, contendo uma representação da imagem no formato especificado pelo parâmetro type (por padrão, esse valor é PNG). A resolução da imagem retornada é de 96 dpi.

+ + + +

Sintaxe

+ +
canvas.toDataURL(type, encoderOptions);
+
+ +

Parâmetros

+ +
+
type {{optional_inline}}
+
Uma {{domxref("DOMString")}} indicando o formato da imagem. Por padrão, o formato definido é image/png.
+
encoderOptions {{optional_inline}}
+
Um {{jsxref("Number")}} entre 0 e 1, indicando a qualidade da imagem solicitada pelo tipo image/jpeg ou image/webp.
+ Se esse argumento for outro valor que não de 0 a 1, então o valor padrão (0.92) será usado. Outros valores serão ignorados.
+
+ +

Valor retornado

+ +

Uma {{domxref("DOMString")}} contendo a data URI solicitada.

+ +

Exemplos

+ +

Dado este elemento {{HTMLElement("canvas")}}:

+ +
<canvas id="canvas" width="5" height="5"></canvas>
+
+ +

Você poderá capturar a data-URL do canvas com as seguintes linhas:

+ +
var canvas = document.getElementById('canvas');
+var dataURL = canvas.toDataURL();
+console.log(dataURL);
+// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
+// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
+
+ +

Defindo a qualidade de imagens jpeg

+ +
var fullQuality = canvas.toDataURL('image/jpeg', 1.0);
+// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...9oADAMBAAIRAxEAPwD/AD/6AP/Z"
+var mediumQuality = canvas.toDataURL('image/jpeg', 0.5);
+var lowQuality = canvas.toDataURL('image/jpeg', 0.1);
+
+ +

Exemplo: Alterando imagens dinamicamente

+ +

Você poderá utilizar esta técnica em associação com os eventos do mouse para alterar dinamicamente uma imagem (escala de cinza vs. cor, neste exemplo):

+ +

HTML

+ +
<img class="grayscale" src="myPicture.png" alt="Description of my picture" />
+ +

JavaScript

+ +
window.addEventListener('load', removeColors);
+
+function showColorImg() {
+  this.style.display = 'none';
+  this.nextSibling.style.display = 'inline';
+}
+
+function showGrayImg() {
+  this.previousSibling.style.display = 'inline';
+  this.style.display = 'none';
+}
+
+function removeColors() {
+  var aImages = document.getElementsByClassName('grayscale'),
+      nImgsLen = aImages.length,
+      oCanvas = document.createElement('canvas'),
+      oCtx = oCanvas.getContext('2d');
+  for (var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; nImgId < nImgsLen; nImgId++) {
+    oColorImg = aImages[nImgId];
+    nWidth = oColorImg.offsetWidth;
+    nHeight = oColorImg.offsetHeight;
+    oCanvas.width = nWidth;
+    oCanvas.height = nHeight;
+    oCtx.drawImage(oColorImg, 0, 0);
+    oImgData = oCtx.getImageData(0, 0, nWidth, nHeight);
+    aPix = oImgData.data;
+    nPixLen = aPix.length;
+    for (nPixel = 0; nPixel < nPixLen; nPixel += 4) {
+      aPix[nPixel + 2] = aPix[nPixel + 1] = aPix[nPixel] = (aPix[nPixel] + aPix[nPixel + 1] + aPix[nPixel + 2]) / 3;
+    }
+    oCtx.putImageData(oImgData, 0, 0);
+    oGrayImg = new Image();
+    oGrayImg.src = oCanvas.toDataURL();
+    oGrayImg.onmouseover = showColorImg;
+    oColorImg.onmouseout = showGrayImg;
+    oCtx.clearRect(0, 0, nWidth, nHeight);
+    oColorImg.style.display = "none";
+    oColorImg.parentNode.insertBefore(oGrayImg, oColorImg);
+  }
+}
+ +

Especificações

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

Compatibilidade entre navegadores

+ + + +

{{Compat("api.HTMLCanvasElement.toDataURL")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlcollection/index.html b/files/pt-br/web/api/htmlcollection/index.html new file mode 100644 index 0000000000..4d462b4b6a --- /dev/null +++ b/files/pt-br/web/api/htmlcollection/index.html @@ -0,0 +1,68 @@ +--- +title: HTMLCollection +slug: Web/API/HTMLCollection +translation_of: Web/API/HTMLCollection +--- +

{{APIRef("HTML DOM")}}

+ +

A interface HTMLCollection representa uma coleção genérica (objeto array) de elementos (na ordem em que aparecem no documento) e oferece métodos e propriedades para selecioná-los da lista.

+ +
Nota: Esta interface é chamada HTMLCollection por razões históricas (antes do DOM4, coleções implementadas por esta interface somente podiam ter elementos HTML).
+ +

Uma coleção HTMLCollection de um HTML DOM está linkada com o documento; ela será automaticamente atualizada quando o documento for modificado.

+ +

Propriedades

+ +
+
{{domxref("HTMLCollection.length")}} {{readonlyInline}}
+
Retorna o número de itens da coleção.
+
+ +

Métodos

+ +
+
{{domxref("HTMLCollection.item()")}}
+
Retorna um nó especificado por index da lista. o primeiro index da lista é 0. Retorna null se index não existir na lista.
+
{{domxref("HTMLCollection.namedItem()")}}
+
Retorna o nó especificado pelo ID ou, caso não tenha ID, o item cuja propriedade name seja igual à pesquisa. Pesquisa por name só é feita em último caso, somente em HTML, e somente se os elementos referenciados suportarem o atributo name. Retorna null se nenhum nó corresponder ao nome pesquisado.
+
+ +

Uso no JavaScript

+ +

HTMLCollection expõe seus membros diretamente como propriedades, tanto por nome quanto por índice. IDs HTML podem conter : e . como caracteres válidos, o que fará necessária a utilização de colchetes para acessar as propriedades. Atualmente HTMLCollection não reconhece IDs puramente numéricos, o que pode causar conflitos com acesso em formato array, apesar do HTML5 os permitir.

+ +

Por exemplo, assumindo que há um elemento <form> no documento e seu id é "myForm":

+ +
var elem1, elem2;
+
+// document.forms é um HTMLCollection
+
+elem1 = document.forms[0];
+elem2 = document.forms.item(0);
+
+alert(elem1 === elem2); // exibe: "true"
+
+elem1 = document.forms.myForm;
+elem2 = document.forms.namedItem("myForm");
+
+alert(elem1 === elem2); // exibe: "true"
+
+elem1 = document.forms["named.item.with.periods"];
+ +

Compatibilidade entre Browsers

+ +

Diferentes browsers se comportam de maneira diferente quando um os mais elementos são pesquisados pela string utilizada  como índice (ou o argumento namedItem). Firefox 8 se comporta como especificado no DOM 2 e no DOM 4, retornando o primeiro elemento encontrado. WebKit browsers e o Internet Explorer, neste caso, retornam outro HTMLCollection e o Opera retorna um {{domxref("NodeList")}} com todos os elementos encontrados.

+ +

Especificações

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlcontentelement/getdistributednodes/index.html b/files/pt-br/web/api/htmlcontentelement/getdistributednodes/index.html new file mode 100644 index 0000000000..fa6b3bb8dc --- /dev/null +++ b/files/pt-br/web/api/htmlcontentelement/getdistributednodes/index.html @@ -0,0 +1,100 @@ +--- +title: HTMLContentElement.getDistributedNodes() +slug: Web/API/HTMLContentElement/getDistributedNodes +tags: + - Componente web + - HTML DOM + - HTMLContentElement + - HTMLContentElement.getDistributedNodes() + - Property + - getDistributedNodes() +translation_of: Web/API/HTMLContentElement/getDistributedNodes +--- +

{{ APIRef("Web Components") }}

+ +

O método HTMLContentElement.getDistributedNodes() retorna um static {{domxref("NodeList")}} do {{glossary("distributed nodes")}} associado com este elemento <content>.

+ +

Syntaxe

+ +
var nodeList = object.getDistributedNodes()
+
+ +

Exemplo

+ +
//Pegue os nós distribuídos
+var nodes = myContentObject.getDistributedNodes();
+ +

Specificações

+ + + + + + + + + + + + + + +
SpecificaçõesStatusComentário
{{SpecName('Shadow DOM', '#the-content-element', 'content')}}{{Spec2('Shadow DOM')}} 
+ +

Compatibilidade do browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
ComponenteChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Supporte básico35{{CompatGeckoDesktop("28")}} [1]{{CompatNo}}26{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support37{{CompatGeckoMobile("28")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Se Shadow DOM não é habilitado no Firefox, <content> elementos se comportará como {{domxref("HTMLUnknownElement")}}. Shadow DOM foi primeiro implementado em Firefox 28 e está atrás de uma preferência, dom.webcomponents.enabled, ao qual é desabilitado por padrão.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlcontentelement/index.html b/files/pt-br/web/api/htmlcontentelement/index.html new file mode 100644 index 0000000000..b3a23164a6 --- /dev/null +++ b/files/pt-br/web/api/htmlcontentelement/index.html @@ -0,0 +1,116 @@ +--- +title: HTMLContentElement +slug: Web/API/HTMLContentElement +tags: + - ContentElement + - Deprecated_header + - HTMLContentElement + - HTMLElement + - Web Components + - elemento depreciado + - shadow dom +translation_of: Web/API/HTMLContentElement +--- +

{{ APIRef("Web Components") }}

+ +

{{Deprecated_header}}

+ +

A interface do HTMLContentElement representa um {{HTMLElement("content")}} Element HTML, ao qual é usado em Shadow DOM

+ +

Propriedades

+ +

Esta interface herda as propriedades de {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLContentElement.select")}}
+
é um {{domxref("DOMString")}} que reflete o {{ htmlattrxref("select", "content") }} attributo HTML . O valor é uma lista de vírgula separada dos seletores CSS que selecionam o conteúdo para inserir em lugar do elemento <content>.
+
+ +

Méthodos

+ +

Esta interface herda os méthodos de {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLContentElement.getDistributedNodes()")}}
+
Returna um static {{domxref("NodeList")}} do {{glossary("distributed nodes")}} associado com este elemento <content>
+
+ +

Specificações

+ + + + + + + + + + + + + + +
SpecificaçõesStatusCommentários
{{SpecName('Shadow DOM', '#the-content-element', 'content')}}{{Spec2('Shadow DOM')}} 
+ +

Compatibilidade do browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
ComponentesChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico35{{CompatGeckoDesktop("28")}} [1]{{CompatNo}}26{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support37{{CompatGeckoMobile("28")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Se Shadow DOM não é habilitado no Firefox, <content> elementos vai se comportar como {{domxref("HTMLUnknownElement")}}. Shadow DOM foi a primeira implementação do Firefox 28 e está atrásde uma preferência , dom.webcomponents.enabled, qual é desabilitado por padrão.

+ +

Veja também

+ + + +
+
 
+
diff --git a/files/pt-br/web/api/htmlcontentelement/seletor/index.html b/files/pt-br/web/api/htmlcontentelement/seletor/index.html new file mode 100644 index 0000000000..63fae05c69 --- /dev/null +++ b/files/pt-br/web/api/htmlcontentelement/seletor/index.html @@ -0,0 +1,98 @@ +--- +title: HTMLContentElement.select +slug: Web/API/HTMLContentElement/Seletor +tags: + - API + - HTMLContentElement + - HTMLContentElement.select + - Select +translation_of: Web/API/HTMLContentElement/select +--- +

{{ APIRef("Web Components") }}

+ +

A propriedade HTMLContentElement.select reflete o atributo selecionado. É um {{domxref("DOMString")}} contendo uma lista de spaço-separado de seletores CSS que seleciona o conteúdo para inserir em lugar do elemento <content>.

+ +

Sintaxe

+ +
object.select = "CSSselector CSSselector ...";
+
+ +

Exemplo

+ +
// Select <h1> elements and elements with class="error"
+myContentObject.select = "h1 .error";
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusCommentário
{{SpecName('Shadow DOM', '#the-content-element', 'content')}}{{Spec2('Shadow DOM')}} 
+ +

Compatibilidade do browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
ComponenteChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico35{{CompatGeckoDesktop("28")}} [1]{{CompatNo}}26{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico37{{CompatGeckoMobile("28")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Se Shadow DOM não estiver habilitado no Firefox, os elementos <content> se comportarão como {{domxref("HTMLUnknownElement")}}. Shadow DOM foi o primeiro implementado no Firefox 28 e está atrás de uma preferência, dom.webcomponents.enabled, ao qual é desabilitado por padrão.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmldivelement/index.html b/files/pt-br/web/api/htmldivelement/index.html new file mode 100644 index 0000000000..f658b94f06 --- /dev/null +++ b/files/pt-br/web/api/htmldivelement/index.html @@ -0,0 +1,133 @@ +--- +title: HTMLDivElement +slug: Web/API/HTMLDivElement +tags: + - API + - HTMLDivElement + - Interface + - PrecisaNovoLayout + - Referência(2) +translation_of: Web/API/HTMLDivElement +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +
 
+ +

A interface HTMLDivElement fornece propriedades especiais ( além da interface normal {{domxref ("HTMLElement")}} que também está a sua disposição por herança ) para manipular elementos div.

+ +

{{InheritanceDiagram(600,120)}}

+ +

Propriedades

+ +

As propriedades são herdadas de seu pai, {{domxref("HTMLElement")}}.

+ + + + + + + + + + + + + + +
NomeTipoDescrição
align {{obsolete_inline}}{{domxref("DOMString")}}Propriedade enumerada indicando alinhamento  dos conteúdos do elemento, respeitando ao contexto geral. Os valores possíveis são "left", "right", "justify", e"center".
+ +

Métodos

+ +

Nenhum método específico; os métodos são herdados de seu pai, {{domxref ("HTMLElement")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "grouping-content.html#the-div-element", "HTMLDivElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "grouping-content.html#the-div-element", "HTMLDivElement")}}{{Spec2('HTML5 W3C')}}No change from {{SpecName("DOM2 HTML")}}.
{{SpecName('DOM2 HTML', 'html.html#ID-22445964', 'HTMLDivElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-22445964', 'HTMLDivElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Compatibilidade de Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Ver também

+ + diff --git a/files/pt-br/web/api/htmlelement/blur/index.html b/files/pt-br/web/api/htmlelement/blur/index.html new file mode 100644 index 0000000000..25a2273aec --- /dev/null +++ b/files/pt-br/web/api/htmlelement/blur/index.html @@ -0,0 +1,89 @@ +--- +title: HTMLElement.blur() +slug: Web/API/HTMLElement/blur +tags: + - API + - DOM HTML + - Foco + - HTMLElement + - Referencia + - metodo +translation_of: Web/API/HTMLOrForeignElement/blur +--- +
{{ APIRef("HTML DOM") }}
+ +

O método HTMLElement.blur() remove o foco do teclado no elemento corrente.

+ +

Sintaxe

+ +
elemento.blur();
+ +

Exemplos

+ +

Removendo o foco de um input de texto

+ +

HTML

+ +
<input type="text" id="meuTexto" value="Texto Exemplo">
+<br><br>
+<button type="button" onclick="focusInput()">Clique para definir o foco</button>
+<button type="button" onclick="blurInput()">Clique para remover o foco</button>
+ +

JavaScript

+ +
function focusInput() {
+  document.getElementById('meuTexto').focus();
+}
+function blurInput() {
+  document.getElementById('meuTexto').blur();
+}
+ +

Resultado

+ +

{{ EmbedLiveSample('Remove_focus_from_a_text_input') }}

+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'editing.html#dom-blur', 'blur')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', 'editing.html#blur()-0', 'blur')}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', 'editing.html#dom-blur', 'blur')}}{{Spec2('HTML5 W3C')}} 
{{SpecName('DOM2 HTML', 'html.html#ID-28216144', 'blur')}}{{Spec2('DOM2 HTML')}} 
+ +

Compatibilidade com navegadores

+ + + +

{{Compat("api.HTMLElement.blur")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlelement/click/index.html b/files/pt-br/web/api/htmlelement/click/index.html new file mode 100644 index 0000000000..8bfe8a9d66 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/click/index.html @@ -0,0 +1,115 @@ +--- +title: HTMLElement.click() +slug: Web/API/HTMLElement/click +tags: + - API + - HTML DOM + - HTMLElement + - Method + - Reference +translation_of: Web/API/HTMLElement/click +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

O método HTMLElement.click() simula o clique do mouse em um elemento.

+ +

Quando clique é usado com elementos que o suportam (por exemplo, um dos {{HTMLElement ("input")}} tipos listados acima), ele também dispara evento de clique do elemento que vai propagar pelos elementos mais acima na árvore de documentos (ou cadeia do evento) e disparando seus eventos de clique também. No entanto, o evento de clique, propagado como bubble, não vai iniciar a navegação do elemento {{HTMLElement("a")}} como se uma verdadeiro clique do mouse tivesse sido recebido. 

+ +

Sintaxe

+ +
elt.click()
+ +

Especificação

+ + + + + + + + + + + + + + + + +
SpecificationStatusComentário
{{SpecName('DOM2 HTML', 'html.html#ID-2651361')}}{{Spec2('DOM2 HTML')}}Initial definition
+ +

Browser compatibilidade

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support20[3]5[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]6[3]
input@file (limited){{CompatVersionUnknown}}4{{CompatVersionUnknown}}12.10{{CompatVersionUnknown}}
input@file (full){{CompatVersionUnknown}}4{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Antes Gecko 5.0 {{geckoRelease("5.0")}}, Gecko não implementa o método de clique em outros elementos que podem ser esperados para responder a cliques do mouse como links (elementos {{HTMLElement("a")}}), nem seria necessariamente acionado o evento clique de outros elementos.

+ +

[2] Em versões do Opera o método click() irá silenciosamente ser ignorado se for realizado baseado no motor de layout Presto em {{HTMLElement("input")}} com o atributo type definido para o arquivo e seu CSS {{cssxref('display')}} propriedade definida como nenhum.

+ +

[3] As versões mais antigas tinham HTMLInputElement.click() e HTMLButtonElement.click() apenas.

diff --git a/files/pt-br/web/api/htmlelement/contenteditable/index.html b/files/pt-br/web/api/htmlelement/contenteditable/index.html new file mode 100644 index 0000000000..22d356ae0d --- /dev/null +++ b/files/pt-br/web/api/htmlelement/contenteditable/index.html @@ -0,0 +1,102 @@ +--- +title: HTMLElement.contentEditable +slug: Web/API/HTMLElement/contentEditable +translation_of: Web/API/HTMLElement/contentEditable +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

A propriedade HTMLElement.contentEditable é usada para indicar se o elemento é editável ou não. Esse atributo enumerado pode ter os seguintes valores:

+ + + +

Você pode usar a propriedade {{domxref( "HTMLElement.isContentEditable")}} para testar o valor calculado {{domxref ("Boolean")}} desta propriedade.

+ +

Sintaxe

+ +
editable = element.contentEditable element.contentEditable= "true"
+
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'interaction.html#contenteditable', 'contenteditable')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Compatibilidade Browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support11{{CompatGeckoDesktop(1.9)}}6[1]10.63.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3{{CompatGeckoMobile(1.9)}}6[1]{{CompatNo}}5
+
+ +

[1] Internet Explorer has a bunch of bugs regarding the implementation of this feature. IE10 crashes in some cases when editing lists (bug 796187). IE11+ uses invalid positioning for caret when an element is floated (bug 858749). In IE9-10 the window freezes when using mousewheel while dragging (bug 809254). IE10-11 does not fire the input event (bug 794285). IE10 crashes after selecting "Cut" from the context menu (bug 801770). IE11+ does not allow placing the caret in an empty table cell (bug 807199). IE10 does not fire contextmenu event when right-clicking on misspelled words (bug 774350). IE11 appends {{HTMLElement("br")}} elements to {{HTMLElement("body")}} when showing/hiding an {{HTMLElement("iframe")}} with contenteditable document inside (bug 864804). IE11 does not allow disabling resize handles for images/inputs (bug 907422).

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlelement/contextmenu/index.html b/files/pt-br/web/api/htmlelement/contextmenu/index.html new file mode 100644 index 0000000000..e03c61a256 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/contextmenu/index.html @@ -0,0 +1,44 @@ +--- +title: HTMLElement.contextMenu +slug: Web/API/HTMLElement/contextMenu +tags: + - API + - Depreciado + - Elemento + - HTML + - HTML DOM + - Propriedade + - Referencia + - UX +translation_of: Web/API/HTMLElement/contextMenu +--- +
{{APIRef("HTML DOM")}}{{deprecated_header()}} +

A propriedade HTMLElement.contextMenu refere-se ao menu de contexo atribuído aum elemento usando o {{htmlattrxref("contextmenu")}} atributo. O menu em sí é criado usando o {{HTMLElement("menu")}} elemento.

+ +

Sintaxe

+ +
var elementContextMenu = element.contextMenu;
+
+ +

Exemplo

+ +
var contextMenu = document.getElementById("element").contextMenu;
+
+// Altere o label da primeira entrada do menu
+contextMenu.firstElementChild.label = "New label";
+
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.HTMLElement.contextMenu")}}

+ +

Veja também

+ + +
diff --git a/files/pt-br/web/api/htmlelement/dataset/index.html b/files/pt-br/web/api/htmlelement/dataset/index.html new file mode 100644 index 0000000000..2cb4ba63b0 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/dataset/index.html @@ -0,0 +1,97 @@ +--- +title: HTMLElement.dataset +slug: Web/API/HTMLElement/dataset +translation_of: Web/API/HTMLOrForeignElement/dataset +--- +

{{ APIRef }}

+ +

A propriedade HTMLElement.dataset permite o acesso, em modo de leitura e escrita, a todos os atributos de dados personalizado (data-*) no elemento. Ele é um mapa de DOMString, com uma entrada para cada atributo de dados personalizado.

+ +

O nome de um atributo de dados customizado inicia com data-. Ele deve conter somente letras, números e os seguintes caracteres: dash (-), dot (.), collon(:), underscore (_). Além disso, ele não deve conter letras ASCII captalizadas (A à Z).

+ +

Um atributo de dados personalizado é transformado em uma chave para uma entrada no {{ domxref("DOMStringMap") }} de acordo com as seguintes regras

+ + + +

A transformação oposta, que mapeia uma chave para um nome de atributo, usa as seguintes regras:

+ + + +

A restrição nas regras acima garantem que as duas trasnformações são inversa uma da outra.

+ +

Por exemplo, o atributo data-abc-def corresponde a chave abcDef.

+ +

Sintaxe

+ +
string = element.dataset.camelCasedName;
+element.dataset.camelCasedName = string;
+ +

Exemplos

+ +
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe
+</div>
+
+var el = document.querySelector('#user');
+
+// el.id == 'user'
+// el.dataset.id === '1234567890'
+// el.dataset.user === 'johndoe'
+// el.dataset.dateOfBirth === ''
+
+el.dataset.dateOfBirth = '1960-10-03'; // set the DOB.
+
+// 'someDataAttr' in el.dataset === false
+
+el.dataset.someDataAttr = 'mydata';
+// 'someDataAttr' in el.dataset === true
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspeficicaçãoStatusComentário
{{SpecName('HTML WHATWG', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML WHATWG')}}Sem mudanças desde o último  snapshot, {{SpecName('HTML5.1')}}
{{SpecName('HTML5.1', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5.1')}}Snapshot de {{SpecName('HTML WHATWG')}}, sem mudanças desde {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5 W3C')}}Snapshot de {{SpecName('HTML WHATWG')}}, definição inicial.
+ +

Compatibilidade com Browsers

+ + + +

{{Compat("api.HTMLElement.dataset")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlelement/focus/index.html b/files/pt-br/web/api/htmlelement/focus/index.html new file mode 100644 index 0000000000..8f798b3d86 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/focus/index.html @@ -0,0 +1,62 @@ +--- +title: HTMLElement.focus() +slug: Web/API/HTMLElement/focus +translation_of: Web/API/HTMLOrForeignElement/focus +--- +
{{ APIRef("HTML DOM") }}
+ +

O método HTMLElement.focus()  seta o foco em um determinado elemento em especifico, caso esse elemento permita ter o foco neste elemento.

+ +

Síntaxe

+ +
element.focus()
+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'editing.html#dom-focus', 'focus')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', 'editing.html#focus()-0', 'focus')}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', 'editing.html#dom-focus', 'focus')}}{{Spec2('HTML5 W3C')}} 
{{SpecName('DOM2 HTML', 'html.html#ID-32130014', 'focus')}}{{Spec2('DOM2 HTML')}} 
{{SpecName('DOM1', 'level-one-html.html#method-focus', 'focus')}}{{Spec2('DOM1')}} 
+ +

Notas

+ +

Caso você utilize o HTMLElement.focus() por meio da manipulação de um evento mousedown , você deve utilizar o evento event.preventDefault() a fim de o foco não sair do arquivo HTMLElement.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlelement/index.html b/files/pt-br/web/api/htmlelement/index.html new file mode 100644 index 0000000000..f264d6158b --- /dev/null +++ b/files/pt-br/web/api/htmlelement/index.html @@ -0,0 +1,410 @@ +--- +title: HTMLElement +slug: Web/API/HTMLElement +tags: + - API + - HTML DOM + - Interface + - NeedsMobileBrowserCompatibility + - NeedsNewLayout + - NeedsTranslation + - Reference + - Référence(2) + - TopicStub +translation_of: Web/API/HTMLElement +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +
 
+ +

A interface HTMLElement representa qualquer elemento HTML. Alguns elementos implementam diretamente essa interface, outros a implementam por meio de uma interface que a herda.

+ +

Propriedades

+ +

Propriedades herdadas do elemento pai, {{domxref("Element")}}, e aquelas implementadas de {{domxref("GlobalEventHandlers")}} e de {{domxref("TouchEventHandlers")}}.

+ +
+
{{domxref("HTMLElement.accessKey")}}
+
Is a {{domxref("DOMString")}} representing the access key assigned to the element.
+
{{domxref("HTMLElement.accessKeyLabel")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the element's assigned access key.
+
{{domxref("HTMLElement.contentEditable")}}
+
Is a {{domxref("DOMString")}}, where a value of "true" means the element is editable and a value of "false" means it isn't.
+
{{domxref("HTMLElement.isContentEditable")}} {{readonlyInline}}
+
Returns a {{domxref("Boolean")}} that indicates whether or not the content of the element can be edited.
+
{{domxref("HTMLElement.contextMenu")}}
+
Is an {{domxref("HTMLMenuElement")}} representing the contextual menu associated with the element. It may be null
+
{{domxref("HTMLElement.dataset")}} {{readonlyInline}}
+
Returns a {{domxref("DOMStringMap")}} that allows access to read and write the element custom data attributes (data-*) .
+
{{domxref("HTMLElement.dir")}}
+
Is a {{domxref("DOMString")}}, reflecting the dir global attribute, representing the directionality of the element. Possible values are "ltr", "rtl", and "auto".
+
{{domxref("HTMLElement.draggable")}}
+
Is a {{jsxref("Boolean")}} indicating if the element can be dragged.
+
{{domxref("HTMLElement.dropzone")}} {{readonlyInline}}
+
Returns a {{domxref("DOMSettableTokenList")}} reflecting the dropzone global attribute and describing the behavior of the element regarding a drop operation.
+
{{domxref("HTMLElement.hidden")}}
+
Is a {{jsxref("Boolean")}} indicating if the element is hidden or not.
+
{{domxref("HTMLElement.itemScope")}} {{experimental_inline}}
+
Is a {{jsxref("Boolean")}}…
+
{{domxref("HTMLElement.itemType")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("DOMSettableTokenList")}}…
+
{{domxref("HTMLElement.itemId")}} {{experimental_inline}}
+
Is a {{domxref("DOMString")}}…
+
{{domxref("HTMLElement.itemRef")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("DOMSettableTokenList")}}…
+
{{domxref("HTMLElement.itemProp")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("DOMSettableTokenList")}}…
+
{{domxref("HTMLElement.itemValue")}} {{experimental_inline}}
+
Returns an {{jsxref("Object")}}…
+
{{domxref("HTMLElement.lang")}}
+
Is a {{domxref("DOMString")}} representing the language of an element's attributes, text, and element contents.
+
{{domxref("HTMLElement.offsetHeight")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a double containing the height of an element, relative to the layout.
+
{{domxref("HTMLElement.offsetLeft")}}{{readonlyInline}}{{experimental_inline}}
+
Returns a double, the distance from this element's left border to its offsetParent's left border.
+
{{domxref("HTMLElement.offsetParent")}}{{readonlyInline}}{{experimental_inline}}
+
Returns an {{domxref("Element")}} that is the element from which all offset calculations are currently computed.
+
{{domxref("HTMLElement.offsetTop")}}{{readonlyInline}}{{experimental_inline}}
+
Returns a double, the distance from this element's top border to its offsetParent's top border.
+
{{domxref("HTMLElement.offsetWidth")}}{{readonlyInline}}{{experimental_inline}}
+
Returns a double containing the width of an element, relative to the layout.
+
{{domxref("HTMLElement.properties")}} {{readonlyInline}}{{experimental_inline}}
+
Returns an {{domxref("HTMLPropertiesCollection")}}…
+
{{domxref("HTMLElement.spellcheck")}}{{ gecko_minversion_inline("1.9")}}
+
Is a {{jsxref("Boolean")}} that controls spell-checking. It is present on all HTML elements, though it hasn't an effect on all of them.
+
{{domxref("HTMLElement.style")}}
+
Is {{domxref("CSSStyleDeclaration")}}, an object representing the declarations of an element's style attributes.
+
{{domxref("HTMLElement.tabIndex")}}
+
Is a long representing the position of the element in the tabbing order.
+
{{domxref("HTMLElement.title")}}
+
Is a {{domxref("DOMString")}} containing the text that appears in a popup box when mouse is over the element.
+
{{domxref("HTMLElement.translate")}} {{experimental_inline}}
+
Is a {{jsxref("Boolean")}}
+
+ +

Event handlers

+ +

Most events properties, of the form onXYZ, are defined on the {{domxref("GlobalEventHandlers")}} or {{domxref("TouchEventHandlers")}}, implemented by HTMLElement. A few more are specific to HTMLElement.

+ +
+
{{ domxref("HTMLElement.oncopy") }}  {{ non-standard_inline() }}
+
Returns the event handling code for the copy event ({{bug("280959")}}).
+
{{ domxref("HTMLElement.oncut") }}  {{ non-standard_inline() }}
+
Returns the event handling code for the cut event ({{bug("280959")}}).
+
{{ domxref("HTMLElement.onpaste") }} {{ non-standard_inline() }}
+
Returns the event handling code for the paste event ({{bug("280959")}}).
+
{{domxref("TouchEventHandlers.ontouchstart")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchstart")}} event.
+
{{domxref("TouchEventHandlers.ontouchend")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchend")}} event.
+
{{domxref("TouchEventHandlers.ontouchmove")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchmove")}} event.
+
{{domxref("TouchEventHandlers.ontouchenter")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchenter")}} event.
+
{{domxref("TouchEventHandlers.ontouchleave")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchleave")}} event.
+
{{domxref("TouchEventHandlers.ontouchcancel")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchcancel")}} event.
+
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("Element")}}.

+ +
+
{{domxref("HTMLElement.blur()")}}
+
Removes keyboard focus from the currently focused element.
+
{{domxref("HTMLElement.click()")}}
+
Sends a mouse click event to the element.
+
{{domxref("HTMLElement.focus()")}}
+
Makes the element the current keyboard focus.
+
{{domxref("HTMLElement.forceSpellCheck()")}} {{experimental_inline}}
+
Makes the spell checker runs on the element.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#extensions-to-the-htmlelement-interface', 'HTMLElement')}}{{Spec2('CSSOM View')}}Added the following properties: offsetParent, offsetTop, offsetLeft, offsetWidth, and offsetHeight.
{{SpecName('HTML WHATWG', 'elements.html#htmlelement', 'HTMLElement')}}{{Spec2('HTML WHATWG')}}Added the following properties: translate, itemScope, itemType, itemId, itemRef, itemProp, properties, and itemValue.
+ Added the following method: forceSpellcheck().
+ Moved the onXYZ attributes to the {{domxref("GlobalEventHandlers")}} interface and added an inheritance from it.
{{SpecName('HTML5 W3C', 'dom.html#htmlelement', 'HTMLElement')}}{{Spec2('HTML5 W3C')}}Added the following properties: dataset, hidden, tabindex, accessKey, accessKeyLabel, draggable, dropzone, contentEditable, isContentEditable, contextMenu, spellcheck, commandType, commandLabel, commandIcon, commandHidden, commandDisabled, commandChecked, style, and all the onXYZ properties.
+ Moved the id and className properties to the {{domxref("Element")}} interface.
{{SpecName('DOM2 HTML', 'html.html#ID-011100101', 'HTMLElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName('DOM2 HTML')}}
{{SpecName('DOM1', 'level-one-html.html#ID-011100101', 'HTMLElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("1.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.accessKey", "accessKey")}}{{CompatGeckoDesktop("5.0")}}17.0{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}(535.10)
{{domxref("HTMLElement.accessKeyLabel", "accessKeyLabel")}}{{CompatGeckoDesktop("8.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{WebkitBug(72715)}}
{{domxref("HTMLElement.blur()", "blur()")}}{{CompatGeckoDesktop("5.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.click()", "click()")}}{{CompatGeckoDesktop("5.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}(535.24)
{{domxref("HTMLElement.dataset", "dataset")}}{{CompatGeckoDesktop("6.0")}}9.0{{CompatUnknown}}11.105.1
{{domxref("HTMLElement.focus()", "focus()")}}{{CompatGeckoDesktop("5.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.contentEditable", "contentEditable")}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}}5.59{{CompatVersionUnknown}}
{{domxref("HTMLElement.spellcheck", "spellcheck")}}{{CompatGeckoDesktop("1.8.1")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.style", "style")}}{{CompatVersionUnknown}} (returns a {{domxref("CSS2Properties")}}, rather than a {{domxref("CSSStyleDeclaration")}}){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("HTMLElement.forceSpellCheck", "forceSpellCheck()")}} {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("HTMLElement.dataset", "dataset")}}{{CompatGeckoDesktop("6.0")}}8.01111.106
{{domxref("HTMLElement.draggable", "draggable")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}12.0{{CompatUnknown}}
{{domxref("HTMLElement.dropzone", "dropzone")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}12.0{{CompatNo}}
{{domxref("HTMLElement.offsetLeft", "offsetLeft")}}, {{domxref("HTMLElement.offsetTop", "offsetTop")}}, {{domxref("HTMLElement.offsetParent", "offsetParent")}}, {{domxref("HTMLElement.offsetHeight", "offsetHeight")}} and {{domxref("HTMLElement.offsetWidth", "offsetWidth")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.translate", "translate")}} {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("HTMLElement.itemScope", "itemScope")}}, {{domxref("HTMLElement.itemType", "itemType")}}, {{domxref("HTMLElement.itemRef", "itemRef")}}, {{domxref("HTMLElement.itemId", "itemId")}}, {{domxref("HTMLElement.itemProp", "itemProp")}}, and {{domxref("HTMLElement.itemValue", "itemValue")}} {{experimental_inline}}{{CompatGeckoDesktop("6.0")}}{{CompatNo}}{{CompatNo}}11.60
+ (Removed in Opera 15)
{{CompatNo}}
{{domxref("HTMLElement.properties", "properties")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.ontouchstart")}}, {{domxref("HTMLElement.ontouchend")}}, {{domxref("HTMLElement.ontouchmove")}}, {{domxref("HTMLElement.ontouchenter")}}, {{domxref("HTMLElement.ontouchleave")}}, and {{domxref("HTMLElement.ontouchcancel")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
{{domxref("HTMLElement.oncopy")}}, {{domxref("HTMLElement.oncut")}}, and {{domxref("HTMLElement.onpaste")}} {{Non-standard_inline}}{{CompatGeckoDesktop("1.9")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support +

{{CompatGeckoMobile("1.0")}}

+
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.accessKey", "accessKey")}}{{CompatGeckoMobile("5.0")}}
{{domxref("HTMLElement.accessKeyLabel", "accessKeyLabel")}}{{CompatGeckoMobile("8.0")}}
{{domxref("HTMLElement.blur()", "blur()")}}{{CompatGeckoMobile("5.0")}}
{{domxref("HTMLElement.click()", "click()")}}{{CompatGeckoMobile("5.0")}}
{{domxref("HTMLElement.dataset", "dataset")}}{{CompatGeckoMobile("6.0")}}
{{domxref("HTMLElement.focus()", "focus()")}}{{CompatGeckoMobile("5.0")}}
{{domxref("HTMLElement.oncopy")}}, {{domxref("HTMLElement.oncut")}}, and {{domxref("HTMLElement.onpaste")}} {{Non-standard_inline}}{{CompatGeckoMobile("1.9")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/htmlelement/lang/index.html b/files/pt-br/web/api/htmlelement/lang/index.html new file mode 100644 index 0000000000..6f877f1e33 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/lang/index.html @@ -0,0 +1,51 @@ +--- +title: HTMLElement.lang +slug: Web/API/HTMLElement/lang +translation_of: Web/API/HTMLElement/lang +--- +
{{ APIRef("HTML DOM") }}
+ +

The HTMLElement.lang property gets or sets the base language of an element's attribute values and text content.

+ +

The language code returned by this property is defined in RFC 1766. Common examples include "en" for English, "ja" for Japanese, "es" for Spanish and so on. The default value of this attribute is unknown. Note that this attribute, though valid at the individual element level described here, is most often specified for the root element of the document.

+ +

This also only works with the lang attribute and not with xml:lang.

+ +

Sintaxe

+ +
var languageUsed = elementNodeReference.lang; // Get the value of lang
+elementNodeReference.lang = NewLanguage; // Set new value for lang
+
+ +

languageUsed é uma variável string que obtém o idioma no qual o texto do elemento atual é gravado. NewLanguage é uma variável  string cujo valor define o idioma no qual o texto do elemento atual é gravado.

+ +

Exemplo

+ +
// this snippet compares the base language and
+// redirects to another url based on language
+if (document.documentElement.lang === "en") {
+  window.location.href = "Some_document.html.en";
+} else if (document.documentElement.lang === "ru") {
+  window.location.href = "Some_document.html.ru";
+}
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM2 HTML', 'html.html#ID-59132807', 'lang')}}{{Spec2('DOM2 HTML')}} 
+ +

 

diff --git a/files/pt-br/web/api/htmlelement/offsetheight/index.html b/files/pt-br/web/api/htmlelement/offsetheight/index.html new file mode 100644 index 0000000000..fdf05ca699 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/offsetheight/index.html @@ -0,0 +1,126 @@ +--- +title: HTMLElement.offsetHeight +slug: Web/API/HTMLElement/offsetHeight +translation_of: Web/API/HTMLElement/offsetHeight +--- +

{{ APIRef("HTML DOM") }}

+ +

A propriedade HTMLElement.offsetHeight é somente leitura e retorna um valor do tipo inteiro a altura de um elemento incluindo  padding-top+padding-bottom+border-top+border-bottom.

+ +

Typically, an element's offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar (if present, if rendered).

+ +

For the document body object, the measurement includes total linear content height instead of the element's CSS height. Floated elements extending below other linear content are ignored.

+ +
+

This property will round the value to an integer. If you need a fractional value, use {{ domxref("element.getBoundingClientRect()") }}.

+
+ +

Syntax

+ +
var intElemOffsetHeight = element.offsetHeight;
+ +

intElemOffsetHeight is a variable storing an integer corresponding to the offsetHeight pixel value of the element. The offsetHeight property is read-only.

+ +

Example

+ +

 

+ +

             Image:Dimensions-offset.png

+ + +

The example image above shows a scrollbar and an offsetHeight which fits on the window. However, non-scrollable elements may have large offsetHeight values, much larger than the visible content. These elements are typically contained within scrollable elements; consequently these non-scrollable elements may be completely or partly invisible, depending on the scrollTop setting of the scrollable container.

+ +

 

+ +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-htmlelement-offsetHeight', 'offsetLeft')}}{{Spec2('CSSOM View')}} 
+ +

Notes

+ +

offsetHeight is a property of the DHTML object model which was first introduced by MSIE. It is sometimes referred to as an element's physical/graphical dimensions, or an element's border-box height.

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}31{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

In compliance with the specification, this property will return null on Webkit if the element is hidden (the style.display of this element or any ancestor is "none") or if the style.position of the element itself is set to "fixed".

+ +

This property will return null on Internet Explorer (9) if the style.position of the element itself is set to "fixed". (Having display:none does not affect this browser.)

+ +

See Also

+ + diff --git a/files/pt-br/web/api/htmlelement/offsetleft/index.html b/files/pt-br/web/api/htmlelement/offsetleft/index.html new file mode 100644 index 0000000000..68f5f0b986 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/offsetleft/index.html @@ -0,0 +1,142 @@ +--- +title: HTMLElement.offsetLeft +slug: Web/API/HTMLElement/offsetLeft +tags: + - API + - ApenasLeitura + - Propriedade + - Referência(2) +translation_of: Web/API/HTMLElement/offsetLeft +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLElement.offsetLeft é um método apenas de leitura que retorna a medida, em pixels, da distância do canto superior esquerdo do elemento atual para o nó {{domxref("HTMLElement.offsetParent")}}.

+ +

Para elementos "block-level", que ocupam todo o espaço do elemento pai, o offsetTop, offsetLeft, offsetWidth, e offsetHeight representam a borda de um elemento relativo ao offsetParent.

+ +

Entretando, para elementos "inline-level"  (como o span) que podem envolver de uma linha para outra, o offsetTop e offsetLeft representam a posição da primeira borda (use {{domxref("Element.getClientRects()")}} para retornar a largura e altura), enquanto offsetWidth e offsetHeight representam as dimensões do bloco delimitador (use {{domxref("Element.getBoundingClientRect()")}} pra retornar sua posição). Portanto, um bloco que possua um left, top, widht ou height do offsetLeft, offsetTop, offsetWidth e offsetHeight não será um delimitador para um span com texto envolvido.

+ +

Sintaxe

+ +
left = element.offsetLeft;
+
+ +

left é um número inteiro representando o deslocamento para esquerda, em pixels,  do elemento pai mais próximo posicionado com relative.

+ +

Exemplo

+ +
var colorTable = document.getElementById("t1");
+var tOLeft = colorTable.offsetLeft;
+
+if (tOLeft > 5) {
+  // deslocamento à esquerda maior que 5: faça alguma coisa
+}
+
+ +

Esse exemplo mostra uma frase 'longa' envolvida por uma div com uma borda azul, e uma caixa vermelha que deveria delimitar o span.

+ +

Image:offsetLeft.jpg

+ +
<div style="width: 300px; border-color:blue;
+  border-style:solid; border-width:1;">
+  <span>Short span. </span>
+  <span id="long">Long span that wraps within this div.</span>
+</div>
+
+<div id="box" style="position: absolute; border-color: red;
+  border-width: 1; border-style: solid; z-index: 10">
+</div>
+
+<script>
+  var box = document.getElementById("box");
+  var long = document.getElementById("long");
+  box.style.left = long.offsetLeft + document.body.scrollLeft + "px";
+  box.style.top = long.offsetTop + document.body.scrollTop + "px";
+  box.style.width = long.offsetWidth + "px";
+  box.style.height = long.offsetHeight + "px";
+</script> 
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSSOM View', '#dom-htmlelement-offsetleft', 'offsetLeft')}}{{Spec2('CSSOM View')}} 
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome para Android
Suporte Básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

Em conformidade com a especificação, essa propriedade  retornará null no Webkit se o elemento não estiver sendo exibido (o style.display desse elemento ou ancestral estiver como "none") ou se o style.position do elemento estiver setado como "fixed".

+ +

Essa propriedade retornará null no Internet Explorer (9) se o style.position do elemento estiver setado como "fixed". (Ter display:none não afeta esse browser.)

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlelement/offsetparent/index.html b/files/pt-br/web/api/htmlelement/offsetparent/index.html new file mode 100644 index 0000000000..d08c3d3e09 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/offsetparent/index.html @@ -0,0 +1,40 @@ +--- +title: HTMLElement.offsetParent +slug: Web/API/HTMLElement/offsetParent +translation_of: Web/API/HTMLElement/offsetParent +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

A propriedade somente de leitura HTMLElement.offsetParent retorna uma referência ao objeto ao qual está contido(mais próximo na hierarquia do conteúdo) posicionado contendo o elemento. Caso o elemento não esteja posicionado, mais próximo a célula da tabela ou do elemento raiz (nos padrões do modo de conformidade do html; no modo quirks de redenrização) é o offsetParent. quando o elemento está definido style.display para "none", offsetParent retorna null. A propriedade offsetParent é útil devido a {{domxref("HTMLElement.offsetTop","offsetTop")}} e {{domxref("HTMLElement.offsetLeft","offsetLeft")}} serem relativos ao seu preenchimento da borda.

+ +
parentObj = element.offsetParent;
+
+ + + +

Especificação

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-htmlelement-offsetparent', 'offsetParent')}}{{Spec2('CSSOM View')}} 
+ +

Compatibilidade do Navegador

+ +

{{Compat("api.HTMLElement.offsetParent")}}

diff --git a/files/pt-br/web/api/htmlelement/offsettop/index.html b/files/pt-br/web/api/htmlelement/offsettop/index.html new file mode 100644 index 0000000000..f0a19ee86d --- /dev/null +++ b/files/pt-br/web/api/htmlelement/offsettop/index.html @@ -0,0 +1,62 @@ +--- +title: HTMLElement.offsetTop +slug: Web/API/HTMLElement/offsetTop +tags: + - API + - ApenasLeitura + - Propriedade +translation_of: Web/API/HTMLElement/offsetTop +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

O HTMLElement.offsetTop é um método apenas de leitura que retorna a medida, em pixels, da distância do elemento atual em relação ao topo do {{domxref("HTMLelement.offsetParent","offsetParent")}}.

+ +

Sintaxe

+ +
topPos = element.offsetTop;
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
var d = document.getElementById("div1");
+var topPos = d.offsetTop;
+
+if (topPos > 10) {
+  // deslocamento em relação ao topo maior
+  // que 10pixels do topo
+}
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSSOM View', '#dom-htmlelement-offsettop', 'offsetTop')}}{{Spec2('CSSOM View')}} 
+ +

Compatibilidade do navegador

+ +

{{Compat("api.HTMLElement.offsetTop")}}

+ +

Em conformidade com a especificação, essa propriedade retornará null no Webkit se o elemento não estiver sendo exibido (o style.display desse elemento ou ancestral estiver como "none") ou se o style.position do elemento estiver setado como "fixed".

+ +

Essa propriedade retornará null no Internet Explorer (9) se o style.position do elemento estiver setado como "fixed". (Ter display:none não afeta esse browser.)

diff --git a/files/pt-br/web/api/htmlelement/offsetwidth/index.html b/files/pt-br/web/api/htmlelement/offsetwidth/index.html new file mode 100644 index 0000000000..63d60ee4c1 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/offsetwidth/index.html @@ -0,0 +1,65 @@ +--- +title: HTMLElement.offsetWidth +slug: Web/API/HTMLElement/offsetWidth +translation_of: Web/API/HTMLElement/offsetWidth +--- +
{{ APIRef("HTML DOM") }}
+ +

A propriedade HTMLElement.offsetWidth é de somente leitura e retorna a largura de um elemento no layout.  Normalmente, o offsetWidth é uma medida que inclui as bordas do elemento, seu padding horizontal e o vertical scrollbar (se presente e renderizado) e também a largura CSS do elemento.

+ +

Sintaxe 

+ +
var offsetWidth =element.offsetWidth;
+
+ +

offsetWidth é uma propriedade somente leitura.

+ +
+

Esta propriedade irá arredondar o valor para um inteiro. se você precisa um valor fracionado, use {{ domxref("element.getBoundingClientRect()") }}.

+
+ +

 

+ +

Exemplo

+ +

 

+ +

             Image:Dimensions-offset.png

+ + +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName('CSSOM View', '#dom-htmlelement-offsetwidth', 'offsetWidth')}}{{Spec2('CSSOM View')}} 
+ +

Notas

+ +

offsetWidth é uma propriedade do modelo de objeto DHTML que foi primeiro apresentado pelo MSIE. Algumas vezes referenciado como as dimensões físicas/gráficas do elemento, ou a largura do border-box.

+ +

Compatibilidade de Browsers

+ +

{{Compat("api.HTMLElement.offsetWidth")}}

+ +

Veja também

+ + + +
 
diff --git a/files/pt-br/web/api/htmlinputelement/index.html b/files/pt-br/web/api/htmlinputelement/index.html new file mode 100644 index 0000000000..2537ee7395 --- /dev/null +++ b/files/pt-br/web/api/htmlinputelement/index.html @@ -0,0 +1,643 @@ +--- +title: HTMLInputElement +slug: Web/API/HTMLInputElement +tags: + - API + - HTML DOM + - Interface + - NeedsNewLayout + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLInputElement +--- +
{{ APIRef("HTML DOM") }}
+ +
+ +

A interface HTMLInputElement fornece propriedades e métodos especiais (além da interface regular {{domxref ("HTMLElement")}}) que também tem disponível por herança) para manipular o layout e a apresentação dos elementos de entrada.

+ +

Propriedades

+ +

Inherits propriedades dos parentes, {{domxref("HTMLElement")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
accept{{domxref("DOMString")}}Reflete o {{ htmlattrxref("accept", "input") }} atributo HTML, contendo uma lista separada por vírgula de tipos de arquivos aceitos pelo servidor quando {{htmlattrxref("type","input")}} é file.
accessKey{{domxref("DOMString")}}Um único caractere que alterna o foco de entrada para o controle.
align {{obsolete_inline}}{{domxref("DOMString")}}Alinhamento do elemento.
alt{{domxref("DOMString")}}Reflete o {{ htmlattrxref("alt", "input") }} atributo HTML, contendo texto alternativo para usar quando {{htmlattrxref("type","input")}} é image.
autocapitalize {{experimental_inline}}{{domxref("DOMString")}}Define o comportamento de capitalização para entrada do usuário. Valores válidos são none, off, characters, words, ou sentences.
autocomplete{{domxref("DOMString")}}Reflects the {{htmlattrxref("autocomplete", "input")}} HTML attribute, indicating whether the value of the control can be automatically completed by the browser. Ignored if the value of the {{htmlattrxref("type","input")}} attribute is hidden, checkbox, radio, file, or a button type (button, submit, reset, image). Possible values are: +
    +
  • off: The user must explicitly enter a value into this field for every use, or the document provides its own auto-completion method; the browser does not automatically complete the entry.
  • +
  • on: The browser can automatically complete the value based on values that the user has entered during previous uses.
  • +
+
autofocus{{jsxref("Boolean")}}Reflects the {{ htmlattrxref("autofocus", "input") }} HTML attribute, which specifies that a form control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form element in a document can have the {{htmlattrxref("autofocus","input")}} attribute. It cannot be applied if the {{htmlattrxref("type","input")}} attribute is set to hidden (that is, you cannot automatically set focus to a hidden control).
checked{{jsxref("Boolean")}}The current state of the element when {{htmlattrxref("type","input")}} is checkbox or radio.
defaultChecked{{jsxref("Boolean")}}The default state of a radio button or checkbox as originally specified in HTML that created this object.
defaultValue{{domxref("DOMString")}}The default value as originally specified in HTML that created this object.
dirName
disabled{{jsxref("Boolean")}}Reflects the {{ htmlattrxref("disabled", "input") }} HTML attribute, indicating that the control is not available for interaction. The input values will not be submitted with the form. See also {{ htmlattrxref("readOnly", "input") }} 
files {{readonlyInline}}{{domxref("FileList")}}A list of selected files.
form {{readonlyInline}}{{domxref("HTMLFormElement")}}The containing form element, if this element is in a form. If this element is not contained in a form element: +
    +
  • {{ HTMLVersionInline(5) }} this can be the {{ htmlattrxref("id", "form") }} attribute of any {{ HTMLElement("form") }} element in the same document. Even if the attribute is set on {{ HTMLElement("input") }}, this property will be null, if it isn't the id of a {{ HTMLElement("form") }} element.
  • +
  • {{ HTMLVersionInline(4) }} this must be null.
  • +
+
formAction{{domxref("DOMString")}}Reflects the {{ htmlattrxref("formaction", "input") }} HTML attribute, containing the URI of a program that processes information submitted by the element. If specified, this attribute overrides the {{ htmlattrxref("action", "form") }} attribute of the {{ HTMLElement("form") }} element that owns this element.
formEncType{{domxref("DOMString")}}Reflects the {{ htmlattrxref("formenctype", "input") }} HTML attribute, containing the type of content that is used to submit the form to the server. If specified, this attribute overrides the {{ htmlattrxref("enctype", "form") }} attribute of the {{ HTMLElement("form") }} element that owns this element.
formMethod{{domxref("DOMString")}}Reflects the {{ htmlattrxref("formmethod", "input") }} HTML attribute, containing the HTTP method that the browser uses to submit the form. If specified, this attribute overrides the {{ htmlattrxref("method", "form") }} attribute of the {{ HTMLElement("form") }} element that owns this element.
formNoValidate{{jsxref("Boolean")}}Reflects the {{ htmlattrxref("formnovalidate", "input") }} HTML attribute, indicating that the form is not to be validated when it is submitted. If specified, this attribute overrides the {{ htmlattrxref("novalidate", "form") }} attribute of the {{ HTMLElement("form") }} element that owns this element.
formTarget{{domxref("DOMString")}}Reflects the {{ htmlattrxref("formtarget", "input") }} HTML attribute, containing a name or keyword indicating where to display the response that is received after submitting the form. If specified, this attribute overrides the {{ htmlattrxref("target", "form") }} attribute of the {{ HTMLElement("form") }} element that owns this element.
height{{domxref("DOMString")}}Reflects the {{ htmlattrxref("height", "input") }} HTML attribute, which defines the height of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is image.
indeterminate{{jsxref("Boolean")}}Indicates that a checkbox is neither on nor off.
labels {{readonlyInline}}{{domxref("NodeList")}}A list of {{ HTMLElement("label") }} elements that are labels for this element.
list{{domxref("HTMLElement")}}Identifies a list of pre-defined options to suggest to the user. The value must be the id of a {{HTMLElement("datalist")}} element in the same document. The browser displays only options that are valid values for this input element. This attribute is ignored when the {{htmlattrxref("type","input")}} attribute's value is hidden, checkbox, radio, file, or a button type.
max{{domxref("DOMString")}}Reflects the {{ htmlattrxref("max", "input") }} HTML attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum (min attribute) value.
maxLength longReflects the {{ htmlattrxref("maxlength", "input") }} HTML attribute, containing the maximum length of text (in Unicode code points) that the value can be changed to. The constraint is evaluated only when the value is changed +
Note: If you set maxLength to a negative value programmatically, an exception will be thrown.
+
min{{domxref("DOMString")}}Reflects the {{ htmlattrxref("min", "input") }} HTML attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ({{htmlattrxref("max","input")}} attribute) value.
multipleReflects the {{ htmlattrxref("multiple", "input") }} HTML attribute, indicating whether more than one value is possible (e.g., multiple files).
name{{domxref("DOMString")}}Reflects the {{ htmlattrxref("name", "input") }} HTML attribute, containing a name that identifies the element when submitting the form.
pattern{{domxref("DOMString")}}Reflects the {{ htmlattrxref("pattern", "input") }} HTML attribute, containing a regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the {{htmlattrxref("title","input")}} attribute to describe the pattern to help the user. This attribute applies when the value of the {{htmlattrxref("type","input")}} attribute is text, search, tel, url or email; otherwise it is ignored.
placeholder{{domxref("DOMString")}}Reflects the {{ htmlattrxref("placeholder", "input") }} HTML attribute, containing a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the {{htmlattrxref("type","input")}} attribute is text, search, tel, url or email; otherwise it is ignored.
readOnly{{jsxref("Boolean")}} +

Reflects the {{ htmlattrxref("readonly", "input") }} HTML attribute, indicating that the user cannot modify the value of the control.
+ {{HTMLVersionInline(5)}}This is ignored if the value of the {{htmlattrxref("type","input")}} attribute is hidden, range, color, checkbox, radio, file, or a button type.

+
required{{jsxref("Boolean")}}Reflects the {{ htmlattrxref("required", "input") }} HTML attribute, indicating that the user must fill in a value before submitting a form.
selectionDirection{{domxref("DOMString")}}The direction in which selection occurred. This is "forward" if selection was performed in the start-to-end direction of the current locale, or "backward" for the opposite direction. This can also be "none" if the direction is unknown."
selectionEndunsigned longThe index of the end of selected text.
selectionStartunsigned longThe index of the beginning of selected text. When nothing is selected, this is also the caret position inside of the <input> element.
sizeunsigned longReflects the {{ htmlattrxref("size", "input") }} HTML attribute, containing size of the control. This value is in pixels unless the value of {{htmlattrxref("type","input")}} is text or password, in which case, it is an integer number of characters. {{ HTMLVersionInline(5) }} Applies only when {{htmlattrxref("type","input")}} is set to text, search, tel, url, email, or password; otherwise it is ignored.
src{{domxref("DOMString")}}Reflects the {{ htmlattrxref("src", "input") }} HTML attribute, which specifies a URI for the location of an image to display on the graphical submit button, if the value of {{htmlattrxref("type","input")}} is image; otherwise it is ignored.
step{{domxref("DOMString")}}Reflects the {{ htmlattrxref("step", "input") }} HTML attribute, which works with {{htmlattrxref("min","input")}} and {{htmlattrxref("max","input")}} to limit the increments at which a numeric or date-time value can be set. It can be the string any or a positive floating point number. If this is not set to any, the control accepts only values at multiples of the step value greater than the minimum.
tabIndexlongThe position of the element in the tabbing navigation order for the current document.
type{{domxref("DOMString")}}Reflects the {{ htmlattrxref("type", "input") }} HTML attribute, indicating the type of control to display. See {{ htmlattrxref("type", "input") }} attribute of {{ HTMLElement("input") }} for possible values.
useMap {{ obsolete_inline }}{{domxref("DOMString")}}A client-side image map.
validationMessage {{readonlyInline}}{{domxref("DOMString")}}A localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation ({{htmlattrxref("willValidate","input")}} is false), or it satisfies its constraints.
validity {{readonlyInline}}{{domxref("ValidityState")}}The validity state that this element is in. 
value{{domxref("DOMString")}} +

Current value in the control.

+ +
+

Note: for certain input types the returned value might not match the value the user has entered. For example, if the user enters a non-numeric value into an <input type="number">, the returned value might be an empty string instead.

+
+
valueAsDate{{jsxref("Date")}}The value of the element, interpreted as a date, or null if conversion is not possible.
valueAsNumberdoubleThe value of the element, interpreted as one of the following in order: +
    +
  1. a time value
  2. +
  3. a number
  4. +
  5. NaN if conversion is not possible
  6. +
+
width{{domxref("DOMString")}}Reflects the {{ htmlattrxref("width", "input") }} HTML attribute, which defines the width of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is image.
willValidate{{jsxref("Boolean")}}Indicates whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation.
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("HTMLElement")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Name & ArgumentsReturnDescription
blur()voidRemoves focus from input; keystrokes will subsequently go nowhere.
checkValidity(){{jsxref("Boolean")}}Returns false if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an {{event("invalid")}} event at the element. It returns true if the element is not a candidate for constraint validation, or if it satisfies its constraints.
click()voidSimulates a click on the element.
focus()voidFocus on input; keystrokes will subsequently go to this element.
mozSetFileArray(files){{non-standard_inline}}voidSets the files selected on the input to the given array of File objects.  This is an alternative to mozSetFileNameArray which can be used in frame scripts: a chrome script can open files as File objects and send them via message manager.
mozGetFileNameArray(length, filenames){{non-standard_inline}}voidReturns an array of all the file names from the input.
mozSetFileNameArray(filenames, length){{non-standard_inline}}voidSets the filenames for the files selected on the input.  Not for use in frame scripts, because it accesses the filesystem.
select()voidSelects the input text in the element, and focuses it so the user can subsequently replace the whole entry.
setCustomValidity(error)voidSets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.
setSelectionRange(selectionStart, selectionEnd, [optional] selectionDirection)voidSelects a range of text in the element (but does not focus it). The optional selectionDirection parameter may be "forward" or "backward" to establish the direction in which selection was set, or "none" if the direction is unknown or not relevant. The default is "none". Specifying a selectionDirection parameter sets the value of the selectionDirection property.
setRangeText(replacement, [optional] start, [optional] end, [optional] selectMode)voidReplaces a range of text with the new text. Supported input types: text, search, url, tel, password.
stepDown(n)voidDecrements the {{htmlattrxref("value","input")}} by ({{htmlattrxref("step","input")}} * n), where n defaults to 1 if not specified. Throws an INVALID_STATE_ERR exception: +
    +
  • if the method is not applicable to for the current {{htmlattrxref("type","input")}} value.
  • +
  • if the element has no {{htmlattrxref("step","input")}} value.
  • +
  • if the {{htmlattrxref("value","input")}} cannot be converted to a number.
  • +
  • if the resulting value is above the {{htmlattrxref("max","input")}} or below the {{htmlattrxref("min","input")}}. 
  • +
+
stepUp(n)voidIncrements the {{htmlattrxref("value","input")}} by ({{htmlattrxref("step","input")}} * n), where n defaults to 1 if not specified. Throws an INVALID_STATE_ERR exception: +
    +
  • if the method is not applicable to for the current {{htmlattrxref("type","input")}} value.
  • +
  • if the element has no {{htmlattrxref("step","input")}} value.
  • +
  • if the {{htmlattrxref("value","input")}} cannot be converted to a number.
  • +
  • if the resulting value is above the {{htmlattrxref("max","input")}} or below the {{htmlattrxref("min","input")}}.
  • +
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "tthe-input-element.html#the-input-element", "HTMLInputElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}
{{SpecName('HTML5 W3C', "forms.html#the-input-element", "HTMLInputElement")}}{{Spec2('HTML5 W3C')}}Technically, the  tabindex and accesskey properties, as well as the blur(), click(), and focus() methods, are now defined on {{domxref("HTMLElement")}}.
+ The following properties are now obsolete: align and useMap.
+ The following properties have been added: autocomplete, autofocus, dirName, files, formAction, formEncType, formMethod, formNoValidate, formTarget, height, indeterminate, labels, list, max, min, multiple, pattern, placeholder, required, selectionDirection, selectionEnd, selectionStart, step, validationMessage, validity, valueAsDate, valueAsNumber, width, and willValidate.
+ The following methods have been added: checkValidity(), setCustomValidity(), setSelectionRange(), stepUp(), and stepDown().
{{SpecName('DOM2 HTML', 'html.html#ID-6043025', 'HTMLInputElement')}}{{Spec2('DOM2 HTML')}}The size property is now an unsigned long. The type property must be entirely given in lowercase characters.
{{SpecName('DOM1', 'level-one-html.html#ID-6043025', 'HTMLInputElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
autocomplete & autofocus properties{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
files property{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.9)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
multiple property{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
indeterminate property{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
list property{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
formAction, formEncType, formMethod, formTarget properties{{CompatVersionUnknown}}{{CompatGeckoDesktop(2)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
formNoValidate, validationMessage, validity, willValidate properties and setCustomValidity() and checkValidity() methods.{{CompatVersionUnknown}}{{CompatGeckoDesktop(2)}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
pattern, placeholder, required properties{{CompatVersionUnknown}}{{CompatGeckoDesktop(2)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
height and weight properties{{CompatVersionUnknown}}{{CompatGeckoDesktop(16)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
labels property{{CompatChrome(14.0)}}{{CompatNo}} ({{bug("556743")}}){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
min, max, and step for <input type="number">{{CompatVersionUnknown}}Experimental, and without specific UI, since {{CompatGeckoDesktop(16)}}: behind the pref dom.experimental_forms{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
stepUp and stepDown methods{{CompatUnknown}}Experimental since {{CompatGeckoDesktop(16)}}: behind the pref dom.experimental_forms
+
+ There are still differences with the latest spec: {{bug(835773)}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
min, max, and step properties for <input type="range">{{CompatVersionUnknown}}{{CompatGeckoDesktop(23)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
min, max, and step properties for <input type="date">{{CompatVersionUnknown}}Experimental, and without specific UI, since {{CompatGeckoDesktop(20)}}: behind the pref dom.experimental_forms{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
min, max, and step properties for other date-related type values{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
mozGetFileNameArray() and mozSetFileNameArray() methods {{non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("1.9.2")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozSetFileArray() method {{non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("38")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
autocapitalize{{CompatChrome(43.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
autocapitalize{{CompatNo}}{{CompatChrome(43.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/htmlinputelement/select/index.html b/files/pt-br/web/api/htmlinputelement/select/index.html new file mode 100644 index 0000000000..c560161be4 --- /dev/null +++ b/files/pt-br/web/api/htmlinputelement/select/index.html @@ -0,0 +1,52 @@ +--- +title: HTMLInputElement.select() +slug: Web/API/HTMLInputElement/select +tags: + - API + - HTML DOM + - HTMLInputElement + - Referencia + - Selecionar + - Select + - metodo +translation_of: Web/API/HTMLInputElement/select +--- +
{{ APIRef("HTML DOM") }}
+ +

O método HTMLInputElement.select() seleciona todo o texto em um elemento {{HTMLElement("textarea")}} ou em um elemento {{HTMLElement("input")}} do tipo text.

+ +

Sintaxe

+ +
element.select()
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'forms.html#dom-textarea/input-select', 'select')}}{{Spec2('HTML WHATWG')}} 
+ +

Notas

+ +

Executar element.select() não irá necessariamente focar o input, por isso é frequentemente usado em conjunto com {{domxref("HTMLElement.focus()")}}.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlinputelement/setselectionrange/index.html b/files/pt-br/web/api/htmlinputelement/setselectionrange/index.html new file mode 100644 index 0000000000..86631688fc --- /dev/null +++ b/files/pt-br/web/api/htmlinputelement/setselectionrange/index.html @@ -0,0 +1,173 @@ +--- +title: HTMLInputElement.setSelectionRange() +slug: Web/API/HTMLInputElement/setSelectionRange +translation_of: Web/API/HTMLInputElement/setSelectionRange +--- +
{{APIRef("HTML DOM")}}
+ +

O métodoHTMLInputElement.setSelectionRange() define as posições inicial e final da seleção atual do texto em um elemento {{HTMLElement("input")}}.

+ +

Opcionalmente, em navegadores mais novos, você pode especificar a direção na qual a seleção deve ser feita; isso permite a você indicar, por exemplo, que a seleção foi feita como se o usuário tivesse clicado no fim do texto selecionado e arrastado em direção ao início.

+ +

Esse método atualiza ao mesmo tempo HTMLInputElement.selectionStart, selectionEnd, and selectionDirection.

+ +

Syntax

+ +
inputElement.setSelectionRange(selectionStart, selectionEnd, [optional] selectionDirection);
+
+ +

Parameters

+ +
+
selectionStart
+
The 0-based index of the first selected character.
+
selectionEnd
+
The 0-based index of the character after the last selected character.
+
selectionDirection {{optional_inline}}
+
A string indicating the direction in which the selection is performed. This string can be "forward" or "backward", or "none" if the direction is unknown or irrelevant.
+
+ +

Example

+ +

The following code:

+ +
<!DOCTYPE html>
+<html>
+<head>
+<meta charset=utf-8>
+<title>JS Bin</title>
+<script>
+function SelectText () {
+        var input = document.getElementById("mytextbox");
+            input.focus();
+            input.setSelectionRange(2,5);
+}
+</script>
+</head>
+<body>
+  <p><input type="text" id="mytextbox" size="20" value="Mozilla"/></p>
+  <p><button onclick="SelectText()">Select text</button></p>
+</body>
+</html>
+
+ +

will produce the following:

+ +

example.png

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "forms.html#dom-textarea/input-setselectionrange", "HTMLInputElement.setSelectionRange()")}}{{Spec2("HTML WHATWG")}}No change
{{SpecName("HTML5.1", "forms.html#dom-textarea/input-setselectionrange", "HTMLInputElement.setSelectionRange()")}}{{Spec2("HTML5.1")}}No change
{{SpecName("HTML5 W3C", "forms.html#dom-textarea/input-setselectionrange", "HTMLInputElement.setSelectionRange()")}}{{Spec2("HTML5 W3C")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}98.0{{CompatVersionUnknown}}
selectionDirection15[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("8.0")}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}[3]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome Mobile
Basic support{{CompatVersionUnknown}}Yes{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}No
selectionDirection{{CompatVersionUnknown}}{{CompatGeckoMobile("8.0")}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}} 
+
+ +

[1] The support for selectionDirection was added Blink in {{WebkitBug("60403")}}.

+ +

Note that accordingly to the WHATWG forms spec selectionStart, selectionEnd properties and setSelectionRange method apply only to inputs of types text, search, URL, tel and password. Chrome, starting from version 33, throws an exception while accessing those properties and method on the rest of input types. For example, on input of type number: "Failed to read the 'selectionStart' property from 'HTMLInputElement': The input element's type ('number') does not support selection." Related links: question on StackOverflow, whatwg bug, Chromium bug.

+ +

[2] The support for selectionDirection was added to Gecko in {{bug("674558")}}.

+ +

[3] The support for selectionDirection was added Webkit in {{WebKitBug("60403")}}.

+ +

See also

+ + diff --git a/files/pt-br/web/api/htmloptionelement/index.html b/files/pt-br/web/api/htmloptionelement/index.html new file mode 100644 index 0000000000..3ec8c7c27a --- /dev/null +++ b/files/pt-br/web/api/htmloptionelement/index.html @@ -0,0 +1,129 @@ +--- +title: HTMLOptionElement +slug: Web/API/HTMLOptionElement +tags: + - API + - HTML DOM + - Interface + - NeedsNewLayout + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLOptionElement +--- +
{{APIRef("HTML DOM")}}
+ +

The HTMLOptionElement interface represents {{HTMLElement("option")}} elements and inherits all classes and methods of the {{domxref("HTMLElement")}} interface.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
defaultSelected{{domxref("Boolean")}}Contains the initial value of the {{htmlattrxref("selected", "option")}} HTML attribute, indicating whether the option is selected by default or not.
disabled{{domxref("Boolean")}}Reflects the value of the {{htmlattrxref("disabled", "option")}} HTML attribute, which indicates that the option is unavailable to be selected. An option can also be disabled if it is a child of an {{HTMLElement("optgroup")}} element that is disabled.
form{{readonlyInline}}{{domxref("HTMLFormElement")}}If the option is a descendent of a {{HTMLElement("select")}} element, then this property has the same value as the form property of the corresponding {{DomXref("HTMLSelectElement")}} object; otherwise, it is null.
index{{readonlyInline}}longThe position of the option within the list of options it belongs to, in tree-order. If the option is not part of a list of options, like when it is part of the {{HTMLElement("datalist")}} element, the value is 0.
label{{domxref("DOMString")}}Reflects the value of the {{htmlattrxref("label", "option")}} HTML attribute, which provides a label for the option. If this attribute isn't specifically set, reading it returns the element's text content.
selected{{domxref("Boolean")}}Indicates whether the option is currently selected.
text{{domxref("DOMString")}}Contains the text content of the element.
value{{domxref("DOMString")}}Reflects the value of the {{htmlattrxref("value", "option")}} HTML attribute, if it exists; otherwise reflects value of the {{domxref("Node.textContent")}} property.
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("HTMLElement")}}.

+ +
+
Option()
+
Is a constructor creating an HTMLOptionElement object. It has four values: the text to display, text, the value associated, value, the value of defaultSelected, and the value of selected. The last three values are optional.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmloptionelement", "HTMLOptionElement")}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', "forms.html#the-option-element", "HTMLOptionElement")}}{{Spec2('HTML5 W3C')}}A constructor, Option(), has been added.
+ The form property can be the null value.
{{SpecName('DOM2 HTML', 'html.html#ID-70901257', 'HTMLOptionElement')}}{{Spec2('DOM2 HTML')}}The selected property changed its meaning: it now indicates if the option is currently selected and no longer if it was initally selected.
+ The defaultSelected property is no longer read-only.
{{SpecName('DOM1', 'level-one-html.html#ID-70901257', 'HTMLOptionElement')}}{{Spec2('DOM1')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/htmloptionelement/option/index.html b/files/pt-br/web/api/htmloptionelement/option/index.html new file mode 100644 index 0000000000..9027e9b799 --- /dev/null +++ b/files/pt-br/web/api/htmloptionelement/option/index.html @@ -0,0 +1,101 @@ +--- +title: Option() +slug: Web/API/HTMLOptionElement/Option +translation_of: Web/API/HTMLOptionElement/Option +--- +
{{APIRef("HTML DOM")}}
+ +

O construtor Option() cria novos {{domxref("HTMLOptionElement")}}.

+ +

Sintaxe

+ +
var optionElementReference = new Option(text, value, defaultSelected, selected);
+ +

Parâmetros

+ +
+
text {{optional_inline}}
+
Um {{domxref("DOMString")}} representa o conteúdo do elemento, o texto mostrado na tela. Se  o texto não é especificado, o texto padrão "" (texto vazio) é  utilizado.
+
value {{optional_inline}}
+
Um {{domxref("DOMString")}} representa o valor do {{domxref("HTMLOptionElement")}}, i.e. o valor do elemento {{htmlelement("option")}}. Se não especificado, o texto é usado como valor, e.g. o elemento {{htmlelement("select")}} tem seu valor associado quando o formulário é submetido ao servidor.
+
defaultSelected {{optional_inline}}
+
Um {{domxref("Boolean")}} é usado para adicionar o atributo selected, para que este {{htmlelement("option")}} seja mostrado como selecionado no elemento {{htmlelement("select")}} quando a página for carregada. Se não especificado, o estado padrão é não selecionado. Observe que o defaultSelected = true não define a opção como o valor selecionado do elemento {{htmlelement("select")}}.
+
selected {{optional_inline}}
+
Um {{domxref("Boolean")}} é usado para colocar elemento {{htmlelement("option")}} no estado de selecionado; como padrão do elemento tem o estado de não selecionado. Se omitido, mesmo que o parâmetro defaultSelected for verdadeiro, o elemento {{htmlelement("option")}} não é selecionado. 
+
+ +

Examplos

+ +

Adicionando novas tags options

+ +
 /* assumindo que temos este HTML
+<select id='s'>
+
+</select>
+*/
+
+var s = document.getElementById('s');
+var options = [Quatro, Cinco, Seis];
+
+options.forEach(function(elemento, chave) {
+    s.appendChild(new Option(elemento, chave));
+});
+
+ /* Resultado
+<select id='s'>
+    <option value="0">Quatro</option>
+    <option value="1">Cinco</option>
+    <option value="2">Seis</option>
+</select> */
+
+ +

Adicionando options com diferentes parâmetros

+ +
/* assumindo que temos este HTML
+<select id="s">
+    <option>Primeiro</option>
+    <option>Segundo</option>
+    <option>Terceiro</option>
+</select>
+*/
+
+var s = document.getElementById('s');
+var options = [ 'zero', 'um', 'dois' ];
+
+options.forEach(function(elemento, chave) {
+  if (elemento == 'zero') {
+    s[s.options.length] = new Option(elemento, s.options.length, false, false);
+  }
+  if (elemento == 'um') {
+    s[s.options.length] = new Option(elemento, s.options.length, true, false); // Adicionando atributo "selected"
+  }
+  if (elemento == 'dois') {
+    s[s.options.length] = new Option(elemento, s.options.length, false, true); // Apenas irá selecionar a opção na visualização
+  }
+});
+
+/* Resultado
+<select id="s">
+  <option value="0">zero</option>
+  <option value="1" selected="">um</option>
+  <option value="2">dois</option> // O usuário verá esta opção selecionada
+</select>
+*/
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
HTML5
+ The definition of 'Option' in that specification.
Recomendado
diff --git a/files/pt-br/web/api/htmlselectelement/checkvalidity/index.html b/files/pt-br/web/api/htmlselectelement/checkvalidity/index.html new file mode 100644 index 0000000000..11bfc0a7bf --- /dev/null +++ b/files/pt-br/web/api/htmlselectelement/checkvalidity/index.html @@ -0,0 +1,98 @@ +--- +title: HTMLSelectElement.checkValidity() +slug: Web/API/HTMLSelectElement/checkValidity +translation_of: Web/API/HTMLSelectElement/checkValidity +--- +
{{ APIRef("HTML DOM") }}
+ +

O HTMLSelectElement.checkValidity() método verifica se o elemento possui restrições e se as satisfaz. Se o elemento falhar suas restrições, o navegador dispara um evento {{event("invalid")}} no elemento e, em seguida, retorna false.

+ +

Sintaxe

+ +
var resultado = selectElt.checkValidity();
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-cva-checkvalidity', 'HTMLSelectElement.checkValidity()')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}.
{{SpecName('HTML5 W3C', 'forms.html#dom-cva-checkvalidity', 'HTMLSelectElement.checkValidity()')}}{{Spec2('HTML5 W3C')}}Initial definition, snapshot of {{SpecName('HTML WHATWG')}}
+ +

Browser compatibilidade

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(2.0)}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(2.0)}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlselectelement/index.html b/files/pt-br/web/api/htmlselectelement/index.html new file mode 100644 index 0000000000..94c0f2edd9 --- /dev/null +++ b/files/pt-br/web/api/htmlselectelement/index.html @@ -0,0 +1,290 @@ +--- +title: HTMLSelectElement +slug: Web/API/HTMLSelectElement +tags: + - API + - HTML DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLSelectElement +--- +
{{APIRef("HTML DOM")}}
+ +

The HTMLSelectElement interface represents a {{HTMLElement("select")}} HTML Element. These elements also share all of the properties and methods of other HTML elements via the {{domxref("HTMLElement")}} interface.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

This interface inherits the properties of {{domxref("HTMLElement")}}, and of {{domxref("Element")}} and {{domxref("Node")}}.

+ +
+
{{domxref("HTMLSelectElement.autofocus")}}
+
A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("autofocus", "select")}} HTML attribute, which indicates whether the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form-associated element in a document can have this attribute specified. {{gecko_minversion_inline("2.0")}}
+
{{domxref("HTMLSelectElement.disabled")}}
+
A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("disabled", "select")}} HTML attribute, which indicates whether the control is disabled. If it is disabled, it does not accept clicks.
+
{{domxref("HTMLSelectElement.form")}}{{ReadOnlyInline}}
+
An {{domxref("HTMLFormElement")}} referencing the form that this element is associated with. If the element is not associated with of a {{HTMLElement("form")}} element, then it returns null.
+
{{domxref("HTMLSelectElement.labels")}}{{ReadOnlyInline}}
+
A {{domxref("NodeList")}} of {{HTMLElement("label")}} elements associated with the element.
+
{{domxref("HTMLSelectElement.length")}}
+
An unsigned long The number of {{HTMLElement("option")}} elements in this select element.
+
{{domxref("HTMLSelectElement.multiple")}}
+
A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("multiple", "select")}} HTML attribute, which indicates whether multiple items can be selected.
+
{{domxref("HTMLSelectElement.name")}}
+
A {{domxref("DOMString")}} reflecting the {{htmlattrxref("name", "select")}} HTML attribute, containing the name of this control used by servers and DOM search functions.
+
{{domxref("HTMLSelectElement.options")}}{{ReadOnlyInline}}
+
An {{domxref("HTMLOptionsCollection")}} representing the set of {{HTMLElement("option")}} elements contained by this element.
+
{{domxref("HTMLSelectElement.required")}}
+
A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("required", "select")}} HTML attribute, which indicates whether the user is required to select a value before submitting the form. {{gecko_minversion_inline("2.0")}}
+
{{domxref("HTMLSelectElement.selectedIndex")}}
+
A long reflecting the index of the first selected {{HTMLElement("option")}} element. The value -1 indicates no element is selected.
+
{{domxref("HTMLSelectElement.selectedOptions")}}{{ReadOnlyInline}}
+
An {{domxref("HTMLCollection")}} representing the set of {{HTMLElement("option")}} elements that are selected.
+
{{domxref("HTMLSelectElement.size")}}
+
A long reflecting the {{htmlattrxref("size", "select")}} HTML attribute, which contains the number of visible items in the control. The default is 1, unless multiple is true, in which case it is 4.
+
{{domxref("HTMLSelectElement.type")}}{{ReadOnlyInline}}
+
A {{domxref("DOMString")}} represeting the form control's type. When multiple is true, it returns "select-multiple"; otherwise, it returns "select-one".
+
{{domxref("HTMLSelectElement.validationMessage")}}{{ReadOnlyInline}}
+
A {{domxref("DOMString")}} representing a localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints.
+
{{domxref("HTMLSelectElement.validity")}}{{ReadOnlyInline}}
+
A {{domxref("ValidityState")}} reflecting the validity state that this control is in.
+
{{domxref("HTMLSelectElement.value")}}
+
A {{domxref("DOMString")}} reflecting the value of the form control (the first selected option). Returns the value attribute of the option element or if it is missing, the text attribute.
+
{{domxref("HTMLSelectElement.willValidate")}}{{ReadOnlyInline}}
+
A {{jsxref("Boolean")}} that indicates whether the button is a candidate for constraint validation. It is false if any conditions bar it from constraint validation.
+
+ +

Methods

+ +

This interface inherits the methods of {{domxref("HTMLElement")}}, and of {{domxref("Element")}} and {{domxref("Node")}}.

+ +
+
{{domxref("HTMLSelectElement.add()")}}
+
Adds an element to the collection of option elements for this select element.
+
{{domxref("HTMLSelectElement.blur()")}}{{obsolete_inline}}
+
Removes input focus from this element. This method is now implemented on {{domxref("HTMLElement")}}.
+
{{domxref("HTMLSelectElement.checkValidity()")}}
+
Checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable {{event("invalid")}} event at the element (and returns false).
+
{{domxref("HTMLSelectElement.focus()")}}{{obsolete_inline}}
+
Gives input focus to this element. This method is now implemented on {{domxref("HTMLElement")}}.
+
{{domxref("HTMLSelectElement.item()")}}
+
Gets an item from the options collection for this {{HTMLElement("select")}} element. You can also access an item by specifying the index in array-style brackets or parentheses, without calling this method explicitly.
+
{{domxref("HTMLSelectElement.namedItem()")}}
+
Gets the item in the options collection with the specified name. The name string can match either the id or the name attribute of an option node. You can also access an item by specifying the name in array-style brackets or parentheses, without calling this method explicitly.
+
{{domxref("HTMLSelectElement.remove()")}}
+
Removes the element at the specified index from the options collection for this select element.
+
{{domxref("HTMLSelectElement.setCustomValidity()")}}
+
Sets the custom validity message for the selection element to the specified message. Use the empty string to indicate that the element does not have a custom validity error.
+
+ +

Example

+ +

Get information about the selected option

+ +
/* assuming we have the following HTML
+<select id='s'>
+    <option>First</option>
+    <option selected>Second</option>
+    <option>Third</option>
+</select>
+*/
+
+var select = document.getElementById('s');
+
+// return the index of the selected option
+console.log(select.selectedIndex); // 1
+
+// return the value of the selected option
+console.log(select.options[select.selectedIndex].value) // Second
+
+ +

A better way to track changes to the user's selection is to watch for the {{event("change")}} event to occur on the <select>. This will tell you when the value changes, and you can then update anything you need to. See the example provided in the documentation for the change event for details.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#htmlselectelement', 'HTMLSelectElement')}}{{Spec2('HTML WHATWG')}}Since the latest snapshot, {{SpecName('HTML5 W3C')}}, it adds the autocomplete property and the reportValidity() method.
{{SpecName('HTML5 W3C', 'forms.html#htmlselectelement', 'HTMLSelectElement')}}{{Spec2('HTML5 W3C')}}Is a snapshot of {{SpecName("HTML WHATWG")}}.
+ It adds the autofocus, form, required, labels, selectedOptions, willValidate, validity and validationMessage properties.
+ The tabindex property and the blur() and focus() methods have been moved to {{domxref("HTMLElement")}}.
+ The methods item(), namedItem(), checkValidity() and setCustomValidity().
{{SpecName('DOM2 HTML', 'html.html#ID-94282980', 'HTMLSelectElement')}}{{Spec2('DOM2 HTML')}}options now returns an {{domxref("HTMLOptionsCollection")}}.
+ length now returns an unsigned long.
{{SpecName('DOM1', 'level-one-html.html#ID-94282980', 'HTMLSelectElement')}}{{Spec2('DOM1')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}} [2]1.01.01.0
item() and namedItem(){{CompatVersionUnknown}}{{CompatVersionUnknown}}[3]{{CompatGeckoDesktop(2.0)}}8[3]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
setCustomValidity(), checkValidity(), willValidate, validationMessage, validity{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(2.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
selectedOptions{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(26)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
labels{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop(56)}}[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support1.01.0{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}1.01.01.01.0
item() and namedItem(){{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(2.0)}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
setCustomValidity(), checkValidity(), willValidate, validationMessage, validity{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(2.0)}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
selectedOptions{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(26)}}1.2{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
labels{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatGeckoMobile(56)}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Implemented in {{bug("556743")}}.

+ +

[2] Historically, Firefox has allowed keyboard and mouse events to bubble up from the <option> element to the parent {{HTMLElement("select")}} element. This doesn't happen in Chrome, however, although this behavior is inconsistent across many browsers. For better Web compatibility (and for technical reasons), when Firefox is in multi-process mode and the <select> element is displayed as a drop-down list. The behavior is unchanged if the <select> is presented inline and it has either the multiple attribute defined or a size attribute set to more than 1. Rather than watching <option> elements for events, you should watch for {event("change")}} events on {{HTMLElement("select")}}. See {{bug(1090602)}} for details.

+ +

[3] namedItem does not appear to take the name attribute into account (only the id attribute) on Internet Explorer and Edge. There is a bug report to Microsoft about this.

+ +

See also

+ + diff --git a/files/pt-br/web/api/htmlshadowelement/index.html b/files/pt-br/web/api/htmlshadowelement/index.html new file mode 100644 index 0000000000..fe52a8caf5 --- /dev/null +++ b/files/pt-br/web/api/htmlshadowelement/index.html @@ -0,0 +1,67 @@ +--- +title: HTMLShadowElement +slug: Web/API/HTMLShadowElement +tags: + - API + - HTML DOM + - HTMLShadowElement + - Web/Api + - shadow dom +translation_of: Web/API/HTMLShadowElement +--- +

{{obsolete_header}}

+ +

{{ APIRef("Web Components") }}

+ +

A interface HTMLShadowElement representa um  elemento HTML {{HTMLElement("shadow")}}, Ao qual é usado no Shadow DOM.

+ +

Propriedades

+ +

 Esta interface herda as propriedades do {{domxref("HTMLElement")}}.

+ +

Métodos

+ +

Esta interface herda os métodos do {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLShadowElement.getDistributedNodes()")}}
+
Retorna uma estática {{domxref("NodeList")}} do {{glossary("distributed nodes")}} associado com este elemento <shadow>.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Shadow DOM', '#the-shadow-element', 'shadow')}}{{Spec2('Shadow DOM')}} 
+ +

Browser compatível

+ + + +

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

+ +

Se Shadow DOM não é habilitado no Firefox, os elementos <shadow> se comportarão como {{domxref("HTMLUnknownElement")}}. Shadow DOM foi implementado primeiro no Firefox 28 e está por trás de uma preferência, dom.webcomponents.enabled, ao qual é desabilitado por padrão. [1]

+ +

Veja também

+ + + +
+
 
+
diff --git a/files/pt-br/web/api/htmlspanelement/index.html b/files/pt-br/web/api/htmlspanelement/index.html new file mode 100644 index 0000000000..dd06fbd0b0 --- /dev/null +++ b/files/pt-br/web/api/htmlspanelement/index.html @@ -0,0 +1,72 @@ +--- +title: HTMLSpanElement +slug: Web/API/HTMLSpanElement +tags: + - API + - HTML DOM + - Interface + - span +translation_of: Web/API/HTMLSpanElement +--- +

{{APIRef("HTML DOM")}}

+ +

A interface HTMLSpanElement representa um elemento {{HTMLElement("span")}} e deriva de uma interface {{DOMxRef("HTMLElement")}}, mas sem implementar propriedades ou métodos adicionais.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Propriedades

+ +

Essa interface não possui propriedades, mas herda propriedades de: {{DOMxRef("HTMLElement")}}.

+ +

Métodos

+ +

Essa interface não possui métodos, mas herda métodos de: {{DOMxRef("HTMLElement")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "text-level-semantics.html#htmlspanelement", "HTMLSpanElement")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5.3', "textlevel-semantics.html#htmlspanelement", "HTMLSpanElement")}}{{Spec2('HTML5.3')}}
{{SpecName('HTML5.2', "textlevel-semantics.html#htmlspanelement", "HTMLSpanElement")}}{{Spec2('HTML5.2')}}
{{SpecName('HTML5.1', "textlevel-semantics.html#htmlspanelement", "HTMLSpanElement")}}{{Spec2('HTML5.1')}}
{{SpecName('HTML5 W3C', "text-level-semantics.html#htmlspanelement", "HTMLSpanElement")}}{{Spec2('HTML5 W3C')}}A definição inicial, como {{HTMLElement("span")}} foi associada a um {{DOMxRef("HTMLElement")}}} antes disso.
+ +

Compatibilidade do navegador

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/idbcursor/index.html b/files/pt-br/web/api/idbcursor/index.html new file mode 100644 index 0000000000..ce9c02414b --- /dev/null +++ b/files/pt-br/web/api/idbcursor/index.html @@ -0,0 +1,181 @@ +--- +title: IDBCursor +slug: Web/API/IDBCursor +translation_of: Web/API/IDBCursor +--- +

{{APIRef("IndexedDB")}}

+ +

O IDBCursor é uma interface da API IndexedDB que representa o cursor para atravessar ou interagir sobre vários registros em um banco de dados.

+ +

O cursor tem uma fonte que indica qual índice ou armazenamento o objeto está sobre a iteração. Ele tem uma posição dentro do intervalo, e move-se numa direcção que é aumentar ou diminuir na ordem de chaves ficha. O cursor permite que um aplicativo para processar de forma assíncrona todos os registros na faixa do cursor.

+ +

Pode ter um número ilimitado de cursores ao mesmo tempo. Você sempre consegue o mesmo objeto IDBCursor representando um determinado cursor. As operações são realizadas na loja de índice ou objeto subjacente.

+ +

{{AvailableInWorkers}}

+ +

Methods

+ +
+
{{domxref("IDBCursor.advance()")}}
+
Define o número de vezes um cursor deve mover a sua posição para a frente.
+
{{domxref("IDBCursor.continue()")}}
+
Avança o cursor para a próxima posição ao longo de sua direção, para o item cuja chave corresponde ao parâmetro chave opcional.
+
{{domxref("IDBCursor.delete()")}}
+
Retorna um {{domxref("IDBRequest")}} objeto, e, em um segmento separado, exclui o registro na posição do cursor, sem alterar a posição do cursor. Isso pode ser usado para excluir registros específicos.
+
{{domxref("IDBCursor.update()")}}
+
Retorna um {{domxref("IDBRequest")}} objeto, e, em um segmento separado, atualiza o valor na posição atual do cursor em armazenar o objeto. Isso pode ser usado para atualizar registros específicos.
+
+ +

Propriedades

+ +
+
{{domxref("IDBCursor.source")}} {{readonlyInline}}
+
Retorna um {{domxref("IDBObjectStore")}} ou {{domxref("IDBIndex")}} que o cursor é a iteração. Esta função nunca retorna nulo ou gera uma exceção, mesmo se o cursor está actualmente a ser iterativo, tem iterated além de seu fim, ou a sua operação não está ativa.
+
{{domxref("IDBCursor.direction")}} {{readonlyInline}}
+
Retorna a direcção do percurso do cursor. Veja constantes para os possíveis valores.
+
{{domxref("IDBCursor.key")}} {{readonlyInline}}
+
Returns the key for the record at the cursor's position. If the cursor is outside its range, this is set to undefined. The cursor's key can be any data type.
+
{{domxref("IDBCursor.primaryKey")}} {{readonlyInline}}
+
Retorna a chave para o registro na posição do cursor. Se o cursor estiver fora do seu alcance, isso é definido como indefinido. A chave do cursor pode ser qualquer tipo de dados.
+
+ +

Constantes

+ +
{{ obsolete_header(25) }}
+ +
+

These constants are no longer available. You should use the string constants directly instead. ({{ bug(891944) }})

+
+ + + +

Example

+ +

In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. For a complete working example, see our IDBCursor example (view example live.)

+ +
function displayData() {
+  var transaction = db.transaction(['rushAlbumList'], "readonly");
+  var objectStore = transaction.objectStore('rushAlbumList');
+
+  objectStore.openCursor().onsuccess = function(event) {
+    var cursor = event.target.result;
+    if(cursor) {
+      var listItem = document.createElement('li');
+      listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year;
+      list.appendChild(listItem);
+
+      cursor.continue();
+    } else {
+      console.log('Entries all displayed.');
+    }
+  };
+};
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBCursor', 'cursor')}}{{Spec2('IndexedDB')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{property_prefix("webkit")}}
+ 24
10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial157.1
Available in workers{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.4{{CompatGeckoMobile("22.0")}}1.0.110228
Available in workers{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+

Be careful in Chrome as it still implements the old specification along with the new one. Similarly it still has the prefixed webkitIndexedDB property even if the unprefixed indexedDB is present.

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/idbfactory/index.html b/files/pt-br/web/api/idbfactory/index.html new file mode 100644 index 0000000000..e422763fd2 --- /dev/null +++ b/files/pt-br/web/api/idbfactory/index.html @@ -0,0 +1,210 @@ +--- +title: IDBFactory +slug: Web/API/IDBFactory +translation_of: Web/API/IDBFactory +--- +

{{APIRef("IndexedDB")}}

+ +
+

A interface IDBFactory, pertencente a IndexedDB API , permite que aplicativos acessem de forma assíncrona os bancos de dados indexados. O objeto que implementa a interface é o window.indexedDB, com este objeto é possível criar, acessar, modificar e excluir informações de um banco de dados. 

+ +

{{AvailableInWorkers}}

+
+ +

Métodos

+ +
+
{{domxref("IDBFactory.open")}}
+
Realizar a abertura de uma conexão com uma base de dados.
+
{{domxref("IDBFactory.deleteDatabase")}}
+
Remove uma base de dados.
+
{{domxref("IDBFactory.cmp")}}
+
Compara dois valores chaves e determina se elas são iguais e se não, quem é a maior.
+
+ +

Métodos Obsoletos

+ +
+
IDBFactory.open, a versão original {{ obsolete_inline }}
+
Este método realizava conexão com uma base de dados, ele ainda é usado em alguns navegadores.
+
+ +

Exemplo

+ +

No código abaixo, realizamos uma conexão com um banco de dados e incluímos manipuladores para os casos de sucesso e erro. Você pode obter o To-do Notifications app como exemplo (Visualizar exemplo.)

+ +
var note = document.querySelector("ul");
+
+// In the following line, you should include the prefixes of implementations you want to test.
+window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
+// DON'T use "var indexedDB = ..." if you're not in a function.
+// Moreover, you may need references to some window.IDB* objects:
+window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
+window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
+// (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
+
+// Let us open version 4 of our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+// these two event handlers act on the database being opened successfully, or not
+DBOpenRequest.onerror = function(event) {
+  note.innerHTML += '<li>Error loading database.</li>';
+};
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // store the result of opening the database in the db variable. This is used a lot later on, for opening transactions and suchlike.
+  db = DBOpenRequest.result;
+};
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBFactory', 'IDBFactory')}}{{Spec2('IndexedDB')}} 
{{SpecName("IndexedDB 2", "#factory-interface", "IDBFactory")}}{{Spec2("IndexedDB 2")}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(23)}} {{property_prefix("webkit")}}
+ {{CompatChrome(24)}} (unprefixed)
+ {{CompatChrome(38)}} (prefixes deprecated)
+ {{CompatChrome(57)}} (prefixes removed)
{{CompatVersionUnknown}}10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial15
+ {{CompatOpera(44)}} (prefixes removed)
7.1
Available in workers{{CompatVersionUnknown}} (unprefixed)
+ {{CompatChrome(38)}} (prefixes deprecated)
+ {{CompatChrome(57)}} (prefixes removed)
{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}
+ {{CompatOpera(44)}} (prefixes removed)
{{CompatUnknown}}
Indexed Database 2.0{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(45)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}
+ {{CompatChrome(38)}} (prefixes deprecated)
+ {{CompatChrome(57)}} (prefixes removed)
{{CompatVersionUnknown}}
+ {{CompatChrome(38)}} (prefixes deprecated)
+ {{CompatChrome(57)}} (prefixes removed)
{{CompatVersionUnknown}}{{CompatGeckoMobile("22.0")}}1.0.11022
+ {{CompatOperaMobile(44)}} (prefixes removed)
8
Available in workers{{CompatVersionUnknown}} (unprefixed)
+ {{CompatChrome(38)}} (prefixes deprecated)
+ {{CompatChrome(57)}} (prefixes removed)
{{CompatVersionUnknown}} (unprefixed)
+ {{CompatChrome(38)}} (prefixes deprecated)
+ {{CompatChrome(57)}} (prefixes removed)
{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+ {{CompatOperaMobile(44)}} (prefixes removed)
{{CompatUnknown}}
Indexed Database 2.0{{CompatChrome(58)}}{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(45)}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/imagecapture/index.html b/files/pt-br/web/api/imagecapture/index.html new file mode 100644 index 0000000000..242ec1ac22 --- /dev/null +++ b/files/pt-br/web/api/imagecapture/index.html @@ -0,0 +1,116 @@ +--- +title: ImageCapture +slug: Web/API/ImageCapture +translation_of: Web/API/ImageCapture +--- +
{{APIRef("MediaStream Image")}}
+ +

A interface ImageCapture da MediaStream Image Capture API fornece métodos para permitir a captura de images ou fotos de uma câmera ou de um dispositivo fotográfico. É fornecido uma interface para capturar images de um dispositive fotográfico referenciado por meio de um {{domxref("MediaStreamTrack")}} válido.

+ +

Construtor

+ +
+
{{domxref("ImageCapture.ImageCapture()", "ImageCapture()")}}
+
Cria um novo objeto ImageCapture que pode ser usado para capturar quadros estáticos (fotos) de um determinado {{domxref ("MediaStreamTrack")}} que representa um fluxo de vídeo.
+
+ +

Propriedades

+ +
+
{{domxref("ImageCapture.track")}} {{readonlyinline}}
+
Retorna uma referência ao {{domxref ("MediaStreamTrack")}} passado ao construtor.
+
+ +

Métodos

+ +

A interface do ImageCapture é baseada em {{domxref ("EventTarget")}}}, portanto inclui os métodos definidos por essa interface e os listados abaixo.

+ +
+
{{domxref("ImageCapture.takePhoto()")}}
+
Faz uma única exposição usando o dispositivo de captura de vídeo que busca um {{domxref ("MediaStreamTrack")}} e retorna um {{jsxref ("Promise")}} que resolve com um {{domxref ("Blob")}} que contém o dados.
+
{{domxref("ImageCapture.getPhotoCapabilities()")}}
+
Retorna um {{jsxref ("Promise")}} que resolve com um objeto {{domxref ("PhotoCapabilities")}} que contém os intervalos de opções de configuração disponíveis.
+
{{domxref("ImageCapture.getPhotoSettings()")}}
+
Retorna um {{jsxref ("Promise")}} que é resolvido com um objeto {{domxref ("PhotoSettings")}} que contém as definições de configuração de foto atuais.
+
{{domxref("ImageCapture.grabFrame()")}}
+
Tira uma captura instantânea do vídeo ao vivo em um {{domxref ("MediaStreamTrack")}}, retornando um {{domxref ("ImageBitmap")}}, se for bem-sucedido.
+
+ +

Exemplo

+ +

O código a seguir foi retirado do Chrome's Grab Frame - Take Photo Sample. Como o ImageCapture requer algum lugar para capturar uma imagem, o exemplo abaixo começa com o dispositivo de mídia de um dispositivo (em outras palavras, uma câmera).

+ +

Este exemplo mostra, aproximadamente, um {{domxref ("MediaStreamTrack")}} extraído do {{domxref ("MediaStream")}} de um dispositivo. A faixa é usada para criar um objeto ImageCapture, para que seja possível chamar takePhoto() e grabFrame(). Por fim, mostra como aplicar os resultados dessas chamadas a um objeto de tela.

+ +
var imageCapture;
+
+function onGetUserMediaButtonClick() {
+  navigator.mediaDevices.getUserMedia({video: true})
+  .then(mediaStream => {
+    document.querySelector('video').srcObject = mediaStream;
+
+    const track = mediaStream.getVideoTracks()[0];
+    imageCapture = new ImageCapture(track);
+  })
+  .catch(error => console.log(error));
+}
+
+function onGrabFrameButtonClick() {
+  imageCapture.grabFrame()
+  .then(imageBitmap => {
+    const canvas = document.querySelector('#grabFrameCanvas');
+    drawCanvas(canvas, imageBitmap);
+  })
+  .catch(error => console.log(error));
+}
+
+function onTakePhotoButtonClick() {
+  imageCapture.takePhoto()
+  .then(blob => createImageBitmap(blob))
+  .then(imageBitmap => {
+    const canvas = document.querySelector('#takePhotoCanvas');
+    drawCanvas(canvas, imageBitmap);
+  })
+  .catch(error => console.log(error));
+}
+
+/* Utils */
+
+function drawCanvas(canvas, img) {
+  canvas.width = getComputedStyle(canvas).width.split('px')[0];
+  canvas.height = getComputedStyle(canvas).height.split('px')[0];
+  let ratio  = Math.min(canvas.width / img.width, canvas.height / img.height);
+  let x = (canvas.width - img.width * ratio) / 2;
+  let y = (canvas.height - img.height * ratio) / 2;
+  canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
+  canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height,
+      x, y, img.width * ratio, img.height * ratio);
+}
+
+document.querySelector('video').addEventListener('play', function() {
+  document.querySelector('#grabFrameButton').disabled = false;
+  document.querySelector('#takePhotoButton').disabled = false;
+});
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('MediaStream Image','#imagecaptureapi','ImageCapture')}}{{Spec2('MediaStream Image')}}Initial definition.
+ +

Compatibilidade do navegador

+ + + +

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

diff --git a/files/pt-br/web/api/index.html b/files/pt-br/web/api/index.html new file mode 100644 index 0000000000..4537f1f179 --- /dev/null +++ b/files/pt-br/web/api/index.html @@ -0,0 +1,32 @@ +--- +title: APIs da Web +slug: Web/API +tags: + - API + - DOM + - JavaScript + - Referencia + - Web +translation_of: Web/API +--- +

Ao escrever código para a Web, há muitas APIs da Web disponíveis. Abaixo está uma lista de todas as APIs e interfaces (tipos de objeto) que você pode usar ao desenvolver seu aplicativo ou site da Web.

+ +

As APIs da Web são normalmente usadas com JavaScript, embora isso nem sempre tenha que ser o caso.

+ +

Especificações

+ +

Esta é uma lista de todas as APIs disponíveis.

+ +

{{ListGroups}}

+ +

Interfaces

+ +

Esta é uma lista de todas as interfaces (isto é, tipos de objetos) disponíveis.

+ +
{{APIListAlpha}}
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/pt-br/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..c83b48750e --- /dev/null +++ b/files/pt-br/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,249 @@ +--- +title: Conceitos Básicos sobre IndexedDb +slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +tags: + - Avançado + - IndexedDB + - conceitos +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +
+

IndexedDB é uma forma de você armazenar dados no browser do usuário. Permite criar aplicativos da Web com habilidades de consulta ricas, independentemente da disponibilidade da rede, esses aplicativos podem trabalhar on-line e off-line. IndexedDB é útil para aplicativos que armazenam uma grande quantidade de dados (por exemplo, um catálogo de DVDs em uma biblioteca de empréstimos) e aplicativos que não precisam de conectividade persistente à Internet para trabalhar (por exemplo, clientes de e-mail, listas de tarefas e Blocos de notas).

+
+ +

Sobre esse documento

+ +

Essa introdução discute conceitos essenciais e a terminologia do IndexedDB. Ele vai ter dar um visão geral e explicar conceitos chaves.

+ +

Você vai achar útil:

+ + + +

Visão geral do IndexedDB

+ +

IndexedDB permite você armazenar e consultar objetos que são indexados com uma chave. Todas as mudanças na base dados são feitas por transações. Como a maioria soluções de armazenamento web, IndexedDB segue a política de mesma origem. Então enquanto você pode acessar dados armazenados em um domínio, você não pode acessar em diferentes domínios.

+ +

IndexedDB é uma API assíncrona que pode ser usada em diversos contextos, incluindo WebWorkers. Isso permite o uso de uma versão síncrona também, para o uso em web workers, mas isso foi removido da especificação por falta de interesse da comunidade web.

+ +


+ IndexedDB foi pensado para ser uma especificação concorrente ao banco de dados WebSQL, mas o W3C depreciou o WebSQL em 18 de novembro de 2010. Embora IndexedDB e WebSQL sejam soluções para armazenamento, eles não oferecem as mesmas funcionalidades. WebSQL Database é um sistema de acesso a banco de dados relacional, enquanto que IndexedDB é um sistema de tabelas indexadas.

+ +

Principais conceitos

+ +

 Se você já trabalhou com outros tipos de banco de dados, você pode esquecer enquanto trabalha com IndexedDB. E tenha esses importantes conceitos em mente:

+ + + +

 

+ + + +

Definições

+ +

Essa seção define e explica os termos usado na API IndexedDB.

+ +

Base de dados

+ +
+
Base de dados
+
Um repositório de informação, normalmente é composto por um ou mais object stores. cada base de dados deve possuir: +
    +
  • Name. This identifies the database within a specific origin and stays constant throughout its lifetime. The name can be any string value (including an empty string).
  • +
  • +

    Current version. When a database is first created, its version is the integer 1 if not specified otherwise. Each database can have only one version at any given time.

    +
  • +
+
+
durable
+
+

In Firefox, IndexedDB used to be durable, meaning that in a readwrite transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk.

+ +

As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}), which is the same behaviour as other IndexedDB-supporting browsers. In this case the {{Event("complete")}} event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further.

+ +
+

Note: In Firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see {{domxref("IDBDatabase.transaction")}}.) This is currently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config.

+
+
+
object store
+
+

The mechanism by which data is stored in the database. The object store persistently holds records, which are key-value pairs. Records within an object store are sorted according to the keys in an ascending order.

+ +

Every object store must have a name that is unique within its database. The object store can optionally have a key generator and a key path. If the object store has a key path, it is using in-line keys; otherwise, it is using out-of-line keys.

+ +

For the reference documentation on object store, see IDBObjectStore or IDBObjectStoreSync.

+
+
version
+
When a database is first created, its version is the integer 1. Each database has one version at a time; a database can't exist in multiple versions at once. The only way to change the version is by opening it with a greater version than the current one. This will start a versionchange transaction and fire an upgradeneeded event. The only place where the schema of the database can be updated is inside the handler of that event.
+
Note: This definition describes the most recent specification, which is only implemented in up-to-date browsers. Old browsers implemented the now deprecated and removed IDBDatabase.setVersion() method.
+
database connection
+
An operation created by opening a database. A given database can have multiple connections at the same time.
+
transaction
+
+

An atomic set of data-access and data-modification operations on a particular database. It is how you interact with the data in a database. In fact, any reading or changing of data in the database must happen in a transaction.

+ +

A database connection can have several active transaction associated with it at a time, so long as the writing transactions do not have overlapping scopes. The scope of transactions, which is defined at creation, determines which object stores the transaction can interact with and remains constant for the lifetime of the transaction. So, for example, if a database connection already has a writing transaction with a scope that just covers the flyingMonkey object store, you can start a second transaction with a scope of the unicornCentaur and unicornPegasus object stores. As for reading transactions, you can have several of them — even overlapping ones.

+ +

Transactions are expected to be short-lived, so the browser can terminate a transaction that takes too long, in order to free up storage resources that the long-running transaction has locked. You can abort the transaction, which rolls back the changes made to the database in the transaction. And you don't even have to wait for the transaction to start or be active to abort it.

+ +

The three modes of transactions are: readwrite, readonly, and versionchange. The only way to create and delete object stores and indexes is by using a versionchange transaction. To learn more about transaction types, see the reference article for IndexedDB.

+ +

Because everything happens within a transaction, it is a very important concept in IndexedDB. To learn more about transactions, especially on how they relate to versioning, see IDBTransaction, which also has reference documentation. For the documentation on the synchronous API, see IDBTransactionSync.

+
+
request
+
The operation by which reading and writing on a database is done. Every request represents one read or write operation.
+
index
+
+

An index is a specialized object store for looking up records in another object store, called the referenced object store. The index is a persistent key-value storage where the value part of its records is the key part of a record in the referenced object store. The records in an index are automatically populated whenever records in the referenced object store are inserted, updated, or deleted. Each record in an index can point to only one record in its referenced object store, but several indexes can reference the same object store. When the object store changes, all indexes that refer to the object store are automatically updated.

+ +

Alternatively, you can also look up records in an object store using the key.

+ +

To learn more on using indexes, see Using IndexedDB. For the reference documentation on index, see IDBKeyRange.

+
+
+ +

Chave e valor

+ +
+
key
+
+

A data value by which stored values are organized and retrieved in the object store. The object store can derive the key from one of three sources: a key generator, a key path, or an explicitly specified value. The key must be of a data type that has a number that is greater than the one before it. Each record in an object store must have a key that is unique within the same store, so you cannot have multiple records with the same key in a given object store.

+ +

A key can be one of the following types: string, date, float, a binary blob, and array. For arrays, the key can range from an empty value to infinity. And you can include an array within an array.

+ +

Alternatively, you can also look up records in an object store using the index.

+
+
key generator
+
A mechanism for producing new keys in an ordered sequence. If an object store does not have a key generator, then the application must provide keys for records being stored. Generators are not shared between stores. This is more a browser implementation detail, because in web development, you don't really create or access key generators.
+
in-line key
+
A key that is stored as part of the stored value. It is found using a key path. An in-line key can be generated using a generator. After the key has been generated, it can then be stored in the value using the key path or it can also be used as a key.
+
out-of-line key
+
A key that is stored separately from the value being stored.
+
key path
+
Defines where the browser should extract the key from in the object store or index. A valid key path can include one of the following: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods or an array containing any of those. It cannot include spaces.
+
value
+
+

Each record has a value, which could include anything that can be expressed in JavaScript, including boolean, number, string, date, object, array, regexp, undefined, and null.

+ +

When an object or array is stored, the properties and values in that object or array can also be anything that is a valid value.

+ +

Blobs and files can be stored, cf. specification {{ fx_minversion_inline("11") }}.

+
+
+ +

Intervalo e escopo

+ +
+
scope
+
The set of object stores and indexes to which a transaction applies. The scopes of read-only transactions can overlap and execute at the same time. On the other hand, the scopes of writing transactions cannot overlap. You can still start several transactions with the same scope at the same time, but they just queue up and execute one after another.
+
cursor
+
A mechanism for iterating over multiple records with a key range. The cursor has a source that indicates which index or object store it is iterating. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. For the reference documentation on cursors, see IDBCursor or IDBCursorSync.
+
key range
+
+

A continuous interval over some data type used for keys. Records can be retrieved from object stores and indexes using keys or a range of keys. You can limit or filter the range using lower and upper bounds. For example, you can iterate over all values of a key between x and y.

+ +

For the reference documentation on key range, see IDBKeyRange.

+
+
+ +

Limitações

+ +

IndexedDB is designed to cover most cases that need client-side storage. However, it is not designed for a few cases like the following:

+ + + +

In addition, be aware that browsers can wipe out the database, such as in the following conditions:

+ + + +

The exact circumstances and browser capabilities change over time, but the general philosophy of the browser vendors is to make the best effort to keep the data when possible.

+ +

Próximos passos

+ +

With these big concepts under our belts, we can get to more concrete stuff. For a tutorial on how to use the API, see Using IndexedDB.

+ +

See also

+ +

Especificação

+ + + +

Referência

+ + + +

Tutoriais

+ + + +

Artigo relacionado

+ + diff --git a/files/pt-br/web/api/indexeddb_api/index.html b/files/pt-br/web/api/indexeddb_api/index.html new file mode 100644 index 0000000000..06e84254f2 --- /dev/null +++ b/files/pt-br/web/api/indexeddb_api/index.html @@ -0,0 +1,167 @@ +--- +title: IndexedDB +slug: Web/API/IndexedDB_API +translation_of: Web/API/IndexedDB_API +--- +
+

IndexedDB é uma API para armazenamento client-side de quantidades significantes de informações e buscas com alta performance por índices. Enquanto DOM Storage é útil para armazenamento de pequenas quantidade de dados, IndexedDB é a solução para grande porção de dados estruturados.

+
+ +

Esta página basicamente é o ponto de entrada para uma descrição técnica dos objetos da API. Precisando de suporte ainda mais inicial consulte os Conceitos Básicos sobre IndexedDb. Para mais detalhes sobre a implementação, veja Usando IndexedDB.
+
+ IndexedDB provém APIs separadas para acesso tanto síncrono quanto assíncrono. As APIs síncronas devem ser utilizadas apenas dentro de Web Workers, apesar de não ser implementada por nenhum navegador atualmente. A API assíncrona funciona tanto com ou sem Web Workers, sendo que o Firefox ainda não implementou este.

+ +

API Assíncrona

+ +

Os métodos da API assíncrona são chamados sem bloquear a thread que os chama. Para obter acesso assíncrono à database, chame open() no atributo indexedDB do objeto window, que retornará um objeto {{domxref("IDBRequest")}}. Operações assíncronas comunicam-se com a aplicação que os chamam executando eventos nos objetos {{domxref("IDBRequest")}}.

+ +
+

Nota: O objeto indexedDB é prefixado em navegadores mais antigos (propriedade mozIndexedDB em Gecko < 16, webkitIndexedDb em Chrome e msIndexedDB no IE 10).

+
+ +

As interfaces da API assíncrona do IndexedDB são:

+ +
+
{{domxref("IDBFactory")}}
+
Provém acesso ao banco de dados. É a interface implementado pelo objeto global indexedDB e é, portanto, o ponto de entrada para API.
+
{{domxref("IDBCursor")}}
+
Itera sobre objectStores e índices
+
{{domxref("IDBCursorWithValue")}}
+
Itera sobre objectStores e índices e retorna o atual valor do cursor
+
{{domxref("IDBDatabase")}}
+
Represents a connection to a database. It's the only way to get a transaction on the database.
+
{{domxref("IDBEnvironment")}}
+
Provides access to a client-side database. It is implemented by the {{ domxref("window") }} and {{ domxref("worker") }} objects.
+
{{domxref("IDBIndex")}}
+
Provides access to the metadata of an index.
+
{{domxref("IDBKeyRange")}}
+
Define um alcance das chaves.
+
{{domxref("IDBObjectStore")}}
+
Representa um ObjectStore
+
{{domxref("IDBOpenDBRequest")}}
+
Representa uma requisição para abrir o banco de dados.
+
{{domxref("IDBRequest")}}
+
Provém acesso a resultados de requisições assíncronas ao banco de dados e a objetos do banco de dados. É o que você obtém quando chama um método assíncrono.
+
{{domxref("IDBTransaction")}}
+
Representa uma transação. Você cria a transação no banco de dados, especifíca o escopo (tal como qual objectStore você deseja acessar), e determina que tipo de acesso (apenas leitura ou também escrita) daquilo que você deseja.
+
+ + + +

Uma versão anterior da especificação também define estas interfaces agora removidas. Elas ainda estão documentadas caso você precise atualizar códigos escritos anteriormente:

+ +
+
{{domxref("IDBVersionChangeRequest")}}
+
Representa uma requisição para alterar a versão do banco de dados. O modo de alterar a versão do banco de dados mudou então (chamando IDBFactory.open sem também chamar IDBDatabase.setVersion) e a interface IDBOpenDBRequest agora tem a funcionalidade do removido IDBVersionChangeRequest.
+
{{domxref("IDBDatabaseException")}}  {{ obsolete_inline() }}
+
Representa condições de erro que podem ser encontradas enquanto performando operações no banco de dados.
+
+ + + +
+

 Nota: há também a versão síncrona da API. A versão síncrona não tem implementação em qualquer navegador. É feita para ser utilizada com WebWorkers.

+
+ +

Limites de Armazenamento

+ +

Não há qualquer limite em um único elemento da database. Entretanto podem haver limites quanto ao tamanho de cada banco de dados. Este limite (e a maneira com qual o usuário chega a ele) pode variar de um navegador para outro:

+ + + +

Exemplos

+ + + +

Compatibilidade dos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
API Assíncrona +

11.0 {{ property_prefix("webkit") }}
+ 24

+
{{ CompatGeckoDesktop("2.0") }} {{ property_prefix("moz") }}
+ {{ CompatGeckoDesktop("16.0") }}
101711.1
API Síncrona (com WebWorkers){{ CompatNo() }}{{ CompatNo() }}
+ See {{ bug(701634) }}
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
API Assíncrona4.4{{ CompatGeckoDesktop("6.0") }} {{ property_prefix("moz") }}
+ {{ CompatGeckoDesktop("16.0") }}
101710.3
+
+ +
+

Nota: alguns browsers ainda não suportam IndexedDB mas suportam WebSQL, mais especificamente Safari/Webkit no desktop e iOS. Uma maneira de driblar este problema é utilizar IndexedDB Polyfill ou Shim, que recorre ao WebSQL para navegadores que não suportam.

+
+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/indexeddb_api/usando_indexeddb/index.html b/files/pt-br/web/api/indexeddb_api/usando_indexeddb/index.html new file mode 100644 index 0000000000..da14879b31 --- /dev/null +++ b/files/pt-br/web/api/indexeddb_api/usando_indexeddb/index.html @@ -0,0 +1,1281 @@ +--- +title: Usando IndexedDB +slug: Web/API/IndexedDB_API/Usando_IndexedDB +tags: + - API IndexedDB Tutorial Avançado +translation_of: Web/API/IndexedDB_API/Using_IndexedDB +--- +
+

IndexedDB é uma forma de armazenar dados no navegador do usuário. Com ele você pode criar aplicações web com possibilidade de fazer query sem necessidade de conexão, suas aplicações podem funcionar tanto online quanto offline. 

+
+ +

Sobre esse documento

+ +

Esse tutorial utiliza a API assíncrona do IndexedDB. Se você não está familiarizado com IndexedDB, você pode ler Conceitos básicos sobre IndexedDB.

+ +

Para a documentação de referência, veja o artigo sobre API IndexedDB, pois nele contém os tipos de objetos utilizados no IndexedDB,  como também métodos da API, tanto síncrona como assíncrona. 

+ +

Padrão básico

+ +

O IndexedDB encoraja o uso do seguinte padrão:

+ +
    +
  1. Abrir um banco de dados.
  2. +
  3. Criar um ObjectStore ao atualizar o banco. 
  4. +
  5. Iniciar uma transação e e faz um request para fazer alguma operação no banco, como adicionar ou obter dados.
  6. +
  7. +
    Esperar a operação ser completada ouvindo algum evento DOM.
    +
  8. +
  9. +
    Fazer algo com o resultado da query (que pode ser obtida pelo objeto request).
    +
  10. +
+ +

OK, então, agora com esses conceitos em mente, nós podemos fazer coisas mais concretas.

+ +

Criando e estruturando o banco

+ +

Pelo fato  da especificação ainda estar evoluindo, as implementações do IndexedDB tem prefixos de navegadores. Os navegadores podem ter implementações diferentes da API IndexedDB até a especificação ser consolidada. Mas uma vez que tudo chegar a um consenso, os navegadores tirarão seus prefixos. Atualmente, algumas implementações removeram o prefixo: Internet Explorer 10, Firefox 16, Chrome 24. Quando eles usam prefixo, navegadores baseados no Gecko usam o prefixo moz, enquanto os navegadores baseados no WebKit usam o prefixo webkit.

+ +

Usando uma versão experimental do IndexedDB

+ +

Se você quiser testar seu código em navegadores que usam prefixo, você pode usar o código abaixo:  

+ +
// Na linha abaixo, você deve incluir os prefixos do navegador que você vai testar.
+window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
+// Não use "var indexedDB = ..." se você não está numa function.
+// Posteriormente, você pode precisar de referências de algum objeto window.IDB*:
+window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
+window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
+// (Mozilla nunca usou prefixo nesses objetos, então não precisamos window.mozIDB*)
+ +

Tome cuidado, implementações prefixadas podem estar com bugs ou implementando especificações antigas. Portanto, não é recomendado usar em produção. É preferível não usar IndexedDB em navegadores antigos:

+ +
if (!window.indexedDB) {
+    window.alert("Seu navegador não suporta uma versão estável do IndexedDB. Alguns recursos não estarão disponíveis.");
+}
+
+ +

Abrindo um banco

+ +

Começamos todo o processo assim:

+ +
// Abrindo o banco de dados
+var request = window.indexedDB.open("DBteste", 3);
+
+ +

Abrir um banco é como qualquer outra operação — Você tem que "requerer (request)".

+ +

A requisição de abertura não abre o banco ou inicia a transação. A chamada da função open() retorna um objeto IDBOpenDBRequest com o resultado (success) ou um erro que você terá que tratar. Muitas outras funções assíncronas no IndexedDB fazem a mesma coisa - retornam um objeto IDBRequest com o resultado ou erro. O resultado para a função open é uma instância de IDBDatabase.

+ +

O segundo parâmetro para o método open é a versão do banco. A versão do banco determina seu schema — os registros no banco e sua estrutura. Se o banco não existe ainda, ele é criado pela operação open, então o evento onupgradeneeded é chamado e você cria o schema do banco nesse evento. Se o banco existe mas você está fornecendo um novo número de versão, o evento onupgradeneeded é chamado imediatamente, permitindo você tratar a atualização do schema. Para mais informações sobre isso veja Updating the version of the database.

+ +
+

O número de versão é um unsigned long long, o que significa que ele pode ver um inteiro muito grande. Isso também significa que você não pode usar float, pois ele será convertido em um inteiro pequeno e a transação pode não acontecer, ou o evento upgradeneeded pode não ser chamado. Então se você usar 2.4 como versão:

+ +
var request = indexedDB.open("DBteste", 2.4); // não faça isso, pois a versão será convertida para 2.
+
+ +

Gerenciando handlers

+ +

A primeira coisa que você vai querer fazer em quase todos os requests é tratar os casos de success e error:

+ +
request.onerror = function(event) {
+  // Fazer algo com request.errorCode!
+};
+request.onsuccess = function(event) {
+  // Fazer algo com request.result!
+};
+ +

Qual das duas funções, onsuccess() ou onerror(),  será chamada? Se tudo correr bem, o evento de sucesso (que é um evento DOM event com propriedade type setada "success") é chamado com request como seu target. Uma vez chamado, a função onsuccess() no request é chamada com o evento de sucesso em seu contexto. Por outro lado, se acontecer algum problema, um evento de erro (que é um evento DOM com a propriedade type setada para "error") é chamado no request. Então a função onerror()  com o evento erro em seu contexto.

+ +

A API IndexedDB é feita para minimizar a necessidade de manipular erros, então você não fará muitos eventos de erro (ao menos, se você usar a API!) No  caso de abrir um banco, portanto, existe algumas condições comuns para eventos de erro. O problema mais comum é o usuário não dar permissão para criar o banco. Um dos principais objetivos do IndexedDB é permitir muitos dados serem armazenados para uso offline. (Para aprender mais sobre o quanto cada navegador pode armazenar, veja Storage limits).  

+ +

Obviamente, navegadores não querem armazenar dados que poluem seu computador, então o navegador mostra uma mensagem ao usuário na primeira vez que um aplicativo tenta abrir o IndexedDB. O usuário pode escolher permitir ou negar acesso. O IndexedDB também é desabilitado no modo privado dos navegadores (ctrl+shift+N no Chrome e ctrl+shift+P no Firefox). Isso acontece porque o intuito do modo privado é não deixar rastros na navegação.

+ +

Agora, assumindo que o usuário aprovou seu request para criar o banco, e você recebeu success; Qual é o próximo passo? O request foi gerado com a chamada de indexedDB.open(), e request.result é uma instância de IDBDatabase, e você definitivamente vai querer armazenar isso para usar depois. Veja abaixo:

+ +
var db;
+var request = indexedDB.open("DBteste");
+request.onerror = function(event) {
+  alert("Você não habilitou minha web app para usar IndexedDB?!");
+};
+request.onsuccess = function(event) {
+  db = request.result;
+};
+
+ +

Tratando Erros

+ +

Como mencionado acima, o evento de erro é chamado quando o request dá erro. Se você quer evitar manipuladores de erro a cada request, você pode adicionar um único manipulador de erro no objeto db, como abaixo:

+ +
db.onerror = function(event) {
+  // Função genérica para tratar os erros de todos os requests desse banco!
+  alert("Database error: " + event.target.errorCode);
+};
+
+ +

Um dos erros mais comuns ao abrir o banco é VER_ERR. Ele indica que a versão do banco existente é maior que a versão que você quer abrir.

+ +

Criando ou atualizando a versão do banco

+ +

Quando você cria um novo banco ou aumenta sua versão, o evento onupgradeneeded será chamado. No manipulador deste evento, você deve criar o objectStore necessário para a versão do banco:

+ +
// Este evento é implementado somente em navegadores mais recentes
+request.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  // cria um objectStore para esse banco
+  var objectStore = db.createObjectStore("nome", { keyPath: "minhaChave" });
+};
+ +

Neste caso, o banco já terá objectStores de suas versões anteriores, então você não terá que criar esses objectStores de novo. Você somente precisará criar um novo objectStore qualquer, ou deletar objectStores da versão anterior que não serão utilizados. Se você precisa mudar um objectStore existente (mudar o keyPath, por exemplo),  então você precisa deletar o objectStore antigo e criá-lo novamente com as novas opções. (Note que isso irá deletar a informação no objectStore! Se você precisa salvar a informação, você deve ler isso e salvá-lo em algum lugar antes de atualizar o banco.)

+ +

Blink/Webkit suporta a versão atual da especificação, nas versões do Chrome 23+ e Opera 17+; IE10+ também suporta. Outros motores e versões antigas não implementam a versão atual da especificação e não suportam a assinatura indexedDB.open(name, version).onupgradeneeded ainda.  Para mais informação sobre como atualizar a versão do banco em Webkit/Blink, veja IDBDatabase reference article.

+ +

Estruturando o banco

+ +

Agora a estrutura do banco. IndexedDB usa "armazens de objetos" em vez de tabelas, e um único banco de dados pode conter qualquer número de "armazem de objetos". Sempre que um valor é armazenado num objectStore, ele é associado a uma chave. Existe várias maneiras diferentes de uma chave ser mostrada, dependendo do que o objectStore usa, um key path ou key generator.

+ +

A tabela abaixo mostra as direfentes chaves suportadas:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Key Path (keyPath)Key Generator (autoIncrement)Description
NãoNãoEste objectStore pode ter qualquer tipo de valor primitivo como número ou string. Você deve suprir uma chave separada sempre que adicionar um novo valor.
SimNãoEste objectStore pode simplesmente armazenar objetos JavaScript. O objeto deve ter uma propriedade com o mesmo nome do key path.
NãoSimEste objectStore pode possuir qualquer tipo de valor. A chave é gerada para você, automaticamente, ou você pode suprir uma chave separada, caso utilize uma chave específica.
SimSimEste objectStore suporta somente objetos JavaScript. Normalmente uma chave é gerada e o valor dela é armazenado no objeto em uma propriedade com o mesmo nome da key path. Portanto, se a propriedade já existe, o valor dela será usado como chave, em vez do valor gerado.
+ +

Você também pode criar índices em qualquer objectStore. Um indice deixa você olhar os valores armazenados no objectStore usando o valor de uma propriedade do objectStore, em vez de sua chave.

+ +

Adicionalmente, indices tem a habilidade de forçar restrições simples nos dados armazenados. Setando uma flag única quando criar o índice, reforça que dois objetos são armazenados contendo o mesmo valor para o key path do índice. Então, por exemplo, se você tem um objeto armazenado que tem um conjunto de pessoas, e você quer ter certeza que ninguém tera o mesmo e-mail, você pode usar um índice com flag única para forçar isso.

+ +

Isso soa meio confuso, mas este exemplo pode iluminar o conceito. Primeiro, vamos definir alguns dados a serem usados no exemplo:

+ +
// Isso é o que os dados de nossos clientes será.
+const DadosClientes = [
+  { ssn: "444-44-4444", nome: "Bill", idade: 35, email: "bill@company.com" },
+  { ssn: "555-55-5555", nome: "Donna", idade: 32, email: "donna@home.org" }
+];
+
+ +

Agora  vamos ver  ccomo criar um IndexedDB para armazenar nossos dados:

+ +
const dbName = "clientes";
+
+var request = indexedDB.open(dbName, 2);
+
+request.onerror = function(event) {
+  // Tratar erros.
+};
+request.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  // Cria um objectStore para conter a informação sobre nossos clientes. Nós vamos
+  // usar "ssn" como key path porque sabemos que é único;
+  var objectStore = db.createObjectStore("clientes", { keyPath: "ssn" });
+
+  // Cria um índice para buscar clientes pelo nome. Podemos ter nomes
+  // duplicados, então não podemos usar como índice único.
+  objectStore.createIndex("nome", "nome", { unique: false });
+
+  // Cria um índice para buscar clientes por email. Queremos ter certeza
+  // que não teremos 2 clientes com o mesmo e-mail;
+  objectStore.createIndex("email", "email", { unique: true });
+
+  // Usando transação oncomplete para afirmar que a criação do objectStore
+  // é terminada antes de adicionar algum dado nele.
+  objectStore.transaction.oncomplete = function(event) {
+    // Armazenando valores no novo objectStore.
+    var clientesObjectStore = db.transaction("clientes", "readwrite").objectStore("clientes");
+    for (var i in DadosClientes) {
+      clientesObjectStore.add(DadosClientes[i]);
+    }
+  }
+};
+
+ +

Como falamos antes, onupgradeneeded é o único lugar onde você pode alterar a estrutura do banco. Nele você pode criar e deletar objectStores e construir ou remover índices.

+ +
Armazens de objetos são criados com uma única chamada de createObjectStore(). O método pega o nome do armazem e um objeto parâmetro. Mesmo que o objeto parâmetro seja opcional, ele é muito importante porque ele deixa você definir propriedades importantes e ajustar tipos de dados que você quer criar. No nosso caso, nós obtemos um objectStore chamado "clientes" e definimos um keyPath, que é a propriedade que faz um objeto individual ser único no banco. Essa propriedade, nesse exemplo, é "ssn", que simboliza o cpf (social security number), que é único. O "ssn" deve ser apresentado em cada objeto armazenado no objectStore
+ +

Nós também criamos um índice chamado "nome" ligado à propriedade nome. Assim como o createObjectStore(), o createIndex() tem um parâmetro opcional options que cuida do tipo de índice que você quer criar. Adicionando objetos que não tem a propriedade nome terá sucesso, porém esses objetos não aparecerão no índice "nome".

+ +

Nós podemos obter os objetos de clientes armazenados usando os ssn da objectStore diretamente, ou usando os nomes usados no índice. Para aprender como isso é feito, veja a seção usando um índice.

+ +

Usando um key generator

+ +

Setando uma flag autoIncrement ao criar o objectStore habilitará o key generator. Por padrão ele não é setado.

+ +

Com o key generator, a chave será gerada automaticamente quando você adicionar algum valor no objectStore. O atual número do key generator é sempre setado 1 quando a primeira key generator do objectStore é criada. Basicamente a próxima chave recebe o incremento de 1. O número atual da key generator nunca decresce,  a não ser se alguma operação do banco for revertida, como numa transação abortada, por exemplo. No entanto, deletar um registro ou limpar todos os registros nunca afeta o key generator dos objectStores.

+ +

Nós podemos criar outro objectStore com o key generator como abaixo:

+ +
// Abrindo o indexedDB.
+var request = indexedDB.open(dbName, 3);
+
+request.onupgradeneeded = function (event) {
+
+    var db = event.target.result;
+
+    // Criando outro objeto chamado "names" com o autoIncrement setado.
+    var objStore = db.createObjectStore("names", { autoIncrement : true });
+
+    // Porque "names" tem o the key generator, a chave para o nome é gerada automaticamente.
+    // Os registros adicionados serão assim:
+    // key : 1 => value : "Bill"
+    // key : 2 => value : "Donna"
+    for (var i in DadosClientes) {
+        objStore.add(DadosClientes[i].nome);
+    }
+}
+ +

Para mais detalhes veja "W3C Key Generators".

+ +

Adicionando, obtendo e removendo dados

+ +

Antes de fazer qualquer coisa em um novo banco, você precisa iniciar uma transação. Transações estão no objeto database, e você tem que especificar qual objectStore você quer na transaction. Uma vez que você está dentro da transação, você pode acessar os objectStores  com seus dados e fazer os requests. Depois, você precisa decidir se você vai fazer mudanças no banco ou se você simplesmente quer ler esses dados. Transações tem três modos disponíveis: readonly, readwrite, and versionchange.

+ +

Para mudar o "schema" ou estrutura do banco — o que envolve criar ou deletar objectStores ou índices — a transação deve ser em modo versionchange. Esta transação é aberta chamando o método {{domxref("IDBFactory.open")}} especificando a  version. (Em navegadores com WebKit que não tem a ultima especificação implementada, o método {{domxref("IDBFactory.open")}} tem apenas um parâmetro, o nome do banco; então você deve chamar {{domxref("IDBVersionChangeRequest.setVersion")}} para estabelecer uma transação versionchange.)

+ +

Para ler os registros de um objectStore existente, a transação pode ser tanto readonly quanto readwrite. Para fazer mudanças em um objectStore existente, a transação deve ser em modo readwrite. Você abre essas transações usando {{domxref("IDBDatabase.transaction")}}. O método aceita dois parâmetros: o storeNames (o escopo, definido como um array de objectStores que você quer acessar) e o modo (readonly or readwrite) da transação. O método retorna o objeto detransação contendo o método {{domxref("IDBIndex.objectStore")}}, que você pode usar para acessar seu objectStore. Por padrão, quando nenhum modo é especificado, a transação é aberta no modo readonly.

+ +

Você pode deixar o acesso aos dados mais rápido usando o escopo correto e o modo correto de transação. Aqui vai algumas dicas:

+ + + +

Adicionando dados no banco

+ +

Se você acabou de criar o banco, então você provavelmente quer escrever algo nele. Veja abaixo:

+ +
var transaction = db.transaction(["clientes"], "readwrite");
+// Nota: Implementações mais antigas usam uma versão IDBTransaction.READ_WRITE antiga em vez de "readwrite".
+// Então, para suportar versões antigas, escreva:
+// var transaction = db.transaction(["clientes"], IDBTransaction.READ_WRITE);
+ +

A função transaction() tem dois argumentos (opcionais) e retorna um objeto de transação. O primeiro argumento é uma lista de objectStores que serão trabalhados na transação. Você pode passar um array vazio se você quer uma transação com todos os objectStores, mas não faça isso pois a especificação diz que um array vazio pode gerar um erro InvalidAccessError. Se você não especificar nada no segundo parâmetro, você tem uma transação read-only. Se você quer escrever no banco, use "readwrite".

+ +

Agora que você tem uma transação, você precisa entender seu tempo de uso. Transações são amarradas a um evento. Se você faz uma transação fora de um evento, ela ficará inativa. A única maneira de manter uma transação ativa é fazer um request nela. Quando o request acabar você terá a oportunidade de extender a transação durante o callback. Se você tentar extender uma transação dentro de um evento, então ela tornará inativa. Se existir requests pendentes, a transação continua ativa. O tempo de vida de uma transação é realmente simples mas deve ser usada em um curto espaço de tempo. Outros exemplos poderão ajudá-lo. Se você começar a ver TRANSACTION_INACTIVE_ERR error então você está fazendo algo errado.

+ +

Transações podem receber eventos DOM de três tipos diferentes: error, abort, e complete. Nós falamos sobre o error, ou seja, a transação recebe um error sempre que o request gerar erro. Um ponto mais sutil é que o comportamento padrão de um erro é abortar a transação na qual ele estava. A menos que você manipule o erro chamando preventDefault() e fazendo algo depois, a transaçaõ inteira será desfeita. Este design força você a pensar sobre manipulação de erros, mas você pode sempre adicionar um manipulador de todos os erros se a manipulação separada estiver complicada. Se você não tratar o erro ou chamar abort() na transação, então a transação é desfeita (roll back) e o evento abort é chamado. Por outro lado, depois de todo request completado, você tem um evento complete. Se você fazer várias operações no banco, então seguir as operações de transações pode ser um caminho a seguir.

+ +

Agora que você tem uma transação, você precisará obter um objectStore dela. Transações somente deixam você obter um objectStore citado na transação. Então você pode adicionar os dados que precisa.

+ +
// Faz algo após a inserção dos dados.
+transaction.oncomplete = function(event) {
+  alert("Pronto!");
+};
+
+transaction.onerror = function(event) {
+  // Não esquecer de tratar os erros!
+};
+
+var objectStore = transaction.objectStore("clientes");
+for (var i in DadosClientes) {
+  var request = objectStore.add(DadosClientes[i]);
+  request.onsuccess = function(event) {
+    // event.target.result == DadosClientes[i].ssn;
+  };
+}
+ +

O result de um request gerado de uma chamada de add() é a chave do valor  que foi adicionado. Então neste caso, ele deve ser igual ao valor do ssn do objeto que foi adicionado, desde que o objeto use o ssn como key path. Note que a função add() não deixa nenhum objeto ser adicionado com a mesma chave. Se você está tentando modificar um registro existente, você deve usar o put(), como explica a seção  {{ anch("Updating an entry in the database") }}.

+ +

Removendo dados do banco

+ +

Para remoção o código é parecido:

+ +
var request = db.transaction(["clientes"], "readwrite")
+                .objectStore("clientes")
+                .delete("444-44-4444");
+request.onsuccess = function(event) {
+  // Pronto!
+};
+ +

Obtendo dados do banco

+ +

Agora que o banco tem algumas informações nele, você pode obtê-las de diferentes maneiras. Primeiro, um get() simples. Você precisa informar a chave do valor a ser obtido:

+ +
var transaction = db.transaction(["clientes"]);
+var objectStore = transaction.objectStore("clientes");
+var request = objectStore.get("444-44-4444");
+request.onerror = function(event) {
+  // Tratar erro!
+};
+request.onsuccess = function(event) {
+  // Fazer algo com request.result!
+  alert("O nome do SSN 444-44-4444 é " + request.result.name);
+};
+ +

Veja agora de maneira resumida:

+ +
db.transaction("clientes").objectStore("clientes").get("444-44-4444").onsuccess = function(event) {
+  alert("O nome do SSN 444-44-4444 é " + request.result.name);
+};
+ +

Viu como funciona? Desde que exista um objectStore, você pode evitar passar uma lista de objectStores que precisa na transação e passar apenas o nome como string. Você também pode ler do banco, apenas, então não precisará de uma transação "readwrite". Chamando transaction() com nenhum modo especificado, você terá uma transação "readonly". Outra consideração é que você não necessita salvar o request em uma variável. Desde que o evento DOM tenha o target que você precisará para obter a propriedade result.

+ +
+

Note: Você pode deixar o acesso aos dados mais rápido limitando o escopo e o modo de transação. Veja algumas dicas:

+ + +
+ +

Atualizando um registro no banco

+ +

Agora que obtemos algum dado, atualizá-ls é inserí-los novamente no IndexedDB é bem simples. Vamos atualizar o exemplo anterior:

+ +
var objectStore = db.transaction(["clientes"], "readwrite").objectStore("clientes");
+var request = objectStore.get("444-44-4444");
+request.onerror = function(event) {
+  // Tratar erro
+};
+request.onsuccess = function(event) {
+  // Obter os valores antigos
+  var data = request.result;
+
+  // atualizar algum dado
+  data.age = 42;
+
+  // Atulizar esse dado no banco
+  var requestUpdate = objectStore.put(data);
+   requestUpdate.onerror = function(event) {
+     // Tratar erro
+   };
+   requestUpdate.onsuccess = function(event) {
+     // Sucesso na atualização \o/
+   };
+};
+ +

Criamos uma objectStore e obtemos um cliente dele, identificado pelo ssn (444-44-4444). Nós atualizamos o objeto, passando-o como parâmetro de um método put de outro request (requestUpdate) sobrescrevendo o valor antigo.

+ +
+

Note que neste caso nós temos que especificar a transação readwrite porque nós queremos escrever no banco, não somente ler os dados dele.

+
+ +

Usando um cursor

+ +

Ao usar o método get() você precisa saber a chave do objeto que deseja obter. Se você quer passear entre todos os valores do seu objectStore, então você pode usar um cursor. Veja:

+ +
var objectStore = db.transaction("cliente").objectStore("cliente");
+
+objectStore.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    alert("O nome do SSN " + cursor.key + " é " + cursor.value.name);
+    cursor.continue();
+  }
+  else {
+    alert("Não existe mais registros!");
+  }
+};
+ +

A função openCursor() tem vários argumentos. Primeiro, você pode limitar o número de itens obtidos usando uma chave que veremos logo abaixo. Segundo, você pode especificar a direção que deseja iterar. No exemplo acima, nós estamos iterando em todos os objetos em ordem ascendente. O callback de sucesso para cursor é um pouco especial. O objeto cursor já é o result do request (acima nós usamos event.target.result). Então a chave atual e o valor pode ser encontrado na propriedade key e value do objeto cursor. Se você quer manter adiante, então você usa o método continue(). Quando você chegar ao fim dos dados (ou se não existem registros encontrados no openCursor()) você ainda tem um callback de sucesso, mas a propriedade result fica undefined.

+ +

Um padrão comum para cursores é obter todos os objetos em um objectStore e adicioná-los a um array como este:

+ +
var clientes = [];
+
+objectStore.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    clientes.push(cursor.value);
+    cursor.continue();
+  }
+  else {
+    alert("Todos os clientes: " + clientes);
+  }
+};
+ +
+

Note: Mozilla também implementou o método getAll() para ser usado nesse caso (e getAllKeys(), que está atualmente dentro da preferência do dom.indexedDB.experimental em about:config). Estes métodos não são parte do padrão IndexedDB, então eles podem desaparecer no futuro. Nós adicionamos porque achamos útil. O código abaixo faz o mesmo que o código acima:

+ +
objectStore.getAll().onsuccess = function(event) {
+  alert("Todos os clientes: " + event.target.result);
+};
+ +

Existe um custo de performance associado com a propriedade value do cursor, porque o objeto é criado de forma lenta. Quando você usa getAll() por exemplo, Gecko deve criar todos os objetos de uma vez. Se você está somente interessado em cada chave, é muito melhor usar o cursor do que usar o getAll(). Se você está tentando obter um array de todos os objetos, então é melhor usar o getAll().

+
+ +

Usando um índice

+ +

Armazenar dados de um cliente usando o SSN como chave é lógico pois o SSN identifica o cliente de forma única. Se você precisa obter um cliente pelo seu nome, portanto, você precisará iterar todos os registros no banco e comparar os nomes até achar o que você procura. Buscar dessa maneira é algo lento, então criamos um índice.

+ +
var index = objectStore.index("nome");
+index.get("John").onsuccess = function(event) {
+  alert("O SSN de John é " + event.target.result.ssn);
+};
+ +

O cursor "nome" não é único, então pode existir mais de um registro com o nome igual a "John". Neste caso você sempre obtem o registro com a chave de menor valor.

+ +

Se você precisa acessar todos os registros retornados, você pode usar um cursor. Você pode abrir dois tipos de cursores. Um cursor normal mapeia o índice ao objeto na objectStore. Uma cursor-chave mapeia o a propriedade índice à chave usada para armazenar o objeto. As diferenças são ilustradas abaixo:

+ +
// Usando um cursor normal para obter todos os objetos
+index.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // cursor.key é um nome, como "Bill", e cursor.value é o objeto inteiro.
+    alert("Nome: " + cursor.key + ", SSN: " + cursor.value.ssn + ", email: " + cursor.value.email);
+    cursor.continue();
+  }
+};
+
+// Usando um cursor-chave para obter todos os objetos
+index.openKeyCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // cursor.key é o nome, como "Bill", e cursor.value é o SSN (chave).
+    // Não tem como obter o resto do objeto
+    alert("Nome: " + cursor.key + ", SSN: " + cursor.value);
+    cursor.continue();
+  }
+};
+ +

Especificando o número e a direção dos cursores

+ +

Se você gostaria de limitar o número de valores retornados pelo cursor, você pode usar um objeto IDBKeyRange e passar isso como o primeiro argumento ao openCursor() ou openKeyCursor(). Você pode fazer um key range que permite um único valor, ou valores acima ou abaixo do especificado. O limite pode ser fechado (o key range inclui os valores dados) ou aberto (o key range não inclue os valores dados). Veja como funciona:

+ +
// Somente se for igual "Donna"
+var singleKeyRange = IDBKeyRange.only("Donna");
+
+// Combinações menores que "Bill", incluindo "Bill"
+var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill");
+
+// Combinações menores que "Bill", sem incluir "Bill"
+var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true);
+
+// Combinações maiores que Donna, não incluindo "Donna"
+var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true);
+
+// Combinações entre "Bill" e "Donna", sem incluir "Donna"
+var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true);
+
+// Para usar qualquer um desses key ranges, basta passar como primeiro parâmetro de openCursor()/openKeyCursor()
+index.openCursor(boundKeyRange).onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Faz algo com o que encontrar
+    cursor.continue();
+  }
+};
+ +

As vezes você pode querer iterar em ordem decrescente, em vez de crescente, alterando o segundo parâmetro de openCursor():

+ +
objectStore.openCursor(boundKeyRange, "prev").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Prev indica ordem decrescente
+    cursor.continue();
+  }
+};
+ +

Se você apenas quer especificar a ordem sem key range, é só passar null no primeiro parâmetro:

+ +
objectStore.openCursor(null, "prev").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Faça algo com os resultados.
+    cursor.continue();
+  }
+};
+ +

Uma vez que o índice "nome" não é único, pode existir várias entradas onde o nome é o mesmo. Isso não acontece com objectStores porque a chave deve ser sempre única. Se você deseja filtrar valores duplicados numa iteração do cursor, você pode passar nextunique (ou prevunique se quiser decrescer) como parâmetro de direção. Quando nextunique ou prevunique é usado, o registro com menor chave é retornado.

+ +
index.openKeyCursor(null, "nextunique").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Faça algo com os registros.
+    cursor.continue();
+  }
+};
+ +

Veja "IDBCursor Constants" para parâmetros válidos.

+ +

Mudança de versão quando a web app está aberta em outra aba.

+ +

Quando sua web app muda a versão você precisa considerar o que vai acontecer se o usuário está na versão antiga em uma aba, e carrega a versão nova na outra. Quando você chamar o open() com a versão mais nova, um evento onblocked  é chamado até que a aba da versão antiga seja fechada ou recarregada. Veja abaixo:

+ +
var openReq = mozIndexedDB.open("DBteste", 2);
+
+openReq.onblocked = function(event) {
+  // Se existe outra aba com a versão antiga
+  alert("Existe uma versão antiga da web app aberta em outra aba, feche-a por favor!");
+};
+
+openReq.onupgradeneeded = function(event) {
+  // Se estiver tudo fechado, então faça as devidas alterações
+  db.createObjectStore(/* ... */);
+  useDatabase(db);
+}
+
+openReq.onsuccess = function(event) {
+  var db = event.target.result;
+  useDatabase(db);
+  return;
+}
+
+function useDatabase(db) {
+  // Esteja certo de que adicionou um evento para notificar se a página muda a versão
+  // Nós devemos fechar o banco. Isso permite à outra página ser atualizada
+  // Se você não fizer isso a atualização não acontecerá até fechar as abas.
+  db.onversionchange = function(event) {
+    db.close();
+    alert("Uma nova versão desta web app está pronta. Atualiza, por favor!");
+  };
+
+  // Fazer algo com os bancos
+}
+
+ +

Segurança

+ +

IndexedDB usa o princípio de mesma origem, o que significa que o banco só será acessado pelo site que o criou.

+ +

É importante notar que o IndexedDB não funciona para conteúdo carregado em um frame de outro site (seja {{ HTMLElement("frame") }} ou {{ HTMLElement("iframe") }}. Esta é uma política de segurança e privacidade análoga ao bloqueio de cookies de terceiros. Para mais detalhes, veja {{ bug(595307) }}.

+ +

Alerta sobre fechar o navegador

+ +

Quando o navegador é fechado, qualquer transação pendente no IndexedDB será abortada (silenciosamente) — ele não vai completar, nem chamar o evento de erro.  Uma vez que o usuário pode sair do navegador, em qualquer momento, isto significa que você não pode confiar em qualquer transação específica para completar ou para saber que ela não foi concluída. Existem várias implicações nesse comportamento.

+ +

Primeiro, você deve ter o cuidado de sempre deixar seu banco de dados em um estado consistente, no final de cada transação. Por exemplo, suponha que você está usando IndexedDB para armazenar uma lista de itens que permitem ao usuário editar. Você salvar a lista após a edição, limpando o armazenamento de objetos e, em seguida, escrever a nova lista. Se você limpar o armazenamento de objetos em uma transação e escrever a nova lista em outra transação, há um perigo de que o navegador irá fechar após a limpeza de dados e antes da gravação, deixando-o com um banco de dados vazio. Para evitar isso, você deve combinar tanto a limpeza quanto a gravação em uma única transação.

+ +

Em segundo lugar, você nunca deve amarrar as operações de banco de dados ao evento unload. Se o evento unload é acionado pelo fechamento do navegador, todas as transações criadas no unload nunca serão concluídas. Uma abordagem intuitiva para manter algumas informações em sessões do navegador é lê-la a partir do banco de dados quando o navegador (ou uma determinada página) é aberta, atualizá-la assim que o usuário interagir com o navegador, e depois salvá-lo para o banco de dados quando o navegador (ou página) será fechada. No entanto, isso não vai funcionar. As transações de banco de dados será criado no unload, mas como elas são assíncronasserão abortadas antes que eles possam executar.

+ +

De fato, não existe uma maneira de garantir que as transações no IndexedDBserão completadas, mesmo com o fechamento padrão do navegador. Ver {{ bug(870645) }}.

+ +

Exemplo de IndexedDB

+ +

HTML

+ +
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
+
+    <h1>IndexedDB Demo: storing blobs, e-publication example</h1>
+    <div class="note">
+      <p>
+        Works and tested with:
+      </p>
+      <div id="compat">
+      </div>
+    </div>
+
+    <div id="msg">
+    </div>
+
+    <form id="register-form">
+      <table>
+        <tbody>
+          <tr>
+            <td>
+              <label for="pub-title" class="required">
+                Title:
+              </label>
+            </td>
+            <td>
+              <input type="text" id="pub-title" name="pub-title" />
+            </td>
+          </tr>
+          <tr>
+            <td>
+              <label for="pub-biblioid" class="required">
+                Bibliographic ID:<br/>
+                <span class="note">(ISBN, ISSN, etc.)</span>
+              </label>
+            </td>
+            <td>
+              <input type="text" id="pub-biblioid" name="pub-biblioid"/>
+            </td>
+          </tr>
+          <tr>
+            <td>
+              <label for="pub-year">
+                Year:
+              </label>
+            </td>
+            <td>
+              <input type="number" id="pub-year" name="pub-year" />
+            </td>
+          </tr>
+        </tbody>
+        <tbody>
+          <tr>
+            <td>
+              <label for="pub-file">
+                File image:
+              </label>
+            </td>
+            <td>
+              <input type="file" id="pub-file"/>
+            </td>
+          </tr>
+          <tr>
+            <td>
+              <label for="pub-file-url">
+                Online-file image URL:<br/>
+                <span class="note">(same origin URL)</span>
+              </label>
+            </td>
+            <td>
+              <input type="text" id="pub-file-url" name="pub-file-url"/>
+            </td>
+          </tr>
+        </tbody>
+      </table>
+
+      <div class="button-pane">
+        <input type="button" id="add-button" value="Add Publication" />
+        <input type="reset" id="register-form-reset"/>
+      </div>
+    </form>
+
+    <form id="delete-form">
+      <table>
+        <tbody>
+          <tr>
+            <td>
+              <label for="pub-biblioid-to-delete">
+                Bibliographic ID:<br/>
+                <span class="note">(ISBN, ISSN, etc.)</span>
+              </label>
+            </td>
+            <td>
+              <input type="text" id="pub-biblioid-to-delete"
+                     name="pub-biblioid-to-delete" />
+            </td>
+          </tr>
+          <tr>
+            <td>
+              <label for="key-to-delete">
+                Key:<br/>
+                <span class="note">(for example 1, 2, 3, etc.)</span>
+              </label>
+            </td>
+            <td>
+              <input type="text" id="key-to-delete"
+                     name="key-to-delete" />
+            </td>
+          </tr>
+        </tbody>
+      </table>
+      <div class="button-pane">
+        <input type="button" id="delete-button" value="Delete Publication" />
+        <input type="button" id="clear-store-button"
+               value="Clear the whole store" class="destructive" />
+      </div>
+    </form>
+
+    <form id="search-form">
+      <div class="button-pane">
+        <input type="button" id="search-list-button"
+               value="List database content" />
+      </div>
+    </form>
+
+    <div>
+      <div id="pub-msg">
+      </div>
+      <div id="pub-viewer">
+      </div>
+      <ul id="pub-list">
+      </ul>
+    </div>
+
+ +

CSS Content

+ +
body {
+  font-size: 0.8em;
+  font-family: Sans-Serif;
+}
+
+form {
+  background-color: #cccccc;
+  border-radius: 0.3em;
+  display: inline-block;
+  margin-bottom: 0.5em;
+  padding: 1em;
+}
+
+table {
+  border-collapse: collapse;
+}
+
+input {
+  padding: 0.3em;
+  border-color: #cccccc;
+  border-radius: 0.3em;
+}
+
+.required:after {
+  content: "*";
+  color: red;
+}
+
+.button-pane {
+  margin-top: 1em;
+}
+
+#pub-viewer {
+  float: right;
+  width: 48%;
+  height: 20em;
+  border: solid #d092ff 0.1em;
+}
+#pub-viewer iframe {
+  width: 100%;
+  height: 100%;
+}
+
+#pub-list {
+  width: 46%;
+  background-color: #eeeeee;
+  border-radius: 0.3em;
+}
+#pub-list li {
+  padding-top: 0.5em;
+  padding-bottom: 0.5em;
+  padding-right: 0.5em;
+}
+
+#msg {
+  margin-bottom: 1em;
+}
+
+.action-success {
+  padding: 0.5em;
+  color: #00d21e;
+  background-color: #eeeeee;
+  border-radius: 0.2em;
+}
+
+.action-failure {
+  padding: 0.5em;
+  color: #ff1408;
+  background-color: #eeeeee;
+  border-radius: 0.2em;
+}
+
+.note {
+  font-size: smaller;
+}
+
+.destructive {
+  background-color: orange;
+}
+.destructive:hover {
+  background-color: #ff8000;
+}
+.destructive:active {
+  background-color: red;
+}
+
+ +

 

+ +

JavaScript Content

+ +
(function () {
+  var COMPAT_ENVS = [
+    ['Firefox', ">= 16.0"],
+    ['Google Chrome',
+     ">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support"]
+  ];
+  var compat = $('#compat');
+  compat.empty();
+  compat.append('<ul id="compat-list"></ul>');
+  COMPAT_ENVS.forEach(function(val, idx, array) {
+    $('#compat-list').append('<li>' + val[0] + ': ' + val[1] + '</li>');
+  });
+
+  const DB_NAME = 'mdn-demo-indexeddb-epublications';
+  const DB_VERSION = 1; // Use a long long for this value (don't use a float)
+  const DB_STORE_NAME = 'publications';
+
+  var db;
+
+  // Used to keep track of which view is displayed to avoid uselessly reloading it
+  var current_view_pub_key;
+
+  function openDb() {
+    console.log("openDb ...");
+    var req = indexedDB.open(DB_NAME, DB_VERSION);
+    req.onsuccess = function (evt) {
+      // Better use "this" than "req" to get the result to avoid problems with
+      // garbage collection.
+      // db = req.result;
+      db = this.result;
+      console.log("openDb DONE");
+    };
+    req.onerror = function (evt) {
+      console.error("openDb:", evt.target.errorCode);
+    };
+
+    req.onupgradeneeded = function (evt) {
+      console.log("openDb.onupgradeneeded");
+      var store = evt.currentTarget.result.createObjectStore(
+        DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });
+
+      store.createIndex('biblioid', 'biblioid', { unique: true });
+      store.createIndex('title', 'title', { unique: false });
+      store.createIndex('year', 'year', { unique: false });
+    };
+  }
+
+  /**
+   * @param {string} store_name
+   * @param {string} mode either "readonly" or "readwrite"
+   */
+  function getObjectStore(store_name, mode) {
+    var tx = db.transaction(store_name, mode);
+    return tx.objectStore(store_name);
+  }
+
+  function clearObjectStore(store_name) {
+    var store = getObjectStore(DB_STORE_NAME, 'readwrite');
+    var req = store.clear();
+    req.onsuccess = function(evt) {
+      displayActionSuccess("Store cleared");
+      displayPubList(store);
+    };
+    req.onerror = function (evt) {
+      console.error("clearObjectStore:", evt.target.errorCode);
+      displayActionFailure(this.error);
+    };
+  }
+
+  function getBlob(key, store, success_callback) {
+    var req = store.get(key);
+    req.onsuccess = function(evt) {
+      var value = evt.target.result;
+      if (value)
+        success_callback(value.blob);
+    };
+  }
+
+  /**
+   * @param {IDBObjectStore=} store
+   */
+  function displayPubList(store) {
+    console.log("displayPubList");
+
+    if (typeof store == 'undefined')
+      store = getObjectStore(DB_STORE_NAME, 'readonly');
+
+    var pub_msg = $('#pub-msg');
+    pub_msg.empty();
+    var pub_list = $('#pub-list');
+    pub_list.empty();
+    // Resetting the iframe so that it doesn't display previous content
+    newViewerFrame();
+
+    var req;
+    req = store.count();
+    // Requests are executed in the order in which they were made against the
+    // transaction, and their results are returned in the same order.
+    // Thus the count text below will be displayed before the actual pub list
+    // (not that it is algorithmically important in this case).
+    req.onsuccess = function(evt) {
+      pub_msg.append('<p>There are <strong>' + evt.target.result +
+                     '</strong> record(s) in the object store.</p>');
+    };
+    req.onerror = function(evt) {
+      console.error("add error", this.error);
+      displayActionFailure(this.error);
+    };
+
+    var i = 0;
+    req = store.openCursor();
+    req.onsuccess = function(evt) {
+      var cursor = evt.target.result;
+
+      // If the cursor is pointing at something, ask for the data
+      if (cursor) {
+        console.log("displayPubList cursor:", cursor);
+        req = store.get(cursor.key);
+        req.onsuccess = function (evt) {
+          var value = evt.target.result;
+          var list_item = $('<li>' +
+                            '[' + cursor.key + '] ' +
+                            '(biblioid: ' + value.biblioid + ') ' +
+                            value.title +
+                            '</li>');
+          if (value.year != null)
+            list_item.append(' - ' + value.year);
+
+          if (value.hasOwnProperty('blob') &&
+              typeof value.blob != 'undefined') {
+            var link = $('<a href="' + cursor.key + '">File</a>');
+            link.on('click', function() { return false; });
+            link.on('mouseenter', function(evt) {
+                      setInViewer(evt.target.getAttribute('href')); });
+            list_item.append(' / ');
+            list_item.append(link);
+          } else {
+            list_item.append(" / No attached file");
+          }
+          pub_list.append(list_item);
+        };
+
+        // Move on to the next object in store
+        cursor.continue();
+
+        // This counter serves only to create distinct ids
+        i++;
+      } else {
+        console.log("No more entries");
+      }
+    };
+  }
+
+  function newViewerFrame() {
+    var viewer = $('#pub-viewer');
+    viewer.empty();
+    var iframe = $('<iframe />');
+    viewer.append(iframe);
+    return iframe;
+  }
+
+  function setInViewer(key) {
+    console.log("setInViewer:", arguments);
+    key = Number(key);
+    if (key == current_view_pub_key)
+      return;
+
+    current_view_pub_key = key;
+
+    var store = getObjectStore(DB_STORE_NAME, 'readonly');
+    getBlob(key, store, function(blob) {
+      console.log("setInViewer blob:", blob);
+      var iframe = newViewerFrame();
+
+      // It is not possible to set a direct link to the
+      // blob to provide a mean to directly download it.
+      if (blob.type == 'text/html') {
+        var reader = new FileReader();
+        reader.onload = (function(evt) {
+          var html = evt.target.result;
+          iframe.load(function() {
+            $(this).contents().find('html').html(html);
+          });
+        });
+        reader.readAsText(blob);
+      } else if (blob.type.indexOf('image/') == 0) {
+        iframe.load(function() {
+          var img_id = 'image-' + key;
+          var img = $('<img id="' + img_id + '"/>');
+          $(this).contents().find('body').html(img);
+          var obj_url = window.URL.createObjectURL(blob);
+          $(this).contents().find('#' + img_id).attr('src', obj_url);
+          window.URL.revokeObjectURL(obj_url);
+        });
+      } else if (blob.type == 'application/pdf') {
+        $('*').css('cursor', 'wait');
+        var obj_url = window.URL.createObjectURL(blob);
+        iframe.load(function() {
+          $('*').css('cursor', 'auto');
+        });
+        iframe.attr('src', obj_url);
+        window.URL.revokeObjectURL(obj_url);
+      } else {
+        iframe.load(function() {
+          $(this).contents().find('body').html("No view available");
+        });
+      }
+
+    });
+  }
+
+  /**
+   * @param {string} biblioid
+   * @param {string} title
+   * @param {number} year
+   * @param {string} url the URL of the image to download and store in the local
+   *   IndexedDB database. The resource behind this URL is subjected to the
+   *   "Same origin policy", thus for this method to work, the URL must come from
+   *   the same origin as the web site/app this code is deployed on.
+   */
+  function addPublicationFromUrl(biblioid, title, year, url) {
+    console.log("addPublicationFromUrl:", arguments);
+
+    var xhr = new XMLHttpRequest();
+    xhr.open('GET', url, true);
+    // Setting the wanted responseType to "blob"
+    // http://www.w3.org/TR/XMLHttpRequest2/#the-response-attribute
+    xhr.responseType = 'blob';
+    xhr.onload = function (evt) {
+                           if (xhr.status == 200) {
+                             console.log("Blob retrieved");
+                             var blob = xhr.response;
+                             console.log("Blob:", blob);
+                             addPublication(biblioid, title, year, blob);
+                           } else {
+                             console.error("addPublicationFromUrl error:",
+                                           xhr.responseText, xhr.status);
+                           }
+                         };
+    xhr.send();
+
+    // We can't use jQuery here because as of jQuery 1.8.3 the new "blob"
+    // responseType is not handled.
+    // http://bugs.jquery.com/ticket/11461
+    // http://bugs.jquery.com/ticket/7248
+    // $.ajax({
+    //   url: url,
+    //   type: 'GET',
+    //   xhrFields: { responseType: 'blob' },
+    //   success: function(data, textStatus, jqXHR) {
+    //     console.log("Blob retrieved");
+    //     console.log("Blob:", data);
+    //     // addPublication(biblioid, title, year, data);
+    //   },
+    //   error: function(jqXHR, textStatus, errorThrown) {
+    //     console.error(errorThrown);
+    //     displayActionFailure("Error during blob retrieval");
+    //   }
+    // });
+  }
+
+  /**
+   * @param {string} biblioid
+   * @param {string} title
+   * @param {number} year
+   * @param {Blob=} blob
+   */
+  function addPublication(biblioid, title, year, blob) {
+    console.log("addPublication arguments:", arguments);
+    var obj = { biblioid: biblioid, title: title, year: year };
+    if (typeof blob != 'undefined')
+      obj.blob = blob;
+
+    var store = getObjectStore(DB_STORE_NAME, 'readwrite');
+    var req;
+    try {
+      req = store.add(obj);
+    } catch (e) {
+      if (e.name == 'DataCloneError')
+        displayActionFailure("This engine doesn't know how to clone a Blob, " +
+                             "use Firefox");
+      throw e;
+    }
+    req.onsuccess = function (evt) {
+      console.log("Insertion in DB successful");
+      displayActionSuccess();
+      displayPubList(store);
+    };
+    req.onerror = function() {
+      console.error("addPublication error", this.error);
+      displayActionFailure(this.error);
+    };
+  }
+
+  /**
+   * @param {string} biblioid
+   */
+  function deletePublicationFromBib(biblioid) {
+    console.log("deletePublication:", arguments);
+    var store = getObjectStore(DB_STORE_NAME, 'readwrite');
+    var req = store.index('biblioid');
+    req.get(biblioid).onsuccess = function(evt) {
+      if (typeof evt.target.result == 'undefined') {
+        displayActionFailure("No matching record found");
+        return;
+      }
+      deletePublication(evt.target.result.id, store);
+    };
+    req.onerror = function (evt) {
+      console.error("deletePublicationFromBib:", evt.target.errorCode);
+    };
+  }
+
+  /**
+   * @param {number} key
+   * @param {IDBObjectStore=} store
+   */
+  function deletePublication(key, store) {
+    console.log("deletePublication:", arguments);
+
+    if (typeof store == 'undefined')
+      store = getObjectStore(DB_STORE_NAME, 'readwrite');
+
+    // As per spec http://www.w3.org/TR/IndexedDB/#object-store-deletion-operation
+    // the result of the Object Store Deletion Operation algorithm is
+    // undefined, so it's not possible to know if some records were actually
+    // deleted by looking at the request result.
+    var req = store.get(key);
+    req.onsuccess = function(evt) {
+      var record = evt.target.result;
+      console.log("record:", record);
+      if (typeof record == 'undefined') {
+        displayActionFailure("No matching record found");
+        return;
+      }
+      // Warning: The exact same key used for creation needs to be passed for
+      // the deletion. If the key was a Number for creation, then it needs to
+      // be a Number for deletion.
+      req = store.delete(key);
+      req.onsuccess = function(evt) {
+        console.log("evt:", evt);
+        console.log("evt.target:", evt.target);
+        console.log("evt.target.result:", evt.target.result);
+        console.log("delete successful");
+        displayActionSuccess("Deletion successful");
+        displayPubList(store);
+      };
+      req.onerror = function (evt) {
+        console.error("deletePublication:", evt.target.errorCode);
+      };
+    };
+    req.onerror = function (evt) {
+      console.error("deletePublication:", evt.target.errorCode);
+      };
+  }
+
+  function displayActionSuccess(msg) {
+    msg = typeof msg != 'undefined' ? "Success: " + msg : "Success";
+    $('#msg').html('<span class="action-success">' + msg + '</span>');
+  }
+  function displayActionFailure(msg) {
+    msg = typeof msg != 'undefined' ? "Failure: " + msg : "Failure";
+    $('#msg').html('<span class="action-failure">' + msg + '</span>');
+  }
+  function resetActionStatus() {
+    console.log("resetActionStatus ...");
+    $('#msg').empty();
+    console.log("resetActionStatus DONE");
+  }
+
+  function addEventListeners() {
+    console.log("addEventListeners");
+
+    $('#register-form-reset').click(function(evt) {
+      resetActionStatus();
+    });
+
+    $('#add-button').click(function(evt) {
+      console.log("add ...");
+      var title = $('#pub-title').val();
+      var biblioid = $('#pub-biblioid').val();
+      if (!title || !biblioid) {
+        displayActionFailure("Required field(s) missing");
+        return;
+      }
+      var year = $('#pub-year').val();
+      if (year != '') {
+        // Better use Number.isInteger if the engine has EcmaScript 6
+        if (isNaN(year))  {
+          displayActionFailure("Invalid year");
+          return;
+        }
+        year = Number(year);
+      } else {
+        year = null;
+      }
+
+      var file_input = $('#pub-file');
+      var selected_file = file_input.get(0).files[0];
+      console.log("selected_file:", selected_file);
+      // Keeping a reference on how to reset the file input in the UI once we
+      // have its value, but instead of doing that we rather use a "reset" type
+      // input in the HTML form.
+      //file_input.val(null);
+      var file_url = $('#pub-file-url').val();
+      if (selected_file) {
+        addPublication(biblioid, title, year, selected_file);
+      } else if (file_url) {
+        addPublicationFromUrl(biblioid, title, year, file_url);
+      } else {
+        addPublication(biblioid, title, year);
+      }
+
+    });
+
+    $('#delete-button').click(function(evt) {
+      console.log("delete ...");
+      var biblioid = $('#pub-biblioid-to-delete').val();
+      var key = $('#key-to-delete').val();
+
+      if (biblioid != '') {
+        deletePublicationFromBib(biblioid);
+      } else if (key != '') {
+        // Better use Number.isInteger if the engine has EcmaScript 6
+        if (key == '' || isNaN(key))  {
+          displayActionFailure("Invalid key");
+          return;
+        }
+        key = Number(key);
+        deletePublication(key);
+      }
+    });
+
+    $('#clear-store-button').click(function(evt) {
+      clearObjectStore();
+    });
+
+    var search_button = $('#search-list-button');
+    search_button.click(function(evt) {
+      displayPubList();
+    });
+
+  }
+
+  openDb();
+  addEventListeners();
+
+})(); // Immediately-Invoked Function Expression (IIFE)
+
+ +

{{ LiveSampleLink('Full_IndexedDB_example', "Test the online live demo") }}

+ +

Ver também

+ +

Uma leitura adicional para você encontrar mais informações.

+ +

Refências

+ + + +

Guias e tutoriais

+ + diff --git a/files/pt-br/web/api/keyboardevent/index.html b/files/pt-br/web/api/keyboardevent/index.html new file mode 100644 index 0000000000..d552857d3f --- /dev/null +++ b/files/pt-br/web/api/keyboardevent/index.html @@ -0,0 +1,439 @@ +--- +title: KeyboardEvent +slug: Web/API/KeyboardEvent +tags: + - API + - DOM + - Evento + - Inteface + - Referencia +translation_of: Web/API/KeyboardEvent +--- +

{{APIRef("DOM Events")}}

+ +

Objetos do tipo KeyboardEvent descrevem a interação do usuário com o teclado. Cada evento descreve uma tecla; o tipo de evento (keydown, keypress, ou keyup) identifica qual tipo de ação foi executada.

+ +
Note: O KeyboardEvent indica o que está havendo com a tecla. Quando você precisar lidar com entrada de texto, use o evento input do HTML5  . Por exemplo, se o usuário envia texto por meio de um sistema manuscrito como um tablet PC, eventos das teclas podem não ser disparados.
+ +

Construtor

+ +
+
{{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}
+
Cria um objeto do tipo KeyboardEvent.
+
+ +

Métodos

+ +

Essa interface também herda métodos dos seus pais, {{domxref("UIEvent")}} e {{domxref("Event")}}.

+ +
+
{{domxref("KeyboardEvent.getModifierState()")}}
+
Retorna um {{jsxref("Boolean")}} indicando se uma tecla, como AltShiftCtrl, ou Meta, foi pressionada quando o evento foi criado.
+
{{domxref("KeyboardEvent.initKeyEvent()")}}{{deprecated_inline}}
+
Inicializa um objeto do tipo KeyboardEvent . isso foi apenas implementado por Gecko (outros usaram {{domxref("KeyboardEvent.initKeyboardEvent()")}}) e não deve mais ser usado. A forma moderna padrão é usar o construtor {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.
+
{{domxref("KeyboardEvent.initKeyboardEvent()")}}{{deprecated_inline}}
+
Inicializa um objeto do tipo KeyboardEvent . Isso nunca foi implementado por Gecko (que usou {{domxref("KeyboardEvent.initKeyEvent()")}}) e não deve mais ser usado. A forma moderna padrão é usar o construtor  {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.
+
+ +

Propriedades

+ +

Essa interface também herda métodos dos seus pais, {{domxref("UIEvent")}} e {{domxref("Event")}}.

+ +
+
{{domxref("KeyboardEvent.altKey")}} {{Readonlyinline}}
+
Retorna um {{jsxref("Boolean")}} que é true se a tecla Alt ( Option ou  no OS X) estava ativa quando o evento foi acionado.
+
{{domxref("KeyboardEvent.char")}} {{Non-standard_inline}}{{Deprecated_inline}}{{Readonlyinline}}
+
Retorna um {{domxref("DOMString")}} representando o valor da tecla em caractere. Se a tecla corresponde a um caractere exibível, esse valor é uma string Unicode não-vazia contendo aquele caractere. Se a tecla não possui uma representação exibível, ela é uma string vazia. +
Nota: Se a tecla é usada como um macro que insere caracteres múltiplos, o valor desse atributo é a string inteira, não apenas o primeiro caractere.
+ +
Aviso: Isso foi removido dos Eventos DOM de nível 3. Isso é apenas suportado no IE.
+
+
{{domxref("KeyboardEvent.charCode")}} {{Deprecated_inline}}{{Readonlyinline}}
+
Returns a {{jsxref("Number")}} representing the Unicode reference number of the key; this attribute is used only by the keypress event. For keys whose char attribute contains multiple characters, this is the Unicode value of the first character in that attribute. In Firefox 26 this returns codes for printable characters. +
Aviso: Este atributo esta depreciado; você deve usar key no lugar, se disponivel.
+
+
{{domxref("KeyboardEvent.code")}} {{Readonlyinline}}
+
Returns a {{domxref("DOMString")}} with the code value of the key represented by the event.
+
{{domxref("KeyboardEvent.ctrlKey")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the Ctrl key was active when the key event was generated.
+
{{domxref("KeyboardEvent.isComposing")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the event is fired between after compositionstart and before compositionend.
+
{{domxref("KeyboardEvent.key")}} {{Readonlyinline}}
+
Returns a {{domxref("DOMString")}} representing the key value of the key represented by the event.
+
{{domxref("KeyboardEvent.keyCode")}} {{deprecated_inline}}{{Readonlyinline}}
+
Returns a {{jsxref("Number")}} representing a system and implementation dependent numerical code identifying the unmodified value of the pressed key. +
Aviso: Este atributo esta depreciado; você deve usar key no lugar, se disponivel.
+
+
{{domxref("KeyboardEvent.locale")}} {{Readonlyinline}}
+
Returns a {{domxref("DOMString")}} representing a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn't know the keyboard's locale. +
Note: This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language.
+
+
{{domxref("KeyboardEvent.location")}} {{Readonlyinline}}
+
Returns a {{jsxref("Number")}} representing the location of the key on the keyboard or other input device.
+
{{domxref("KeyboardEvent.metaKey")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the Meta (or Command on OS X) key was active when the key event was generated.
+
{{domxref("KeyboardEvent.repeat")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the key is being held down such that it is automatically repeating.
+
{{domxref("KeyboardEvent.shiftKey")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the Shift key was active when the key event was generated.
+
{{domxref("KeyboardEvent.which")}} {{deprecated_inline}}{{Readonlyinline}}
+
Returns a {{jsxref("Number")}} representing a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as keyCode. +
Aviso: Este atributo esta depreciado; você deve usar key no lugar, se disponivel.
+
+
+ +

Notes

+ +

There are keydown, keypress, and keyup events. For most keys, Gecko dispatches a sequence of key events like this:

+ +
    +
  1. When the key is first depressed, the keydown event is sent.
  2. +
  3. If the key is not a modifier key, the keypress event is sent.
  4. +
  5. When the user releases the key, the keyup event is sent.
  6. +
+ +

Special cases

+ +

Certain keys toggle the state of an LED indicator, such as Caps Lock, Num Lock, and Scroll Lock. On Windows and Linux, these keys dispatch only the keydown and keyup events. Note that on Linux, Firefox 12 and earlier also dispatched the keypress event for these keys.

+ +

On Mac, however, Caps Lock dispatches only the keydown event due to a platform event model limitation. Num Lock had been supported on old MacBook (2007 model and older) but Mac hasn't supported Num Lock feature even on external keyboards in these days. On the old MacBook which has Num Lock key, Num Lock doesn't cause any key events. And Gecko supports Scroll Lock key if an external keyboard which has F14 is connected. However, it generates keypress event. This inconsistent behavior is a bug; see {{bug(602812)}}.

+ +

Auto-repeat handling

+ +

When a key is pressed and held down, it begins to auto-repeat. This results in a sequence of events similar to the following being dispatched:

+ +
    +
  1. keydown
  2. +
  3. keypress
  4. +
  5. <<repeating until the user releases the key>>
  6. +
  7. keyup
  8. +
+ +

This is what the DOM Level 3 specification says should happen. There are some caveats, however, as described below.

+ +

Auto-repeat on some GTK environments such as Ubuntu 9.4

+ +

In some GTK-based environments, auto-repeat dispatches a native key-up event automatically during auto-repeat, and there's no way for Gecko to know the difference between a repeated series of keypresses and an auto-repeat. On those platforms, then, an auto-repeat key will generate the following sequence of events:

+ +
    +
  1. keydown
  2. +
  3. keypress
  4. +
  5. <<repeating until the user releases the key>>
  6. +
  7. keyup
  8. +
+ +

In these environments, unfortunately, there's no way for web content to tell the difference between auto-repeating keys and keys that are just being pressed repeatedly.

+ +

Auto-repeat handling prior to Gecko 4.0

+ +

Before Gecko 4.0 {{geckoRelease('4.0')}}, keyboard handling was less consistent across platforms.

+ +
+
Windows
+
Auto-repeat behavior is the same as in Gecko 4.0 and later.
+
Mac
+
After the initial keydown event, only keypress events are sent until the keyup event occurs; the inter-spaced keydown events are not sent.
+
Linux
+
The event behavior depends on the specific platform. It will either behave like Windows or Mac depending on what the native event model does.
+
+ +

Example

+ +
<!DOCTYPE html>
+<html>
+<head>
+<script>
+var metaChar = false;
+var exampleKey = 16;
+
+function keyEvent(event) {
+  var key = event.keyCode || event.which;
+  var keychar = String.fromCharCode(key);
+  if (key == exampleKey) {
+    metaChar = true;
+  }
+  if (key != exampleKey) {
+    if (metaChar) {
+      alert("Combination of metaKey + " + keychar);
+      metaChar = false;
+    } else {
+      alert("Key pressed " + key);
+    }
+  }
+}
+
+function metaKeyUp (event) {
+  var key = event.keyCode || event.which;
+
+  if (key == exampleKey) {
+    metaChar = false;
+  }
+}
+</script>
+</head>
+
+<body onkeydown="keyEvent(event)" onkeyup="metaKeyUp(event)">
+</body>
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events', '#interface-KeyboardEvent', 'KeyboardEvent')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

The KeyboardEvent interface specification went through numerous draft versions, first under DOM Events Level 2 where it was dropped as no consensus arose, then under DOM Events Level 3. This led to the implementation of non-standard initialization methods, the early DOM Events Level 2 version, {{domxref("KeyboardEvent.initKeyEvent()")}} by Gecko browsers and the early DOM Events Level 3 version, {{domxref("KeyboardEvent.initKeyboardEvent()")}} by others. Both have been superseded by the modern usage of a constructor: {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
constructor{{CompatVersionUnknown}}{{CompatGeckoDesktop("31.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
.char{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
.charCode{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
.codeSee Browser compatibility of {{domxref("KeyboardEvent.code")}}.
.isComposing{{CompatNo}}{{CompatGeckoDesktop("31.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
.keySee Browser compatibility of {{domxref("KeyboardEvent.key")}}.
.keyCode{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
.locale{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
.location{{CompatVersionUnknown}}{{CompatGeckoDesktop("15.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
.repeat{{CompatVersionUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
.which{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
.getModifierState()See Browser compatibility of {{domxref("KeyboardEvent.getModifierState")}}
.initKeyboardEvent(){{CompatVersionUnknown}}[1]{{CompatNo}}[2]{{CompatIE("9.0")}}[3]{{CompatUnknown}}{{CompatVersionUnknown}}[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
constructor{{CompatUnknown}}{{CompatGeckoMobile("31.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.char{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.charCode{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.codeSee Browser compatibility of {{domxref("KeyboardEvent.code")}}.
.isComposing{{CompatNo}}{{CompatGeckoMobile("31.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
.keySee Browser compatibility table of {{domxref("KeyboardEvent.key")}}.
.keyCode{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.locale{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.location{{CompatUnknown}}{{CompatGeckoMobile("15.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.repeat{{CompatUnknown}}{{CompatGeckoMobile("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.which{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.getModifierState()See Browser compatibility of {{domxref("KeyboardEvent.getModifierState")}}
.initKeyboardEvent(){{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] The arguments of initKeyboardEvent() of WebKit and Blink's are different from the definition in DOM Level 3 Events. The method is: initKeyboardEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in views::AbstractView viewArg, in DOMString keyIndentifierArg, in number locationArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in boolean altGraphKeyArg)

+ +

[2] Gecko won't support initKeyboardEvent() because supporting it completely breaks feature detection of web applications. See {{Bug(999645)}}.

+ +

[3] The argument of initKeyboardEvent() of IE is different from the definition in DOM Level 3 Events. The method is: initKeyboardEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in views::AbstractView viewArg, in DOMString keyArg, in number locationArg, in DOMString modifierListArg, in boolean repeatArt, in DOMString locationArg). See document of initKeyboardEvent() in MSDN.

+ +

[4] Note that manually firing an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.

diff --git a/files/pt-br/web/api/location/assign/index.html b/files/pt-br/web/api/location/assign/index.html new file mode 100644 index 0000000000..e1a1cf8609 --- /dev/null +++ b/files/pt-br/web/api/location/assign/index.html @@ -0,0 +1,120 @@ +--- +title: Location.assign() +slug: Web/API/Location/assign +tags: + - API + - HTML-DOM + - Location + - Referencia + - metodo +translation_of: Web/API/Location/assign +--- +

{{ APIRef("HTML DOM") }}

+ +

O método Location.assign() faz com que o navegador carregue o documento na URL especificada e a exiba na janela atual.

+ +

Se a tatefa não poder ser executada por alguma violação de segurança, uma {{domxref("DOMException")}} do tipo SECURITY_ERROR será lançada. Isso acontece se a origem do script chamador do método for diferente da origem da página originalmente descrita no objeto {{domxref("Location")}}, geralmente quando o script está hospedado em um dominio diferente.

+ +

Se a URL especificada for inválida, uma {{domxref("DOMException")}} do tipo SYNTAX_ERROR será lançada.

+ +

Sintaxe

+ +
location.assign(url);
+
+ +

Parâmetros

+ +
+
url
+
É uma {{domxref("DOMString")}} contendo a URL da página destino.
+
+ +

Exemplos

+ +
// Navega para a página do artigo Location.reload
+document.location.assign('https://developer.mozilla.org/en-US/docs/Web/API/Location.reload');
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('HTML WHATWG', "history.html#dom-location-assign", "Location.assign()")}}{{Spec2('HTML WHATWG')}}Sem alterações  no {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#dom-location-assign", "Location.assign()")}}{{Spec2('HTML5 W3C')}}Definição inicial.
+ +

Compatibilidade com Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/location/index.html b/files/pt-br/web/api/location/index.html new file mode 100644 index 0000000000..027a8564ec --- /dev/null +++ b/files/pt-br/web/api/location/index.html @@ -0,0 +1,184 @@ +--- +title: Location +slug: Web/API/Location +tags: + - API + - Interface + - Location +translation_of: Web/API/Location +--- +

{{APIRef("HTML DOM")}}

+ +

Resumo

+ +

A interface Location representa a localização do objeto a qual ele está associado. Mudanças feitas na interface serão refletidas nos objetos relacionados a ela. Tanto a interface {{domxref("Document")}}, como a interface {{domxref("Window")}} , têm este vínculo com a inteface Location, acessível via {{domxref("Document.location")}} e {{domxref("Window.location")}} respectivamente.

+ +

Propriedades

+ +

A inteface Location não herda nenhuma propriedade, mas implementa as propriedades de {{domxref("URLUtils")}}.

+ +
+
{{domxref("URLUtils.href")}}
+
É uma {{domxref("DOMString")}} que contém toda URL.
+
{{domxref("URLUtils.protocol")}}
+
É uma {{domxref("DOMString")}} que contém o esquema de protocolo da URL, incluindo o final ':'.
+
{{domxref("URLUtils.host")}}
+
É uma {{domxref("DOMString")}} que contém o host, que é o hostname seguido de ':' e a port da URL.
+
{{domxref("URLUtils.hostname")}}
+
É uma {{domxref("DOMString")}} que contém o domínio da URL.
+
{{domxref("URLUtils.port")}}
+
É uma {{domxref("DOMString")}} que contém o número da porta da URL.
+
{{domxref("URLUtils.pathname")}}
+
É uma {{domxref("DOMString")}} que contém '/', como caractere inicial, seguido do caminho da URL.
+
{{domxref("URLUtils.search")}}
+
É uma {{domxref("DOMString")}} que contém um '?' seguido dos parâmetros da URL.
+
{{domxref("URLUtils.hash")}}
+
É uma {{domxref("DOMString")}} que contém um '#' seguido do identificador de fragmento da URL.
+
{{domxref("URLUtils.username")}}
+
É uma {{domxref("DOMString")}} que contém o nome de usuário especificado antes do nome de domínio.
+
{{domxref("URLUtils.password")}}
+
É uma {{domxref("DOMString")}} que contém a senha especificada antes do nome de domínio.
+
{{domxref("URLUtils.origin")}} {{readOnlyInline}}
+
Retorna uma {{domxref("DOMString")}} que contém a forma canônica da origem do local especificado.
+
+ +

Métodos

+ +

A inteface Location não herda nenhum método, mas implementa os métodos de {{domxref("URLUtils")}}.

+ +
+
{{domxref("Location.assign()")}}
+
Carrega o recurso na URL fornecida como parâmetro.
+
{{domxref("Location.reload()")}}
+
Recarrega o recurso a partir da URL atual. Seu único parâmetro opcional é um {{domxref("Boolean")}}, que, quando verdadeiro (true), faz com que a página sempre seja recarregada a partir do servidor. Se for falso (false) ou não especificado,  o navegador pode recarregar a página a partir de seu cache.
+
{{domxref("Location.replace()")}}
+
Substitui o recurso atual pelo recurso presente na URL fornecida. A diferença entre o método assign() é que após usar replace() a página atual não será salva na sessão  {{domxref("History")}}, ou seja, o usuário não será capaz de usar o botão voltar para navegar até a página.
+
{{domxref("URLUtils.toString()")}}
+
Retorna uma {{domxref("DOMString")}} que contém toda URL. O método é um sinônimo para {{domxref("URLUtils.href")}}, embora não possa ser usado para modificar o valor.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "history.html#the-location-interface", "Location")}}{{Spec2('HTML WHATWG')}}Nenhuma mudança a partir {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Location")}}{{Spec2('HTML5 W3C')}}Definição inicial.
+ +

Compatibilidade entre Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
origin em Windows.location{{CompatUnknown}}{{CompatGeckoDesktop("21")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
origin em todos objetos location (mas nos objetos Workers, que usam {{domxref("WorkerLocation")}}){{CompatUnknown}}{{CompatGeckoDesktop("26")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
username e password{{CompatUnknown}}{{CompatGeckoDesktop("26")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
origin on Windows.location{{CompatUnknown}}{{CompatGeckoMobile("21")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
origin on all location objects (mas nos objetos Workers, que usam {{domxref("WorkerLocation")}}){{CompatUnknown}}{{CompatGeckoMobile("26")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
username e password{{CompatUnknown}}{{CompatGeckoMobile("26")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/location/reload/index.html b/files/pt-br/web/api/location/reload/index.html new file mode 100644 index 0000000000..24d990bbe8 --- /dev/null +++ b/files/pt-br/web/api/location/reload/index.html @@ -0,0 +1,114 @@ +--- +title: Location.reload() +slug: Web/API/Location/reload +tags: + - API + - HTML-DOM + - Localização + - Referencia + - metodo +translation_of: Web/API/Location/reload +--- +

{{ APIRef("HTML DOM") }}

+ +

O método Location.reload() recarrega a URL atual. Seu unico parâmetro opcional é um {{domxref("Boolean")}}, que, quando true, faz com que a página sempre seja recarregada do servidor. Se ele é false ou não estiver especificado, o navegador pode carregar ela do cache.

+ +

Caso não seja possível recarregar por questões de violação de segurança, uma {{domxref("DOMException")}} do tipo SECURITY_ERROR é jogada. Isso acontece se a origem do script que chama o método é diferente da origem da página originalmente descrita pelo objeto {{domxref("Location")}}, usualmente quando o script é hosteado em um domínio diferente.

+ +

Sintaxe

+ +
object.reload(forcedReload);
+
+ +

Parametros

+ +
+
forcedReload {{optional_inline}}
+
É uma flag {{domxref("Boolean")}}, que quando true, faz com que a página sempre seja recarregada do servidor, se é false ou não for definido, o navegador pode recarregar a página do cache.
+
+ +

Exemplos

+ +
// Recarrega a página atual sem usar o cache
+document.location.reload(true);
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "history.html#dom-location-reload", "Location.reload()")}}{{Spec2('HTML WHATWG')}}Nenhuma mudança do  {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#dom-location-reload", "Location.reload()")}}{{Spec2('HTML5 W3C')}}Definição inicial.
+ +

Compatibilidade de Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/location/search/index.html b/files/pt-br/web/api/location/search/index.html new file mode 100644 index 0000000000..6cc17724d5 --- /dev/null +++ b/files/pt-br/web/api/location/search/index.html @@ -0,0 +1,55 @@ +--- +title: 'Location: search' +slug: Web/API/Location/search +tags: + - API + - Location + - Propriedade + - Search +translation_of: Web/API/Location/search +--- +
{{ApiRef("Location")}}
+ +

A propriedade search da interface {{domxref("Location")}} é um texto de busca, também chamado de query string ou querystring; isso é, uma {{domxref("USVString")}} contendo um '?' seguido pelos parâmetros da URL.

+ +

Os navegadores modernos fornecem o URLSearchParams e o URL.searchParams para facilitar a análise dos parâmetros da querystring.

+ +

Sintaxe

+ +
string = object.search;
+object.search = string;
+
+ +

Exemplos

+ +
// Seleciona o elemento <a id="myAnchor" href="https://developer.mozilla.org/en-US/docs/Location.search?q=123">
+var anchor = document.getElementById("myAnchor");
+var queryString = anchor.search; // Retorna:'?q=123'
+
+// Análise adicional:
+let params = new URLSearchParams(queryString);
+let q = parseInt(params.get("q")); // é o número 123
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-location-search', 'search')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ +

Compatibilidade do navegador

+ + + +

{{Compat("api.Location.search")}}

diff --git a/files/pt-br/web/api/mediadevices/index.html b/files/pt-br/web/api/mediadevices/index.html new file mode 100644 index 0000000000..83e3452f58 --- /dev/null +++ b/files/pt-br/web/api/mediadevices/index.html @@ -0,0 +1,251 @@ +--- +title: MediaDevices +slug: Web/API/MediaDevices +translation_of: Web/API/MediaDevices +--- +
{{APIRef("Media Capture and Streams")}}{{SeeCompatTable}}
+ +

As interfaces MediaDevices proporcionam accesso aos dispositivos de entrada de midia conectados, como câmeras e microfones, bem como compartilhamento de tela. Essencialmente, isso te permite obter acesso a qualquer mídia gerada pelo hardware.

+ +

Propriedades

+ +

As mesmas propriedades de {{domxref("EventTarget")}}.

+ +

Manipuladores de Evento

+ +
+
{{ domxref("MediaDevices.ondevicechange") }}
+
O manipulador de evento para o evento {{event("devicechange")}}. Esse evento é entregue ao objeto MediaDevices quando uma entrada de mídia ou dispositivo de saída é conectado ou removido do computador do usuário.
+
+ +

Métodos

+ +

Mesmos métodos de {{domxref("EventTarget")}}.

+ +
+
{{ domxref("EventTarget.addEventListener()") }}
+
Registra um manipulador de eventos para um tipo específico de evento.
+
{{ domxref("MediaDevices.enumerateDevices()") }}
+
Obtém um array de informações sobre a entrada de midia e dispositivos de saída disponíveis no sistema.
+
{{domxref("MediaDevices.getSupportedConstraints()")}}
+
Retorna um objeto consoante com {{domxref("MediaTrackSupportedConstraints")}} indicando quais propriedades restritivas são suportadas na interface {{domxref("MediaStreamTrack")}}. Veja {{SectionOnPage("/en-US/docs/Web/API/Media_Streams_API", "Capabilities and constraints")}} para aprender mais sobre restrições e como usá-las.
+
{{ domxref("MediaDevices.getUserMedia()") }}
+
Após a permissão do usuário (pedida através de um prompt), liga a câmera, microfone e/ou a tramissão de tela no sistema e fornece uma {{domxref("MediaStream")}} contendo uma faixa de vídeo e/ou áudio com a entrada.
+
{{ domxref("EventTarget.removeEventListener()") }}
+
Remove um escutador de evento.
+
+ +

Exemplo

+ +
'use strict';
+
+// Coloca as variáveis no escopo global para torná-las disponível para o Console do navegador.
+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; // torna as variáveis disponíveis para o Console do navegador
+  video.srcObject = stream;
+})
+.catch(function(error) {
+  if (error.name === 'ConstraintNotSatisfiedError') {
+    errorMsg('A resolução ' + constraints.video.width.exact + 'x' +
+        constraints.video.width.exact + ' px não é suportada pelo seu dispositivo.');
+  } else if (error.name === 'PermissionDeniedError') {
+    errorMsg('As permissões para usar sua câmera e microfone não foram fornecidas. ' +
+      'Você precisa permitir o acesso da página aos seus dispositivos para ' +
+      'que a demo funcione.');
+  }
+  errorMsg('getUserMedia error: ' + error.name, error);
+});
+
+function errorMsg(msg, error) {
+  errorElement.innerHTML += '<p>' + msg + '</p>';
+  if (typeof error !== 'undefined') {
+    console.error(error);
+  }
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Media Capture', '#mediadevices', 'MediaDevices')}}{{Spec2('Media Capture')}}Definição inicial
+ +

Compatibilidade

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico{{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}}
Eventos ondevicechange e devicechange{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(51)}}[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
Captura de áudio estéreo{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(55)}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroid WebviewChrome para AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome para Android
Suporte Básico{{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}}
Eventos ondevicechange e devicechange{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(51)}}[1]{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
Captura de áudio estéreo{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+ +

[1] O suporte para o evento devicechange e para {{domxref("MediaDevices.ondevicechange")}} começou no Firefox 51, mas somente pra Mac, e desabilitado por padrão. Ele pode ser habilitado configurando a preferência media.ondevicechange.enabled para true. O suporte para esse evendo foi adicionado para Linux e Windows — ativado por padrão — a partir do Firefox 52.

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/mediastreamtrack/index.html b/files/pt-br/web/api/mediastreamtrack/index.html new file mode 100644 index 0000000000..33f62732dc --- /dev/null +++ b/files/pt-br/web/api/mediastreamtrack/index.html @@ -0,0 +1,181 @@ +--- +title: MediaStreamTrack +slug: Web/API/MediaStreamTrack +translation_of: Web/API/MediaStreamTrack +--- +
{{APIRef("Media Capture and Streams")}}
+ +

Resumo

+ +

A interface MediaStream representa uma stream de conteúdo de mídia. Uma stream consiste em várias tracks, como faixas de áudio e vídeo.

+ +

Properties

+ +
+
{{domxref("MediaStreamTrack.enabled")}}
+
Is a Boolean value with a value of true if the track is enabled, that is allowed to render the media source stream; or false if it is disabled, that is not rendering the media source stream but silence and blackness. If the track has been disconnected, this value can be changed but has no more effect.
+
{{domxref("MediaStreamTrack.id")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing a unique identifier (GUID) for the track; it is generated by the browser.
+
{{domxref("MediaStreamTrack.kind")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} set to "audio" if the track is an audio track and to "video", if it is a video track. It doesn't change if the track is deassociated from its source.
+
{{domxref("MediaStreamTrack.label")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing a user agent-assigned label that identifies the track source, as in "internal microphone". The string may be left empty and is empty as long as no source has been connected. When the track is deassociated from its source, the label is not changed.
+
{{domxref("MediaStreamTrack.muted")}} {{readonlyInline}}
+
Returns a Boolean value with a value of true if the track is muted, false otherwise.
+
{{domxref("MediaStreamTrack.readonly")}} {{readonlyInline}}
+
Returns a Boolean value with a value of true if the track is readonly (such a video file source or a camera that settings can't be modified),false otherwise.
+
{{domxref("MediaStreamTrack.readyState")}} {{readonlyInline}}
+
Returns an enumerated value giving the status of the track.It takes one of the following values: +
    +
  • "live" which indicates that an input is connected and does its best-effort in providing real-time data. In that case, the output of data can be switched on or off using the MediaStreamTrack.enabled attribute.
  • +
  • "ended" which indicates that the input is not giving any more data and will never provide new data.
  • +
+
+
{{domxref("MediaStreamTrack.remote")}} {{readonlyInline}}
+
Returns a boolean value with a value of true if the track is sourced by a {{domxref("RTCPeerConnection")}}, false otherwise.
+
+ +

Event handlers

+ +
+
{{domxref("MediaStreamTrack.onstarted")}}
+
Is a {{domxref("EventHandler")}} containing the action to perform when an {{event("started")}} event is fired on the object, that is when a new {{domxref("MediaStreamTrack")}} object is added.
+
{{domxref("MediaStreamTrack.onmute")}}
+
Is a {{domxref("EventHandler")}} containing the action to perform when an {{event("mute")}} event is fired on the object, that is when the streaming is terminating.
+
{{domxref("MediaStreamTrack.onunmute")}}
+
Is a {{domxref("EventHandler")}} containing the action to perform when an {{event("unmute")}} event is fired on the object, that is when a  {{domxref("MediaStreamTrack")}} object is removed from it.
+
{{domxref("MediaStreamTrack.onoverconstrained")}}
+
Is a {{domxref("EventHandler")}} containing the action to perform when an {{event("overconstrained")}} event is fired on the object, that is when a  {{domxref("MediaStreamTrack")}} object is removed from it.
+
{{domxref("MediaStreamTrack.oneended")}}
+
Is a {{domxref("EventHandler")}} containing the action to perform when an {{event("ended_(MediaStream)", "ended")}} event is fired on the object, that is when a  {{domxref("MediaStreamTrack")}} object is removed from it.
+
+ +

Methods

+ +
+
{{domxref("MediaStreamTrack.getConstraints()")}}
+
 
+
{{domxref("MediaStreamTrack.applyConstraints()")}}
+
 
+
{{domxref("MediaStreamTrack.getSettings()")}}
+
 
+
{{domxref("MediaStreamTrack.getCapabilities()")}}
+
 
+
{{domxref("MediaStreamTrack.clone()")}}
+
 
+
{{domxref("MediaStreamTrack.stop()")}}
+
Stops playing the source associated to the track, both the source and the track are deassociated. The track state is set to ended.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#mediastreamtrack', 'MediaStreamTrack')}}{{Spec2('Media Capture')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
stop(){{CompatUnknown}}{{CompatGeckoDesktop(34)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
muted, onmuted, onunmuted, readonly, readyState, remote, onstarted, onended, onoverconstrained, appendConstraint(), applyConstraints(), constraints(), getConstraints(){{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+ + + + + + +
stop()
+
{{CompatUnknown}}{{CompatGeckoDesktop(34)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
muted, onmuted, onunmuted, readonly, readyState, remote, onstarted, onended, onoverconstrained, appendConstraint(), applyConstraints(), constraints(), getConstraints(){{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/messagechannel/index.html b/files/pt-br/web/api/messagechannel/index.html new file mode 100644 index 0000000000..225416121f --- /dev/null +++ b/files/pt-br/web/api/messagechannel/index.html @@ -0,0 +1,152 @@ +--- +title: MessageChannel +slug: Web/API/MessageChannel +translation_of: Web/API/MessageChannel +--- +

{{APIRef("HTML DOM")}}

+ +

A interface MessageChannel da API Channel Messaging nos permite criar um novo canal de mensagem e enviar os dados através de suas duas propriedades {{domxref("MessagePort")}}.

+ +

{{AvailableInWorkers}}

+ +

Propriedades

+ +
+
{{domxref("MessageChannel.port1")}} {{readonlyInline}}
+
Retorna port1 do canal.
+
{{domxref("MessageChannel.port2")}} {{readonlyInline}}
+
Retorna port2 do canal.
+
+ +

Construtor

+ +
+
{{domxref("MessageChannel.MessageChannel", "MessageChannel()")}}
+
+

Retorna um novo objeto MessageChannel com dois novos objetos {{domxref("MessagePort")}}.

+
+
+ +

Exemplo

+ +

No seguinte bloco de codigo, você pode ver um novo canal sendo criado usando o construtor {{domxref("MessageChannel.MessageChannel", "MessageChannel()")}}. Quando o {{HTMLElement("iframe")}} tiver carregado, nos passamos o {{domxref("MessageChannel.port2")}} para o {{HTMLElement("iframe")}} usando {{domxref("MessagePort.postMessage")}} juntamente com uma mensagem. O manipulador handleMessage então reponde à mensagem que foi enviada de volta do {{HTMLElement("iframe")}} (using {{domxref("MessagePort.onmessage")}}), colocando-o em um parágrafo.

+ +
var channel = new MessageChannel();
+var para = document.querySelector('p');
+
+var ifr = document.querySelector('iframe');
+var otherWindow = ifr.contentWindow;
+
+ifr.addEventListener("load", iframeLoaded, false);
+
+function iframeLoaded() {
+  otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
+}
+
+channel.port1.onmessage = handleMessage;
+function handleMessage(e) {
+  para.innerHTML = e.data;
+}   
+ +

Para um exemplo completo, veja nosso  channel messaging basic demo no Github (rode online também ).

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('HTML WHATWG', 'web-messaging.html#message-channels','Message channels')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade entre os navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico4{{CompatVersionUnknown}}{{CompatGeckoDesktop(41)}}10.010.65
Disponivel em workers{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte Básico4.44{{CompatVersionUnknown}}{{CompatGeckoMobile(41)}}{{CompatVersionUnknown}}10.011.55.1
Disponivel em workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/messageport/index.html b/files/pt-br/web/api/messageport/index.html new file mode 100644 index 0000000000..ae82cc0a79 --- /dev/null +++ b/files/pt-br/web/api/messageport/index.html @@ -0,0 +1,117 @@ +--- +title: MessagePort +slug: Web/API/MessagePort +tags: + - API + - Channel messaging + - HTML5 + - Interface + - MessagePort + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/MessagePort +--- +

{{APIRef("HTML DOM")}}

+ +

The MessagePort interface of the Channel Messaging API represents one of the two ports of a {{domxref("MessageChannel")}}, allowing messages to be sent from one port and listening out for them arriving at the other.

+ +

{{AvailableInWorkers}}

+ +

Methods

+ +

Inherits methods from its parent, {{domxref("EventTarget")}}

+ +
+
{{domxref("MessagePort.postMessage","postMessage()")}}
+
Sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.
+
{{domxref("MessagePort.start","start()")}}
+
Starts the sending of messages queued on the port (only needed when using {{domxref("EventTarget.addEventListener")}}; it is implied when using {{domxref("MessagePort.onmessage")}}.)
+
{{domxref("MessagePort.close","close()")}}
+
Disconnects the port, so it is no longer active.
+
+ +

Event handlers

+ +

Inherits event handlers from its parent, {{domxref("EventTarget")}}

+ +
+
{{domxref("MessagePort.onmessage","onmessage")}}
+
An {{domxref("EventListener")}} called when {{domxref("MessageEvent")}} of type message is fired on the port—that is, when the port receives a message.
+
{{domxref("MessagePort.onmessageerror","onmessageerror")}}
+
An {{domxref("EventListener")}} called when a {{domxref("MessageEvent")}} of type {{domxref("MessageError")}} is fired—that is, when it receives a message that cannot be deserialized.
+
+ +

Events

+ +
+
{{domxref("MessagePort.message_event","message")}}
+
Fired when a MessagePort object receives a message.
+ Also available via the {{domxref("MessagePort.onmessage","onmessage")}} property.
+
{{domxref("MessagePort.messageerror_event","messageerror")}}
+
Fired when a MessagePort object receives a message that can't be deserialized.
+ Also available via the {{domxref("MessagePort.onmessageerror","onmessageerror")}} property.
+
+ +

Example

+ +

In the following example, you can see a new channel being created using the {{domxref("MessageChannel.MessageChannel","MessageChannel()")}} constructor.

+ +

When the IFrame has loaded, we register an {{domxref("MessagePort.onmessage","onmessage")}} handler for {{domxref("MessageChannel.port1")}} and transfer {{domxref("MessageChannel.port2")}} to the IFrame using the {{domxref("window.postMessage")}} method along with a message.

+ +

When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph.

+ +
var channel = new MessageChannel();
+var output = document.querySelector('.output');
+var iframe = document.querySelector('iframe');
+
+// Wait for the iframe to load
+iframe.addEventListener("load", onLoad);
+
+function onLoad() {
+  // Listen for messages on port1
+  channel.port1.onmessage = onMessage;
+
+  // Transfer port2 to the iframe
+  iframe.contentWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
+}
+
+
+// Handle messages received on port1
+function onMessage(e) {
+  output.innerHTML = e.data;
+}
+
+ +

For a full working example, see our channel messaging basic demo on Github (run it live too).

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'web-messaging.html#message-ports','Message ports')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/messageport/postmessage/index.html b/files/pt-br/web/api/messageport/postmessage/index.html new file mode 100644 index 0000000000..26e9ffbbc1 --- /dev/null +++ b/files/pt-br/web/api/messageport/postmessage/index.html @@ -0,0 +1,81 @@ +--- +title: MessagePort.postMessage() +slug: Web/API/MessagePort/postMessage +translation_of: Web/API/MessagePort/postMessage +--- +

{{APIRef("HTML DOM")}}

+ +

O método postMessage() da interface {{domxref("MessagePort")}} envia uma mensagem da porta e opcionalmente transfere a propriedade do objeto para outros contexto de navegação.

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
port.postMessage(message, transferList);
+ +

Returns

+ +

Vazio.

+ +

Parameters

+ +
+
message
+
A mensagem que você quer enviar atravéz do canal. Esta mensagem pode ser de qualquer tipo de dados basico. Multiplos items podem ser enviados com diferentestes tipos de dados como em um Array.
+
transferList {{optional_inline}}
+
{{domxref("Transferable")}} objects to be transferred — these objects have their ownership transferred to the receiving browsing context, so are no longer usable by the sending browsing context.
+
+ +

Example

+ +

In the following code block, you can see a new channel being created using the {{domxref("MessageChannel()", "MessageChannel.MessageChannel")}} constructor. When the IFrame has loaded, we pass {{domxref("MessageChannel.port2")}} to the IFrame using {{domxref("window.postMessage")}} along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph — {{domxref("MessageChannel.port1")}} is listened to, to check when the message arrives.

+ +
var channel = new MessageChannel();
+var para = document.querySelector('p');
+
+var ifr = document.querySelector('iframe');
+var otherWindow = ifr.contentWindow;
+
+ifr.addEventListener("load", iframeLoaded, false);
+
+function iframeLoaded() {
+  otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
+}
+
+channel.port1.onmessage = handleMessage;
+function handleMessage(e) {
+  para.innerHTML = e.data;
+}   
+ +

For a full working example, see our channel messaging basic demo on Github (run it live too).

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'web-messaging.html#dom-messageport-postmessage', 'postMessage()')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.MessagePort.postMessage")}}

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/mouseevent/clientx/index.html b/files/pt-br/web/api/mouseevent/clientx/index.html new file mode 100644 index 0000000000..efeb585203 --- /dev/null +++ b/files/pt-br/web/api/mouseevent/clientx/index.html @@ -0,0 +1,149 @@ +--- +title: MouseEvent.clientX +slug: Web/API/MouseEvent/clientX +translation_of: Web/API/MouseEvent/clientX +--- +

{{APIRef("DOM Events")}}

+ +

clientX é uma propriedade somente de leitura da interface {{domxref("MouseEvent")}} que fornece as coordenadas horizontais dentro da área do aplicativo do cliente em que o evento ocorreu (diferente das coordenadas dentro da página). Por exemplo, clicando no canto superior esquerdo da área do cliente sempre irá resultar em um evento de mouse com um valor clientX de 0, independentemente se a página foi rolada horizontalmente. Originalmente, essa propriedade era definida como o número inteiro long. O Módulo de Visualização CSSOM o redefiniu como a fraçãodouble. Veja a seção de compatibilidade do Navegador para detalhes.

+ +

Sintaxe

+ +
var x = instanceOfMouseEvent.clientX
+
+ +

Valor de retorno

+ +

Um número

+ +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <title>clientX/clientY example</title>
+
+    <script>
+      function showCoords(evt){
+        alert(
+          "clientX value: " + evt.clientX + "\n" +
+          "clientY value: " + evt.clientY + "\n"
+        );
+      }
+    </script>
+  </head>
+  <body onmousedown="showCoords(event)">
+    <p>Para mostrar as coordenadas do mouse em qualquer lugar da página.</p>
+  </body>
+</html>
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSSOM View','#dom-mouseevent-clientx', 'clientX')}}{{Spec2('CSSOM View')}}Redefine {{domxref("MouseEvent")}} delong para double
{{SpecName('DOM3 Events','#widl-MouseEvent-clientX','MouseEvent.clientX')}}{{Spec2('DOM3 Events')}}Nenhuma mudança de {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.clientX')}}{{Spec2('DOM2 Events')}}Definição inicial.
+ +

Compatibilidade com Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown()}}6{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
Redefinido de long para double{{CompatChrome(56)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Redefinido de long para double{{CompatChrome(56)}}{{CompatChrome(56)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/mouseevent/clienty/index.html b/files/pt-br/web/api/mouseevent/clienty/index.html new file mode 100644 index 0000000000..6333ab631c --- /dev/null +++ b/files/pt-br/web/api/mouseevent/clienty/index.html @@ -0,0 +1,91 @@ +--- +title: MouseEvent.clientY +slug: Web/API/MouseEvent/clientY +tags: + - API + - CSSOM View + - Eventos de DOM + - Eventos de mouse + - Propriedade + - Somente Leitura +translation_of: Web/API/MouseEvent/clientY +--- +
{{APIRef("DOM Events")}}
+ +

A propriedade clientY  da interface {{domxref("MouseEvent")}} fornece a coordenada vertical do cliente dentro da aplicacão em que o evento ocorreu (ao contrário da coordenada que pertence a página).

+ +

Por exemplo, clicando no topo da área do cliente sempre resultará num evento de mouse com um valor 0 de clientY, independente se a página está "escrollada" verticalmente.

+ +

Sintaxe

+ +
var y = instanciaDeEventoDoMouse.clientY
+
+ +

Valor de retorno

+ +

O valor retornado por essa propriedade é um valor flutuante double como foi redefinida pelo "CSSOM View Module". Originalmente esta propriedade era definida como um inteiro long. Veja a seção de compatibilidade de browsers para mais detalhes.

+ +

Exemplo

+ +

Este exemplo mostra as coordenadas do mouse quando você ativar o evento {{Event("mousemove")}}.

+ +

HTML

+ +
<p>Mova seu mouse para ver sua posicão.</p>
+<p id="screen-log"></p>
+ +

JavaScript

+ +
let screenLog = document.querySelector('#screen-log');
+document.addEventListener('mousemove', logKey);
+
+function logKey(e) {
+  screenLog.innerText = `
+    Screen X/Y: ${e.screenX}, ${e.screenY}
+    Client X/Y: ${e.clientX}, ${e.clientY}`;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Example")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSSOM View','#dom-mouseevent-clienty', 'clientY')}}{{Spec2('CSSOM View')}}Redefine {{domxref("MouseEvent")}} de long para double.
{{SpecName('DOM3 Events','#widl-MouseEvent-clientY','MouseEvent.clientY')}}{{Spec2('DOM3 Events')}}Sem mudanças vindas de {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.clientY')}}{{Spec2('DOM2 Events')}}Definição inicial.
+ +

Compatibilidade de browser

+ + + +

{{Compat("api.MouseEvent.clientY")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/mouseevent/index.html b/files/pt-br/web/api/mouseevent/index.html new file mode 100644 index 0000000000..cce575dec6 --- /dev/null +++ b/files/pt-br/web/api/mouseevent/index.html @@ -0,0 +1,336 @@ +--- +title: MouseEvent +slug: Web/API/MouseEvent +tags: + - API + - DOM + - DOM Events + - Interface + - Precisa de Tradução + - Referencia + - TopicStub +translation_of: Web/API/MouseEvent +--- +

A interface MouseEvent representa eventos que ocorrem devido à interação do usuário com um dispositivo apontador (como um mouse). Eventos comuns usando esta interface incluem click, dblclick, mouseup, mousedown.

+ +

MouseEvent deriva de UIEvent, que por sua vez deriva de Event. Embora o método MouseEvent.initMouseEvent() seja mantido para compatibilidade com versões anteriores, a criação de um objeto MouseEvent deve ser feita usando o construtor MouseEvent().

+ +

Vários eventos mais específicos derivam de MouseEvent como: WheelEvent e DragEvent.
+  

+ +

{{InheritanceDiagram}}

+ +

Construtor

+ +
+
MouseEvent()
+
Cria um objeto MouseEvent.
+
+ +

Propriedades

+ +

Essa interface também herda propriedades de seus pais, UIEvent  e Event.

+ +
+
+

MouseEvent.altKey Read only

+
+
Retorna truese a tecla alt estava pressionada quando o evento do mouse foi disparado.
+
+

MouseEvent.button Read only

+
+
O número do botão que foi pressionado (se aplicável) quando o evento do mouse foi disparado.
+
MouseEvent.buttonsRead only 
+
+

Os botões sendo pressionados (se houver) quando o evento do mouse foi disparado.

+
+
MouseEvent.clientX Read only
+
A coordenada X do ponteiro do mouse em coordenadas locais (conteúdo DOM).
+
MouseEvent.clientYRead only
+
A coordenada Y do ponteiro do mouse em coordenadas locais (conteúdo DOM).
+
MouseEvent.ctrlKey Read only
+
Retorna true se a tecla control estava pressionada quando o evento do mouse foi disparado.
+
MouseEvent.metaKey Read only
+
Retorna true se a tecla meta estava pressionada quando o evento do mouse foi disparado.
+
MouseEvent.movementXRead only
+
A coordenada X do ponteiro do mouse em relação à posição do último evento mousemove .
+
MouseEvent.movementY Read only
+
A coordenada Y do ponteiro do mouse em relação à posição do último  evento mousemove.
+
MouseEvent.offsetX Read only     
+
A coordenada X do ponteiro do mouse em relação à posição da borda de preenchimento do nó de destino.
+
MouseEvent.offsetY Read only   
+
A coordenada Y do ponteiro do mouse em relação à posição da borda de preenchimento do nó de destino.
+
MouseEvent.pageX Read only
+
A coordenada X do ponteiro do mouse em relação a todo o documento.
+
MouseEvent.pageY Read only
+
A coordenada Y do ponteiro do mouse em relação a todo o documento.
+
MouseEvent.region Read only
+
Retorna o id da região afetada pelo evento. Se nenhuma região atingida for afetada, null será retornado.
+
MouseEvent.relatedTarget Read only
+
+

O destino secundário do evento, se houver.

+
+
MouseEvent.screenX Read only
+
A coordenada X do ponteiro do mouse em coordenadas globais (tela).
+
MouseEvent.screenY Read only
+
A coordenada Y do ponteiro do mouse em coordenadas globais (tela).
+
MouseEvent.shiftKey Read only
+
Retorna true se a tecla shift estava pressionada quando o evento do mouse foi disparado.
+
MouseEvent.which Read only
+
O botão sendo pressionado quando o evento do mouse foi disparado.
+
MouseEvent.mozPressure Read only
+
A quantidade de pressão aplicada a um dispositivo de toque ou tablet ao gerar o evento; este valor varia entre 0.0 (pressão mínima) e 1.0 (pressão máxima).
+
MouseEvent.mozInputSource Read only
+
+
+

O tipo de dispositivo que gerou o evento (uma das constantes MOZ_SOURCE_*   listadas abaixo). Isso permite, por exemplo, determinar se um evento de mouse foi gerado por um mouse real ou por um evento de toque (o que pode afetar o grau de precisão com que você interpreta as coordenadas associadas ao evento).

+
+
MouseEvent.webkitForce Read only
+
A quantidade de pressão aplicada ao clicar
+
MouseEvent.xRead only
+
Alias ​​para MouseEvent.clientX.
+
MouseEvent.y Read only
+
Alias ​​para MouseEvent.clientY
+
+ +

Constantes

+ +
+
MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN Read only
+
Força mínima necessária para um clique normal.
+
MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN Read only
+
Força mínima necessária para um clique de força
+
+ +

Método

+ +

Essa interface também herda métodos de seus pais, UIEvent e Event.

+ +
+
MouseEvent.getModifierState()
+
+ +
+
Retorna o estado tual da tecla modificadora especificada. Consulte KeyboardEvent.getModifierState() para obter detalhes.
+
+ +
+
MouseEvent.initMouseEvent()
+
Inicializa o valor de um MouseEvent criado. Se o evento já foi despachado, este método não faz nada.
+
+ +

Exemplo

+ +

Este exemplo demonstra a simulação de um clique (que está gerando programaticamente um evento de clique) em uma caixa de seleção usando métodos DOM.

+ +
function simulateClick() {
+  var evt = new MouseEvent("click", {
+    bubbles: true,
+    cancelable: true,
+    view: window
+  });
+  var cb = document.getElementById("checkbox"); //element to click on
+  var canceled = !cb.dispatchEvent(evt);
+  if(canceled) {
+    // A handler called preventDefault
+    alert("canceled");
+  } else {
+    // None of the handlers called preventDefault
+    alert("not canceled");
+  }
+}
+document.getElementById("button").addEventListener('click', simulateClick);
+ +
<p><label><input type="checkbox" id="checkbox"> Checked</label>
+<p><button id="button">Click me</button>
+ +

Clique no botão para ver como funciona a amostra:

+ +

{{EmbedLiveSample('Example')}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View','#extensions-to-the-mouseevent-interface', 'MouseEvent')}}Rascunho de trabalhoRedefine MouseEvent de longo para duplo. Isto significa que um PointerEvent cuja pointerType é rato será uma de casal.
{{SpecName("HTML WHATWG", "#dom-mouseevent-region", "MouseEvent.region")}}{{Spec2('HTML WHATWG')}}Do Document Object Model (DOM) Nível 3 Events Specification , adicionado propriedades movementX e movementY.
{{SpecName('Pointer Lock','#extensions-to-the-mouseevent-interface','MouseEvent')}}{{Spec2('Pointer Lock')}}
{{SpecName('CSSOM View', '#extensions-to-the-mouseevent-interface', 'MouseEvent')}}{{Spec2('CSSOM View')}}A partir do documento de modelo de objeto (DOM) Nível 3 Especificação de eventos , adicionados offsetX e offsetY, pageX e pageY, x, e y propriedades. Propriedades redefinidas de tela, página, cliente e coordenadas (x e y) a partir double de long.
{{SpecName('DOM3 Events','#events-mouseevents','MouseEvent')}}{{Spec2('DOM3 Events')}}Em Document Object Model (DOM) Nível 2, especificação de eventos, adicionado ao construtor MouseEvent (), o método getModifierState() e a propriedade de buttons.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent')}}{{Spec2('DOM2 Events')}}Definição inicial.
+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
{{domxref("MouseEvent.movementX","movementX")}}
+ {{domxref("MouseEvent.movementY","movementY")}}
{{CompatChrome(37)}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}} {{property_prefix("moz")}}{{ CompatUnknown() }}{{CompatVersionUnknown()}}{{ CompatUnknown() }}
{{ domxref("MouseEvent.buttons", "buttons") }}{{CompatChrome(43)}}{{CompatVersionUnknown()}}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatNo}}
{{ domxref("MouseEvent.which", "which") }}{{CompatChrome(1)}}{{CompatVersionUnknown()}}1.09.05.01.0
{{domxref("MouseEvent.getModifierState()", "getModifierState()")}}{{CompatChrome(47)}}{{CompatVersionUnknown()}}{{CompatGeckoDesktop(15)}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
{{domxref("MouseEvent.mozPressure", "mozPressure")}} and {{domxref("MouseEvent.mozInputSource", "mozInputSource")}} {{non-standard_inline}}{{CompatNo}}{{ CompatUnknown() }}{{CompatGeckoDesktop(2)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("MouseEvent.MouseEvent", "MouseEvent()")}}{{CompatChrome(45)}}{{ CompatUnknown() }}{{CompatGeckoDesktop(11)}}9.0{{CompatVersionUnknown()}}{{ CompatUnknown() }}
{{domxref("MouseEvent.region")}}{{CompatChrome(51)}}[1]{{ CompatUnknown() }}{{CompatGeckoDesktop(32)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
{{domxref("MouseEvent.offsetX")}}, and {{domxref("MouseEvent.offsetY")}}{{CompatVersionUnknown()}}9{{CompatGeckoDesktop(40)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
{{domxref("MouseEvent.screenX")}}, {{domxref("MouseEvent.screenY")}}, {{domxref("MouseEvent.clientX")}}, and {{domxref("MouseEvent.Y")}} are double instead of long.{{CompatChrome(56)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] Requires enabling the ExperimentalCanvasFeatures flag.

+ +

Veja também

+ +

Seu pai direto, UIEvent.
+ PointerEvent: Para eventos de ponteiro avançados, incluindo multitoque

diff --git a/files/pt-br/web/api/mutationobserver/index.html b/files/pt-br/web/api/mutationobserver/index.html new file mode 100644 index 0000000000..2ca0d03404 --- /dev/null +++ b/files/pt-br/web/api/mutationobserver/index.html @@ -0,0 +1,221 @@ +--- +title: MutationObserver +slug: Web/API/MutationObserver +translation_of: Web/API/MutationObserver +--- +

{{APIRef("DOM")}}

+ +

MutationObserver fornece aos desenvolvedores uma maneira de reagir a mudanças em um DOM. Ele é concebido como um substituto para Mutation Events definido na especificação de eventos DOM nível 3.

+ +

Constructor

+ +

MutationObserver()

+ +

Construtor para instanciar novos observadores de mutação do DOM.

+ +
MutationObserver(
+  function callback
+);
+
+ +
Parâmetros
+ +
+
callback
+
A função que será chamada em cada mutação do DOM. O observador irá chamar esta função com dois argumentos. O primeiro é um array de objetos, cada um do tipo MutationRecord. O segundo é a essa instância MutationObserver.
+
+ +

Métodos da instância

+ + + + + + + + + + + + + +
void observe( {{domxref("Node")}} target, MutationObserverInit options );
void disconnect();
Array takeRecords();
+ +

observe()

+ +

Registra a instância MutationObserver para receber notificações das mutações do DOM no nó especificado.

+ +
void observe(
+  {{domxref("Node")}} target,
+  MutationObserverInit options
+);
+
+ +
Parâmetros
+ +
+
target
+
O {{domxref("Node")}} no qual é observadas as mutações do DOM.
+
options
+
Um objeto MutationObserverInit especifica quais mutações DOM devem ser reportadas.
+
+ +
NOTA: Adicionar um observador para um elemento é como utilizar o addEventListener, se você observar o elemento várias vezes não faz diferença. Ou seja, se você observar um elemento duas vezes, o callback do observador não disparará duas vezes, nem você deverá executar duas vezes o disconnect(). Em outras palavras, uma vez que um elemento é observado, observá-lo novamento com a mesma instância do observador não fará nada. No entanto, se o objeto callback for diferente, ele, é claro, adicionará outro observador para isso.
+ +

disconnect()

+ +

Pára o rebimento de notificações das mutações do DOM na instância MutationObserver. O callback do observador não será invocado até que método observe() seja novamente utilizado.

+ +
void disconnect();
+
+ +

takeRecords()

+ +

Esvazia a fila de registro da instância MutationObserver e retorna o que estava nela.

+ +
Array takeRecords();
+
+ +
Valor de retorno
+ +

Retorna um Array de MutationRecords.

+ +

MutationObserverInit

+ +

MutationObserverInit é um objeto que pode especificar as seguintes propriedades:

+ +
NOTA: No mínimo childList, attributes, ou characterData devem ser definidos como true. Caso contrário o erro "An invalid or illegal string was specified" é lançado.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescription
childListDefina como true se adições e remoções dos elementos filho do nó alvo (incluindo nós de texto) devem ser observadas.
attributesDefina como true se mutações dos atributos do alvo devem ser observadas.
characterDataDefina como true se mutações dos dados do alvo devem ser observadas.
subtreeDefina como true se mutações não apenas do alvo, mas também dos descendentes do alvo devem ser observadas.
attributeOldValueDefina como true se attributes é definido como true e o valor do atributo do alvo antes da mutação precisa ser gravado.
characterDataOldValueDefina como true se characterData é definido como true e os dados do alvo antes da mutação precisam ser gravados.
attributeFilterDefina como um array de nomes locais de atributo (sem namespace) se nem todas mutações de atributo precisam ser observadas.
+ +

MutationRecord

+ +

MutationRecord é um objeto que será passado para o callback do observador. Tem as seguintes propriedades:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
typeStringRetorna attributes se a mutação foi a de um atributo, characterData se foi de um nó CharacterData, e childList se foi a mutação para uma árvore de nós.
target{{domxref("Node")}}Retorna o nó que a mutação afetou, dependendo do type. Para attributes é o elemento cujo atributo mudou. Para characterData é o nó CharacterData. Para childList é o nó cujos filhos mudaram.
addedNodes{{domxref("NodeList")}}Retorna os nós adicionados. Será uma NodeList vazia se nenhum nó foi adicionado.
removedNodes{{domxref("NodeList")}}Retorna os nós removidos. Será uma NodeList vazia se nenhum nó foi removido.
previousSibling{{domxref("Node")}}Retorna o irmão anterior dos nós adicionados ou removidos, ou null.
nextSibling{{domxref("Node")}}Retorna o próximo irmão dos nós adicionados ou removidos, ou null.
attributeNameStringRetorna o nome local do atributo modificado, ou null.
attributeNamespaceStringRetorna o namespace do atributo modificado, ou null.
oldValueStringO valor retornado depende do type. Para attributes, é o valor do atributo modificado antes da troca. Para characterData, são os dados do nó modificado antes da troca. Para childList é null.
+ +

Exemplo de uso

+ +

O exemplo a seguir foi retirado deste post.

+ +
// seleciona o nó alvo
+var target = document.querySelector('#some-id');
+
+// cria uma nova instância de observador
+var observer = new MutationObserver(function(mutations) {
+  mutations.forEach(function(mutation) {
+    console.log(mutation.type);
+  });
+});
+
+// configuração do observador:
+var config = { attributes: true, childList: true, characterData: true };
+
+// passar o nó alvo, bem como as opções de observação
+observer.observe(target, config);
+
+// mais tarde você pode parar de observar
+observer.disconnect();
+
+ +

Leitura adicional

+ + + +

Compatibilidade de browser

+ +

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

diff --git a/files/pt-br/web/api/navigation_timing_api/index.html b/files/pt-br/web/api/navigation_timing_api/index.html new file mode 100644 index 0000000000..d40f46ba45 --- /dev/null +++ b/files/pt-br/web/api/navigation_timing_api/index.html @@ -0,0 +1,153 @@ +--- +title: Navigation Timing +slug: Web/API/Navigation_timing_API +tags: + - Web Performance API +translation_of: Web/API/Navigation_timing_API +--- +

A API Navigation Timing fornece dados que podem ser usados para medir a performance de um website. Diferente de outros mecanismos baseados em Javascript que já foram usados para o mesmo propósito, esta API pode fornecer dados sobre a latência do começo ao fim que podem ser mais precisas e relevantes.

+ +

O exemplo a seguir mostra como você pode medir o tempo de carregamento percebido:

+ +
function onLoad() {
+  var now = new Date().getTime();
+  var page_load_time = now - performance.timing.navigationStart;
+  console.log("Tempo de carregamento percebido pelo usuário: " + page_load_time);
+}
+
+ +

Existem muitos eventos medidos em milisegundos que podem ser acessados através da interface {{domxref("PerformanceTiming")}} interface. A lista de eventos na ordem em que ocorrem são:

+ + + +

O objeto window.performance.navigation guarda dois atributos que podem ser usados para saber se o carregamento da página é iniciada por um redirecionamento, pelo botão voltar/avançar ou pela URL mesmo.

+ +

window.performance.navigation.type:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstanteValorDescrição
TYPE_NAVIGATENEXT0Navegação iniciada pelo clique em um link, ou pela entrada da URL na barra de endereços, ou envio de formulário, ou inicializada através da operação de um script diferente que os usados por TYPE_RELOAD e TYPE_BACK_FORWARD como listado abaixo.
TYPE_RELOAD1Navegação através da operação de recarregamento ou pelo método location.reload().
TYPE_BACK_FORWARD2Navegação através de uma operação de histórico.
TYPE_UNDEFINED255Qualquer tipo de navegação não definida pelos valores acima.
+ +

window.performance.navigation.redirectCount indicará, se houver, quantos redirecionamentos aconteceram até que a página final seja alcançada.

+ +

A API Navigation Timing pode ser usada para colher dados da performance do lado do cliente enviado para um servidor via XHR tanto quanto os dados medidos que eram muito dificultosos de medir de outras maneiras como o tempo de "descarga" de uma página anterior, tempo de look up do dominio, tempo total do window.onload total time, etc.

+ +

Exemplos

+ +

Calculando o tempo total necessário para carregar uma página:

+ +
var perfData = window.performance.timing;
+var pageLoadTime = perfData.loadEventEnd - perfData.navigationStart;
+
+ +

Calculando os tempos de resposta da requisição:

+ +
var connectTime = perfData.responseEnd - perfData.requestStart;
+ +

Links

+ + + +

Compatibillidade de Navegadores

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico6.0{{ CompatGeckoDesktop("7") }}915.08
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico4.0{{ CompatGeckoDesktop("15") }}915.08
+
diff --git a/files/pt-br/web/api/navigator/battery/index.html b/files/pt-br/web/api/navigator/battery/index.html new file mode 100644 index 0000000000..5ae9f207f4 --- /dev/null +++ b/files/pt-br/web/api/navigator/battery/index.html @@ -0,0 +1,40 @@ +--- +title: Navigator.battery +slug: Web/API/Navigator/battery +tags: + - API + - Battery API + - Propriedade +translation_of: Web/API/Navigator/battery +--- +

{{ ApiRef("Battery API") }}

+ +

Resumo

+ +

O objeto battery fornece informações sobre o nível de carga da bateria do sistema; você pode também escutar eventos enviados por ele que fornecem atualizações sobre o status atual da carga. Isso implementa a Battery Status API; consulte essa documentação para mais detalhes, um guia de utilização da API e códigos de exemplo.

+ +

Sintaxe

+ +
var battery = window.navigator.battery;
+ +

Valor

+ +

navigator.battery é um objeto do tipo {{domxref("BatteryManager")}}.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigator/cookieenabled/index.html b/files/pt-br/web/api/navigator/cookieenabled/index.html new file mode 100644 index 0000000000..430471cb24 --- /dev/null +++ b/files/pt-br/web/api/navigator/cookieenabled/index.html @@ -0,0 +1,49 @@ +--- +title: Navigator.cookieEnabled +slug: Web/API/Navigator/cookieEnabled +translation_of: Web/API/Navigator/cookieEnabled +--- +

{{ ApiRef("HTML DOM") }}

+ +

navigator.cookieEnabled retorna um valor Booleano que indica quando cookies estão habilitados ou não. A propriedade é de apenas leitura.

+ +

Sintaxe

+ +
var cookieEnabled = navigator.cookieEnabled;
+
+ + + +

Exemplo

+ +
if (!navigator.cookieEnabled) {
+  // The browser does not support or is blocking cookies from being set.
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("HTML WHATWG", "webappapis.html#dom-navigator-cookieenabled", "Navigator.cookieEnabled")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

Compatibilidade entre navegadores

+ + + +

{{Compat("api.Navigator.cookieEnabled")}}

diff --git a/files/pt-br/web/api/navigator/devicememory/index.html b/files/pt-br/web/api/navigator/devicememory/index.html new file mode 100644 index 0000000000..9b4a48aae5 --- /dev/null +++ b/files/pt-br/web/api/navigator/devicememory/index.html @@ -0,0 +1,39 @@ +--- +title: Navigator.deviceMemory +slug: Web/API/Navigator/deviceMemory +translation_of: Web/API/Navigator/deviceMemory +--- +

{{SeeCompatTable}}{{APIRef("Device Memory")}}

+ +

A propriedade de somente-leitura deviceMemory da interface {{domxref("navigator")}} retorna a quantidade de memória do dispositivo em gigabytes. Este valor é uma aproximação por arredondamento da potência mais próxima de 2 e dividindo este número por 1024.

+ +

Sintaxe

+ +
var memory = navigator.deviceMemory
+ +

Valor

+ +

Um número de ponto flutuante.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Device Memory','#sec-device-memory-js-api','deviceMemory')}}{{Spec2('Device Memory')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.Navigator.deviceMemory")}}

diff --git a/files/pt-br/web/api/navigator/geolocation/index.html b/files/pt-br/web/api/navigator/geolocation/index.html new file mode 100644 index 0000000000..12cc9cbfbc --- /dev/null +++ b/files/pt-br/web/api/navigator/geolocation/index.html @@ -0,0 +1,46 @@ +--- +title: Navigator.geolocation +slug: Web/API/Navigator/geolocation +translation_of: Web/API/Navigator/geolocation +--- +
{{APIRef("Geolocation API")}}
+ +

A propriedade de apenas leitura Navigator.geolocation retorna um objeto {{domxref("Geolocation")}} que disponibiliza acesso de conteúdo Web à localização do dispositivo. Isso permite que um Web site ou aplicativo ofereçam resultados customizados baseado na localização do usuário.

+ +
+

Nota: Por questão de segurança, quando uma página web tenta acessar as informações de localização, o usuário é notificado e lhe é perguntado se este garante permissão. Esteja alerta que cada navegador possui suas próprias políticas e métodos para requisitar permissão.

+
+ +

Sintaxe

+ +
geo = navigator.geolocation
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName('Geolocation', '#navi-geo', 'Navigator.geolocation')}}{{Spec2('Geolocation')}}Definição inicial
+ +

Compatibilidade de navegador

+ +

{{Compat("api.Navigator.geolocation")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigator/getusermedia/index.html b/files/pt-br/web/api/navigator/getusermedia/index.html new file mode 100644 index 0000000000..4df2f528d4 --- /dev/null +++ b/files/pt-br/web/api/navigator/getusermedia/index.html @@ -0,0 +1,184 @@ +--- +title: navigator.getUserMedia +slug: Web/API/Navigator/getUserMedia +translation_of: Web/API/Navigator/getUserMedia +--- +

{{APIRef("Media Capture and Streams")}}{{deprecated_header}}

+ +

O método Navigator.getUserMedia() atualmente esta deprecated (obseleto), ele é responsavel por pedir a permissão do usuário para usar até 1 dispositivo de entrada de vídeo (como câmera, ou tela compartilhada) e até 1 dispositivo de entrada de áudio (como o microfone) como fonte para o stream de mídia (pode ser representado por uma instância MediaStream).

+ +

Se o usuário der permissão, a MediaStream (o track do video e/ou audio) , é entregue ao callback de sucesso, se a permissão é negada, pode ser que não haja dispositivo compatível ou alguma condição de erro aconteceu, retornando o callback de erro com uma instancia do objeto   {{domxref("MediaStreamError")}} , com a descrição do erro que aconteceu, se o usuário não fizer nenhuma escolha, nenhum callback é retornado.

+ +

Sintaxe

+ +
navigator.getUserMedia ( permissoes, callbackSucesso, callbackErro );
+ +

Exemplo

+ +

Este é um exemplo de uso da função getUserMedia() com prefixos específicos dos navegadores.

+ +
navigator.getMedia = ( navigator.getUserMedia ||
+                       navigator.webkitGetUserMedia ||
+                       navigator.mozGetUserMedia ||
+                       navigator.msGetUserMedia);
+
+navigator.getMedia (
+
+   // permissoes
+   {
+      video: true,
+      audio: true
+   },
+
+   // callbackSucesso
+   function(localMediaStream) {
+      var video = document.querySelector('video');
+      video.src = window.URL.createObjectURL(localMediaStream);
+      video.onloadedmetadata = function(e) {
+         // Faz algo com o vídeo aqui.
+      };
+   },
+
+   // callbackErro
+   function(err) {
+    console.log("O seguinte erro ocorreu: " + err);
+   }
+
+);
+ +

Parâmetros

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
parâmetroObrigatório/ 
+ Opcional 
Descrição
permissoesObrigatórioOs tipos de mídia habilitados no objeto LocalMediaStream enviado para a callbackSucesso.
callbackSucessoObrigatórioA função da aplicação a ser invocada para receber o objeto LocalMediaStream.
callbackErroOpcionalA função a ser invocada na aplicação se a chamada a getUserMedia falhar.
+ +

permissoes

+ +

O parâmetro permissoes é um objeto MediaStreamConstraints com dois membros do tipo Boolean: video e audio. Estes membros descrevem os tipos de mídia habilitados no objeto LocalMediaStream. Pelo menos um destes membros deve ser especificado para que o argumento seja validado. Se um membro especificado não for suportado pelo navegador, a função getUserMedia invocará a callbackErro com o erro NOT_SUPPORTED_ERROR. Se o navegador não puder encontrar nenhuma fonte de mídia com o tipo especificado, a função getUserMedia invocará a callbackErro com o erro MANDATORY_UNSATISFIED_ERR.

+ +

Se o valor de um membro não estiver especificado no objeto, o valor padrão deste membro será falso. Veja como configurar o objeto permissoes para obter tanto áudio como vídeo:

+ +
{ video: true, audio: true }
+ +

callbackSucesso

+ +

A função getUserMedia invocará a função especificada em callbackSucesso com o objeto LocalMediaStream que contém a fonte de mídia. Você pode associar este objeto com o elemento apropriado e trabalhar com ele, como mostrado no exemplo a seguir:

+ +
function(localMediaStream) {
+   var video = document.querySelector('video');
+   video.src = window.URL.createObjectURL(localMediaStream);
+   video.onloadedmetadata = function(e) {
+      // Faz algo com o vídeo aqui.
+   };
+},
+ +

callbackErro

+ +

A função getUserMedia invocará a função especificada em callbackErro com um argumento code. Os códigos de erro são descritos abaixo:

+ + + + + + + + + + + + + + + + + + + + + + +
ErroDescrição
PERMISSION_DENIED O usuário não permitiu acesso a um dispositivo de mídia necessário para essa operação. 
NOT_SUPPORTED_ERROR Uma mídia especificada não é suportada pelo navegador.
MANDATORY_UNSATISFIED_ERROR Nenhuma fonte de mídia do tipo especificado foi encontrada.
+ +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Stream API 21{{property_prefix("webkit")}} 20{{property_prefix("moz")}} {{CompatNo}} 12{{CompatUnknown}} 
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Stream API {{CompatNo}} {{CompatNo}}{{CompatUnknown}} 12{{CompatNo}} 
+
+ +

Atualmente, usar o WebRTC para acessar a câmera de vídeo é suportado nos navegadores Chrome, Opera e Firefox 20.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigator/index.html b/files/pt-br/web/api/navigator/index.html new file mode 100644 index 0000000000..6ef2055b7a --- /dev/null +++ b/files/pt-br/web/api/navigator/index.html @@ -0,0 +1,119 @@ +--- +title: Navigator +slug: Web/API/Navigator +translation_of: Web/API/Navigator +--- +

{{ apiref() }}

+ +

The Navigator interface represents the state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities.

+ +

A Navigator object can be retrieved using the read-only {{domxref("Window.navigator")}} property.

+ +

Properties

+ +

Doesn't inherit any property, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorLanguage")}}, {{domxref("NavigatorOnLine")}}, {{domxref("NavigatorGeolocation")}}, {{domxref("NavigatorPlugins")}}, {{domxref("NavigatorUserMedia")}}, and {{domxref("NetworkInformation")}}.

+ +

Standard

+ +
+
{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}
+
Returns the internal "code" name of the current browser. Do not rely on this property to return the correct value.
+
{{domxref("NavigatorID.appName")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("DOMString")}} with the official name of the browser. Do not rely on this property to return the correct value.
+
{{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{experimental_inline}}
+
Returns the version of the browser as a {{domxref("DOMString")}}. Do not rely on this property to return the correct value.
+
{{domxref("Navigator.battery")}} {{readonlyInline}}
+
Returns a {{domxref("BatteryManager")}} object you can use to get information about the battery charging status.
+
{{domxref("NetworkInformation.connection")}} {{readonlyInline}}{{experimental_inline}}
+
Provides a {{domxref("Connection")}} with information about the network connection of a device.
+
{{domxref("NavigatorGeolocation.geolocation")}} {{readonlyInline}}
+
Returns a {{domxref("Geolocation")}} object allowing accessing the location of the device.
+
{{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("Boolean")}} flag indicating whether the host browser is Java-enabled or not.
+
{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the preferred language of the user, usually the language of the browser UI. The null value is returned when this is unknown.
+
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
+
Returns an array of {{domxref("DOMString")}} representing the languages known to the user, by order of preference.
+
{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
+
Returns an {{domxref("MimeTypeArray")}} listing the MIME types supported by the browser.
+
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
+
Returns a {{domxref("Boolean")}} indicating whether the browser is working online.
+
{{domxref("Navigator.oscpu")}}
+
Returns a string that represents the current operating system.
+
{{domxref("NavigatorID.platform")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a string representing the platform of the browser. Do not rely on this function to return a significant value.
+
{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser.
+
{{domxref("NavigatorID.product")}} {{readonlyInline}} {{experimental_inline}}
+
Always returns 'Gecko', on any browser. This property is kept only for compatibility purpose.
+
{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
+
Returns the user agent string for the current browser.
+
{{domxref("Navigator.serviceWorker")}} {{readonlyInline}}
+
Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document.
+
+ +

Non-standard

+ +
+
{{domxref("window.navigator.buildID", "navigator.buildID")}} {{non-standard_inline}}
+
Returns the build identifier of the browser (e.g., "2006090803").
+
{{domxref("Navigator.cookieEnabled")}} {{non-standard_inline}}
+
Returns a boolean indicating whether cookies are enabled in the browser or not.
+
{{domxref("navigator.doNotTrack")}} {{non-standard_inline}}
+
Reports the value of the user's do-not-track preference. When this value is "yes", your web site or application should not track the user.
+
{{domxref("navigator.id")}} {{non-standard_inline}}
+
Returns the {{domxref("window.navigator.id", "id")}} object which you can use to add support for BrowserID to your web site.
+
{{domxref("window.navigator.mozApps", "navigator.mozApps")}} {{non-standard_inline}}
+
Returns an {{domxref("window.navigator.mozApps", "Apps")}} object you can use to install, manage, and control Open Web apps.
+
{{domxref("Navigator.mozAudioChannelManager", "navigator.mozAudioChannelManager")}} {{non-standard_inline}}
+
The navigator.mozAudioChannelManager object provides access to the {{domxref("mozAudioChannelManager")}} interface, which is used to manage your Firefox OS device's audio channels, including setting what channel's volume to affect when the volume buttons are pressed inside a particular app.
+
{{domxref("window.navigator.mozNotification","navigator.mozNotification")}} {{deprecated_inline("22")}} {{non-standard_inline}}
+ {{domxref("window.navigator.webkitNotification","navigator.webkitNotification")}}
+
Returns a {{domxref("navigator.mozNotification", "notification")}} object you can use to deliver notifications to the user from your web application.
+
{{domxref("navigator.mozSocial")}} {{non-standard_inline}}
+
The Object, returned by the navigator.mozSocial property, is available within the social media provider's panel to provide functionality it may need.
+
{{domxref("window.navigator.productSub", "navigator.productSub")}} {{non-standard_inline}}
+
Returns the build number of the current browser (e.g., "20060909").
+
{{domxref("window.navigator.securitypolicy", "navigator.securitypolicy")}} {{non-standard_inline}}
+
Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".
+
{{domxref("window.navigator.standalone", "navigator.standalone")}} {{non-standard_inline}}
+
Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.
+
{{domxref("window.navigator.vendor", "navigator.vendor")}} {{non-standard_inline}}
+
Returns the vendor name of the current browser (e.g., "Netscape6").
+
{{domxref("window.navigator.vendorSub", "navigator.vendorSub")}} {{non-standard_inline}}
+
Returns the vendor version number (e.g. "6.1").
+
navigator.webkitPointer {{non-standard_inline}}
+
Returns a PointerLock object for the Mouse Lock API.
+
+ +

Methods

+ +

Doesn't inherit any method, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorUserMedia")}}, and {{domxref("NavigatorStorageUtils")}}.

+ +

Standard

+ +
+
{{domxref("NavigatorUserMedia.getUserMedia()")}}
+
After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.
+
{{domxref("window.navigator.registerContentHandler", "navigator.registerContentHandler")}}
+
Allows web sites to register themselves as a possible handler for a given MIME type.
+
{{domxref("navigator.registerProtocolHandler", "navigator.registerProtocolHandler")}}
+
Allows web sites to register themselves as a possible handler for a given protocol.
+
{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline("1.7.8")}} {{obsolete_inline("9.0")}} {{experimental_inline}}
+
Returns false. JavaScript taint/untaint functions removed in JavaScript 1.2.
+
{{domxref("Navigator.vibrate()")}} {{gecko_minversion_inline("11.0")}}
+
Causes vibration on devices with support for it. Does nothing if vibration support isn't available.
+
+ +

Non standard

+ +
+
{{domxref("window.navigator.mozIsLocallyAvailable", "navigator.mozIsLocallyAvailable")}} {{non-standard_inline}}
+
Lets code check to see if the document at a given URI is available without using the network.
+
{{domxref("window.navigator.mozPay", "navigator.mozPay")}} {{non-standard_inline}}
+
Allows in-app payment.
+
{{domxref("window.navigator.preference", "navigator.preference")}} {{obsolete_inline("2.0")}} {{non-standard_inline}}
+
Sets a user preference. This method is only available to privileged code and is obsolete; you should use the XPCOM Preferences API instead.
+
{{domxref("window.navigator.requestWakeLock", "navigator.requestWakeLock")}} {{non-standard_inline}}
+
Request a wake lock for a resource. A wake lock prevents a specific part of a device from being turned off automatically.
+
diff --git a/files/pt-br/web/api/navigator/share/index.html b/files/pt-br/web/api/navigator/share/index.html new file mode 100644 index 0000000000..ce6640ada2 --- /dev/null +++ b/files/pt-br/web/api/navigator/share/index.html @@ -0,0 +1,87 @@ +--- +title: Navigator.share() +slug: Web/API/Navigator/share +translation_of: Web/API/Navigator/share +--- +
{{APIRef("HTML DOM")}}{{securecontext_header}}
+ +

O método navigator.share() da API de compartilhamento da Web chama o mecanismo de compartilhamento nativo do dispositivo.

+ +

Sintaxe

+ +
var sharePromise = navigator.share(data);
+
+ +

Parâmetros

+ +
+
data
+
Um objeto que contém dados para compartilhar. Pelo menos um dos seguintes campos deve ser especificado. As opções disponíveis são:
+
+ + + +
+
+ +

Valor de retorno

+ +

Um {{domxref ("Promise")}} que será cumprido assim que um usuário concluir uma ação de compartilhamento (geralmente o usuário escolheu um aplicativo para compartilhar). Ele rejeitará imediatamente se o parâmetro de dados não estiver especificado corretamente e também rejeitará se o usuário cancelar o compartilhamento.

+ +

Exemplos

+ +

Em nosso teste de compartilhamento na Web (consulte o código-fonte), há um botão que, quando clicado, invoca a API de compartilhamento na Web para compartilhar o URL da MDN. O JavaScript fica assim:

+ +
const shareData = {
+  title: 'MDN',
+  text: 'Aprenda desenvolvimento web no MDN!',
+  url: 'https://developer.mozilla.org',
+}
+
+const btn = document.querySelector('button');
+const resultPara = document.querySelector('.result');
+
+// Deve ser acionado algum tipo de "ativação do usuário"
+btn.addEventListener('click', async () => {
+  try {
+    await navigator.share(shareData)
+  } catch(err) {
+    resultPara.textContent = 'Error: ' + e
+  }
+  resultPara.textContent = 'MDN compartilhado com sucesso!'
+});
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('Web Share API','#share-method','share()')}}{{Spec2('Web Share API')}}
+ +

Compatibilidade do navegador

+ + + +

{{Compat("api.Navigator.share")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigatorid/index.html b/files/pt-br/web/api/navigatorid/index.html new file mode 100644 index 0000000000..c56f1e1b81 --- /dev/null +++ b/files/pt-br/web/api/navigatorid/index.html @@ -0,0 +1,120 @@ +--- +title: NavigatorID +slug: Web/API/NavigatorID +translation_of: Web/API/NavigatorID +--- +

{{APIRef("HTML DOM")}}

+ +

The NavigatorID interface contains methods and properties related to the identity of the browser.

+ +

There is no object of type NavigatorID, but other interfaces, like {{domxref("Navigator")}} or {{domxref("WorkerNavigator")}}, implement it.

+ +

Properties

+ +

The NavigatorID interface doesn't inherit any property.

+ +
+
{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{deprecated_inline}}
+
Always returns 'Mozilla', on any browser. This property is kept only for compatibility purpose.
+
{{domxref("NavigatorID.appName")}} {{readonlyInline}} {{deprecated_inline}}
+
Returns the official name of the browser. Do not rely on this property to return the correct value.
+
{{domxref("NavigatorID.appVersion")}} {{readonlyInline}} {{deprecated_inline}}
+
Returns the version of the browser as a string. Do not rely on this property to return the correct value.
+
{{domxref("NavigatorID.platform")}} {{readonlyInline}} {{deprecated_inline}}
+
Returns a string representing the platform of the browser. Do not rely on this property to return the correct value.
+
{{domxref("NavigatorID.product")}} {{readonlyInline}} {{deprecated_inline}}
+
Always returns 'Gecko', on any browser. This property is kept only for compatibility purpose.
+
{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
+
Returns the user agent string for the current browser.
+
+ +

Methods

+ +

The NavigatorID interface doesn't inherit any method.

+ +
+
{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline()}}
+
Always returns false. JavaScript taint/untaint functions were removed in JavaScript 1.2. This method is only kept for compatibility purpose
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatorid', 'NavigatorID')}}{{Spec2('HTML WHATWG')}}Added the appCodeName property and the taintEnabled() method,  for compatibility purpose.
{{SpecName('HTML5 W3C', '#navigatorid', 'NavigatorID')}}{{Spec2('HTML5 W3C')}}Initial specification.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/navigatorid/platform/index.html b/files/pt-br/web/api/navigatorid/platform/index.html new file mode 100644 index 0000000000..590d9bd515 --- /dev/null +++ b/files/pt-br/web/api/navigatorid/platform/index.html @@ -0,0 +1,63 @@ +--- +title: NavigatorID.platform +slug: Web/API/NavigatorID/platform +tags: + - API + - DOM + - DOM_0 + - Gecko + - HTML5 + - Propriedade + - Referencia + - Referência(2) +translation_of: Web/API/NavigatorID/platform +--- +

{{ ApiRef("HTML DOM") }}

+ +

Retorna uma string representando a plataforma do navegador. A especificação permite aos navegadores retornar sempre strings vazias, portanto não se utilize dessa propriedade para obter resultados confiáveis.

+ +

Sintaxe

+ +
plataforma = navigator.platform
+
+ +

Valor

+ +

Uma {{domxref("DOMString")}} identificando a plataforma na qual o navegador está sendo executado, ou uma string vazia se o browser se negar a (ou for incapaz de) identificar a plataforma. plataforma é uma string que pode estar vazia ou representar a plataforma na qual o navegador está sendo executado.

+ +

Por exemplo: "MacIntel", "Win32", "FreeBSD i386", "WebTV OS"

+ +

Exemplo

+ +
console.log(navigator.platform);
+ +

Notas

+ +

Na maioria dos browsers, incluindo Chrome, Edge e Firefox 63 em diante, NavegatorID.platform retorna "Win32", mesmo que o browser seja executado em uma versão 64-bit do Windows. No Internet Explorer e em versões do Firefox anteriores à versão 63, a propriedade ainda retorna "Win64".

+ +

No Firefox, a preferência general.platform.override pode ser usada para sobrepor o valor de retorno padrão dessa propriedade.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-navigator-platform', 'NavigatorID.platform')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ +

Compatibilidade

+ + + +

{{Compat("api.NavigatorID.platform")}}

diff --git a/files/pt-br/web/api/navigatorid/useragent/index.html b/files/pt-br/web/api/navigatorid/useragent/index.html new file mode 100644 index 0000000000..c5e6211724 --- /dev/null +++ b/files/pt-br/web/api/navigatorid/useragent/index.html @@ -0,0 +1,89 @@ +--- +title: NavigatorID.userAgent +slug: Web/API/NavigatorID/userAgent +tags: + - API + - Descontinuado + - Propriedade + - Referencia + - Somente Leitura +translation_of: Web/API/NavigatorID/userAgent +--- +

{{ApiRef("HTML DOM")}}

+ +

A propriedade read-only (apenas leitura) NavigatorID.userAgent retorna a string do agente do usuário (user agent) para o browser atual.

+ +
+

 A especifícação demanda que os navegadores forneçam, nessa propriedade, a menor quantidade de informações posssível. Nunca assuma que o valor dessa propriedade permanecerá o mesmo em verções futuras de um mesmo navegador. Tente não utiliza-la, ou ultileze-a somente para verções presentes ou passadas de um navegador. Novos navegadores podem utilizar-se do mesmo agente do usuário, ou parte dele, que navegadores mais aintigos: não existe qualquer garantia de que o agente do navegador é de fato o enunciado por essa propriedade.
+
+ Além disso, tenha em mente que os usuários do navegador podem manipular o valor dessa propriedade caso queiram (UA spoofing).

+
+ +

A idenficação de browsers baseada na detecção de sua string de agente de usuário não é confiável e não é recomendável, pois a string de agente de usuário pode ser configurada pelo usuário. Por exemplo:

+ + + +

Sintaxe

+ +
var au = window.navigator.userAgent;
+
+ +

Valor

+ +

au guarda o valor da string de agente de usuário do browser atual.

+ +

A string de agente de usuário é contruida em uma estrutura formal que pode ser decomposta em diferentes informações. Cada uma dessas informações é provinda de outras propriedades de window.navigator, que também podem ser configuradas pelo usuário. Navegadores baseados na engine Gecko seguem a seguinte estrutura:

+ +
ageteDeUsuário = códigoDoNomeDoAplicativo/versãoDoAplicativo número (Plataforma; Segurança; OS-ou-CPU;
+Localização; rv: número-da-verção-de-revisão) produto/produtoSub
+Nome-do-Aplicativo versão-do-Nome-do-Aplicativo
+
+ +

Examplo

+ +
alert(window.navigator.userAgent)
+// alerta "Mozilla/5.0 (Windows; U; Win98; en-US; rv:0.9.2) Gecko/20010725 Netscape6/6.1"
+
+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-navigator-useragent', 'NavigatorID.userAgent')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ +

Compatibilidade

+ + + +

{{Compat("api.NavigatorID.userAgent")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigatorlanguage/index.html b/files/pt-br/web/api/navigatorlanguage/index.html new file mode 100644 index 0000000000..7d6b0751e7 --- /dev/null +++ b/files/pt-br/web/api/navigatorlanguage/index.html @@ -0,0 +1,148 @@ +--- +title: NavigatorLanguage +slug: Web/API/NavigatorLanguage +tags: + - API + - HTML-DOM + - NeedsTranslation + - No Interface + - Reference + - TopicStub +translation_of: Web/API/NavigatorLanguage +--- +

{{APIRef("HTML DOM")}}

+ +

NavigatorLanguage contains methods and properties related to the language of the navigator.

+ +

There is no object of type NavigatorLanguage, but other interfaces, like {{domxref("Navigator")}} or {{domxref("WorkerNavigator")}}, implement it.

+ +

Properties

+ +

The NavigatorLanguage interface doesn't inherit any property.

+ +
+
{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the preferred language of the user, usually the language of the browser UI. The null value is returned when this is unknown.
+
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
+
Returns an array of {{domxref("DOMString")}} representing the languages known to the user, by order of preference.
+
+ +

Methods

+ +

The NavigatorLanguage interface neither implements, nor inherit any method.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatorlanguage', 'NavigatorLanguage')}}{{Spec2('HTML WHATWG')}}Since the {{SpecName('HTML5 W3C')}} snapshot, the languages property has been added.
{{SpecName('HTML5 W3C', '#navigatorlanguage', 'NavigatorLanguage')}}{{Spec2('HTML5 W3C')}}Initial specification; snapshot of  an early version{{SpecName('HTML WHATWG')}}.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
languages37{{CompatGeckoDesktop("32")}}{{CompatNo}}24{{CompatNo}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatGeckoDesktop("35")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
languages{{CompatUnknown}}{{CompatUnknown}} {{CompatGeckoMobile("32")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("35")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/navigatorlanguage/language/index.html b/files/pt-br/web/api/navigatorlanguage/language/index.html new file mode 100644 index 0000000000..c29fe80ac0 --- /dev/null +++ b/files/pt-br/web/api/navigatorlanguage/language/index.html @@ -0,0 +1,131 @@ +--- +title: NavigatorLanguage.language +slug: Web/API/NavigatorLanguage/language +translation_of: Web/API/NavigatorLanguage/language +--- +
{{APIRef("HTML DOM")}}
+ +

A propriedade NavigatorLanguage.language retorna uma string representando a língua de preferência do usuário, normalmente a língua da interface do navegador.

+ +

Sintaxe

+ +
var lang = navigator.language
+
+ +

Valor

+ +

Uma {{domxref("DOMString")}} lang armazena a string representando a língua como definida em BCP 47. Exemplos de códigos de línguas válidos incluem "en", "en-US", "fr", "fr-FR", "es-ES", etc.

+ +

Atente-se que no Safari no macOS e iOS antes da versão 10.2, o código do país é retornado em caixa baixa: "en-us", "fr-fr" etc.

+ +

Exemplo

+ +
if (window.navigator.language != 'en') {
+  doLangSelect(window.navigator.language);
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComentários
{{ SpecName('HTML5.1', '#dom-navigator-language', 'NavigatorLanguage.language') }}{{ Spec2('HTML5.1') }}Definição inicial
+ +

Compatibilidade com navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}[2]
+ {{CompatGeckoDesktop("5.0")}}[3]
11.0[4]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("35")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatNo}}[4]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("35")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Retorna a língua da interface do browser, não o valor do HTTP header Accept-Language .

+ +

[2] Antes do Gecko 2.0 {{geckoRelease("2.0")}}, o valor dessa propriedade também fazia parte da string de user agent, como reportado em {{domxref("window.navigator.userAgent", "navigator.userAgent")}}.

+ +

[3] Começando no Gecko 5.0 {{geckoRelease("5.0")}}, o valor dessa propriedade é baseado no valor do HTTP header Accept-Language.

+ +

[4] As propriedades (não padronizadas) mais próximas disponíveis são userLanguage e browserLanguage.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigatoronline/index.html b/files/pt-br/web/api/navigatoronline/index.html new file mode 100644 index 0000000000..6e5118c62b --- /dev/null +++ b/files/pt-br/web/api/navigatoronline/index.html @@ -0,0 +1,134 @@ +--- +title: NavigatorOnLine +slug: Web/API/NavigatorOnLine +tags: + - API + - HTML-DOM +translation_of: Web/API/NavigatorOnLine +--- +

{{APIRef("HTML DOM")}}

+ +

A interface NavigatorOnLine contém métodos e propriedades relacionados ao status de conectividade do navegador.

+ +

Não há objetosdo tipo NavigatorOnLine, mas há outras interfaces, como {{domxref("Navigator")}} ou {{domxref("WorkerNavigator")}} que o implementa.

+ +

Propriedades

+ +

A interface NavigatorOnLine não herda nenhuma propriedade.

+ +

 

+ +
+
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
+
Retorna um {{domxref("Boolean")}} indicando se o browser está online.
+
+ +

Métodos

+ +

A interface NavigatorOnLine não implementa nem herda nenhum método.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#navigatoronline', 'NavigatorOnLine')}}{{Spec2('HTML WHATWG')}}Nenhuma mudança desde a ultima atualização, do {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', '#navigatoronline', 'NavigatorOnLine')}}{{Spec2('HTML5 W3C')}}Snapshot do {{SpecName('HTML WHATWG')}} com sua especificação inicial
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatGeckoMobile(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigatoronline/online/index.html b/files/pt-br/web/api/navigatoronline/online/index.html new file mode 100644 index 0000000000..acaed23e82 --- /dev/null +++ b/files/pt-br/web/api/navigatoronline/online/index.html @@ -0,0 +1,91 @@ +--- +title: Navigator.onLine +slug: Web/API/NavigatorOnLine/onLine +tags: + - API + - DOM Reference + - NavigatorOnLine + - Offline + - Online + - Propriedade + - Referencia +translation_of: Web/API/NavigatorOnLine/onLine +--- +
{{ApiRef("HTML DOM")}}
+ +

Retorna o estado da conexão do navegador. A propriedade retorna um valor booleano, com true significando online e false significando offline. A propriedade envia atualizações assim que a capacidade do navegador de se conectar a rede muda. A atualização ocorre quando o usuário entra em um link ou quando algum script faz uma requisição a uma página remota. Exemplo, a propriedade deve retornar false quando usuários clicam em links assim que perderem suas conexões com a internet.

+ +

Navegadores implementam esta propriedade de formas diferentes.

+ +

No Chrome e Safari, caso o navegador não for capaz de se conectar a uma rede local (LAN) ou a um roteador, ele está offline; em todas as outras condições, retorna true. Utilizar essa propriedade para determinar que o navegador está offline seja sempre que o navegador retornar false como valor pode gerar falsos positivos, em casos em que o computador está executando um software de virtualização que tem adaptadores de ethernet virtuais que sempre estão "conectados." ou quando o computador estiver conectado ao roteador e este estiver sem internet. Se você realmente quer determinar o estado da conexão do navegador, você deve desenvolver meios adicionais para esta verificação. Para aprender mais, veja o artigo do HTML5 Rocks, Working Off the Grid.

+ +

No Firefox e Internet Explorer, mudar o navegador para o modo offline envia um valor false. Até o Firefox 41, todas as outras condições retornam um valor true; desde o Firefox 41, no OS X e Windows, o valor seguirá a conectividade real da rede.

+ +

Você pode ver mudanças no estado da rede escutando os eventos window.ononline e window.onoffline.

+ +

Sintaxe

+ +
online = window.navigator.onLine;
+
+ +

Valor

+ +

online é um booleano true ou false.

+ +

Exemplo

+ +

Veja  um exemplo ao-vivo.

+ +

Para verificar se você está online, chame window.navigator.onLine, como no exemplo abaixo:

+ +
if (navigator.onLine) {
+  console.log('online');
+} else {
+  console.log('offline');
+}
+ +

Caso o navegador não suporta o exemplo de navigator.onLine acima, ele sempre retornará false/undefined.

+ +

Para ver mudanças no estado da rede, use addEventListener para escutar os eventos em window.online e window.offline, como no exemplo abaixo:

+ +
window.addEventListener('offline', function(e) { console.log('offline'); });
+
+window.addEventListener('online', function(e) { console.log('online'); });
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName("HTML WHATWG", "browsers.html#dom-navigator-online", "navigator.onLine")}}{{Spec2("HTML WHATWG")}}Definição inicial
+ +

Compatibilidade com os navegadores

+ + + +

{{Compat("api.NavigatorOnLine.onLine")}}

+ +

Notas

+ +

Veja s eventos Online/Offline para descrições mais detalhadas desta propriedade assim como novas funcionalidades offline introduzidas no Firefox 3.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigatoronline/online_and_offline_events/index.html b/files/pt-br/web/api/navigatoronline/online_and_offline_events/index.html new file mode 100644 index 0000000000..e12a1fc649 --- /dev/null +++ b/files/pt-br/web/api/navigatoronline/online_and_offline_events/index.html @@ -0,0 +1,99 @@ +--- +title: Eventos on-line e off-line +slug: Web/API/NavigatorOnLine/Online_and_offline_events +translation_of: Web/API/NavigatorOnLine/Online_and_offline_events +--- +

IAlguns navegadores utilizam Online/Offline events relacionados à WHATWG Web Applications 1.0 specification.

+ +

Introdução

+ +

Para criar um bom aplicativo off-line, primeiramente é necessário que você saiba quando o aplicativo está off-line. Consequentemente, você também precisará saber quando seu aplicativo retorna ao estado on-line novamente, ou seja, os eventos são:

+ +
    +
  1. Você precisa saber quando o usuário está on-line novamente, assim você pode sincronizar novamente com o servidor.
  2. +
  3. Você precisa saber quando o usuário está off-line, então você deverá agendar os acessos ao servidor para mais tarde.
  4. +
+ +

Este é o processo que os eventos on-line/off-line ajudam a facilitar.

+ +

Seu aplicativo também poderá precisar estabelecer que certos documentos deverão ser mantidos em um cache off-line. Você pode saber mais sobre isso no artigo Offline resources in Firefox.

+ +

API

+ + + +

navigator.onLine é uma propriedade que mantém valores true/false (true para on-line, false para off-line). Esta propriedade é atualizada quando o usuário entra em "Modo Off-line" clicando no item de menu correspondente (Arquivo -> Modo Off-line).

+ +

Essa propriedade também deverá ser atualizada toda vez que o navegador perde a conexão com a Internet. De acordo com a especificação:

+ +
A propriedade navigator.onLine deve retornar false se o usuário clicar num link ou se um aplicativo tentar contatar uma página remota e não estiver conectado à Internet ou se o navegador souber que a tentativa irá falhar por qualquer motivo...
+ +

O Firefox 2 atualiza esta propriedade quando se entra em Modo Off-line ou sai do mesmo e também quando a conexão com a Internet é perdida ou reestabelecida no Windows e no Linux.

+ +

Essa propriedade existiu em versões mais antigas do Firefox e do Internet Explorer (a especificação acima foi baseada nestas implementações anteriores), então você pode começar a utilizá-la imediatamente. A auto-detecção de estado de rede foi implementada no Firefox 2.

+ +

Eventos "on-line" e "off-line"

+ +

O Firefox 3 implementou dois novos eventos: "on-line" e "off-line". Estes dois eventos são chamados na tag <body> de cada página quando o navegador muda entre os modos on e off-line. Também, esses eventos são propagados a partir do document.body, para document, terminando em window. Ambos eventos não podem ser interrompidos (você não pode prevenir que o usuário fique on-line ou off-line).

+ +

Você pode resgistrar listeners para esses eventos em caminhos conhecidos:

+ + + +

Example

+ +

a simple test case que você pode rodar para ver como esses eventos funcionam. XXX Quando os testes para isso forem criados, redirecione para eles e atualize 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>
+
+ +

Notas

+ +

Se a API não estiver implementada no navegador, você pode usar outros sinais para detectar quando se está off-line, inclusive receber AppCache error events e responses from XMLHttpRequest.

+ +

Referências

+ + + +

{{ HTML5ArticleTOC() }}

+ +

{{ languages( { "es": "es/Eventos_online_y_offline", "fr": "fr/\u00c9v\u00e8nements_online_et_offline", "ja": "ja/Online_and_offline_events", "pl": "pl/Zdarzenia_online_i_offline", "pt": "pt/Eventos_online_e_offline" } ) }}

diff --git a/files/pt-br/web/api/navigatorplugins/index.html b/files/pt-br/web/api/navigatorplugins/index.html new file mode 100644 index 0000000000..ddcc629eb8 --- /dev/null +++ b/files/pt-br/web/api/navigatorplugins/index.html @@ -0,0 +1,69 @@ +--- +title: NavigatorPlugins +slug: Web/API/NavigatorPlugins +tags: + - API + - DOM + - Experimental + - HTML + - Interface + - Navigation + - NavigatorPlugins + - Plugins + - Reference +translation_of: Web/API/NavigatorPlugins +--- +

{{APIRef("HTML DOM")}}{{SeeCompatTable}}

+ +

O NavigatorPlugins {{Glossary("mixin")}} adiciona na interface do {{domxref ("Navigator")}} métodos e propriedades para descobrir e interagir com plugins instalados no navegador.

+ +

 

+ +

Propriedades

+ +
+
{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
+
Retorna um {{domxref ("MimeTypeArray")}} listando os tipos MIME suportados pelo navegador.
+
{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}
+
Retorna um {{domxref ("PluginArray")}} listando os plugins instalados no navegador.
+
+ +

Métodos

+ +

A interface NavigatorPlugins NavigatorPlugins não herda nenhum método.

+ +
+
{{domxref("NavigatorPlugins.javaEnabled", "NavigatorPlugins.javaEnabled()")}} {{readonlyInline}}{{experimental_inline}}
+
Retorna uma flag {{domxref ("Boolean")}} indicando se o navegador do host tem o Java ativo ou não.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', '#navigatorplugins', 'NavigatorPlugins')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ + + + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigatorplugins/javaenabled/index.html b/files/pt-br/web/api/navigatorplugins/javaenabled/index.html new file mode 100644 index 0000000000..29aba43a52 --- /dev/null +++ b/files/pt-br/web/api/navigatorplugins/javaenabled/index.html @@ -0,0 +1,54 @@ +--- +title: NavigatorPlugins.javaEnabled() +slug: Web/API/NavigatorPlugins/javaEnabled +tags: + - API + - Example + - Method + - Reference +translation_of: Web/API/NavigatorPlugins/javaEnabled +--- +

{{ APIRef("HTML DOM") }}

+ +

Este método indica se o navegador atual tem o Java ativo ou não.

+ +

Sintaxe

+ +
result = window.navigator.javaEnabled()
+
+ +

Exemplo

+ +
if (window.navigator.javaEnabled()) {
+   // browser has java
+}
+
+ +

Notas

+ +

O valor de retorno para este método indica se a preferência que controla o Java está ativado ou desativado - não se o navegador oferece suporte ao Java, em geral.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EsécificaçõesEstadoComentário
{{SpecName('HTML WHATWG', '#dom-navigator-javaenabled', 'NavigatorPlugins.javaEnabled')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ + + + + +

{{Compat("api.NavigatorPlugins.javaEnabled")}}

diff --git a/files/pt-br/web/api/node/appendchild/index.html b/files/pt-br/web/api/node/appendchild/index.html new file mode 100644 index 0000000000..dbca22a3f2 --- /dev/null +++ b/files/pt-br/web/api/node/appendchild/index.html @@ -0,0 +1,56 @@ +--- +title: Node.appendChild +slug: Web/API/Node/appendChild +translation_of: Web/API/Node/appendChild +--- +
{{ApiRef("DOM")}}
+ +

Resumo

+ +

Adiciona um nó ao final da lista de filhos de um nó pai especificado. Se o nó já existir no documento, ele é removido de seu nó pai atual antes de ser adicionado ao novo pai.

+ +

Sintaxe

+ +
var filho = elemento.appendChild(filho);
+ + + +

Descrição

+ +

O método appendChild devolve uma referência ao nó adicionado.

+ +

Exemplo

+ +
// Cria um novo elemento de parágrafo e adiciona-o ao final do documento
+var p = document.createElement("p");
+document.body.appendChild(p);
+ +

Notas

+ +

Se filho é uma referência a um nó existente no documento, appendChild vai movê-lo de sua posição atual para a nova posição (i.e, não é necessário remover o nó de seu pai atual antes de adicioná-lo a outro nó).

+ +

Isso também significa que um nó não pode estar em dois lugares do documento ao mesmo tempo. Assim, se o nó já tem um pai, ele é primeiro removido para, só então, ser adicionado na nova posição.

+ +

Você pode usar o método {{domxref("Node.cloneNode")}} para criar uma cópia do nó antes de adicioná-lo ao novo pai. (Note que cópias feitas com o método cloneNode não serão mantidas sincronizadas automaticamente)

+ +

Este método não permite mover nós entre documentos diferentes. Se você quiser adicionar um nó de um documento diferente (por exemplo para mostrar o resultado de uma requisição AJAX), você precisa primeiro usar o método {{domxref("document.importNode")}}.

+ +

appendChild() é um dos métodos fundamentais da programação para a web usando o DOM. O método appendChild() insere um novo nó na estrutura do DOM de um documento, e é a segunda parte do processo criar-e-adicionar tão importante na construção de páginas web programaticamente.

+ +

Especificação

+ + + +

Ver também

+ + diff --git a/files/pt-br/web/api/node/baseuri/index.html b/files/pt-br/web/api/node/baseuri/index.html new file mode 100644 index 0000000000..fe376eac67 --- /dev/null +++ b/files/pt-br/web/api/node/baseuri/index.html @@ -0,0 +1,82 @@ +--- +title: Node.baseURI +slug: Web/API/Node/baseURI +translation_of: Web/API/Node/baseURI +--- +
+
{{APIRef("DOM")}}
+ +

Resumo

+
+ +

A propriedade somente leitura Node.baseURI retorna a URL base absoluta de um nó.

+ +

A URL base é usada para resolver URLs relativas quando o navegador precisa obter uma URL absoluta, por exemplo, quando processa o atributo src do elemento HTML  {{HTMLElement("img")}} ou o atributo xlink:href do XML.

+ +

No caso comum, a URL base é simplesmente a localização do documento, mas ela pode ser afetada por vários fatores, incluindo o elemento {{HTMLElement("base")}} em HTML e o atributo xml:base em XML.

+ +

Sintaxe

+ +
var baseURI = node.baseURI;
+
+ + + +

Detalhes

+ +

A URL base de um documento

+ +

É a URL base de um documento padrão ao endereço do documento ( como exibido pelo navegador e disponível em {{domxref("window.location")}} ), mas pode mudar o padrão:

+ + + +

Veja a seção URLs base do padrão HTML para mais detalhes.

+ +

Você pode usar {{domxref("document")}}.baseURI  para obter a URL base de um documento. Note que a obtenção da URL base para um documento pode retornar diferentes URLs ao longo do tempo se as tags {{HTMLElement("base")}} ou a localização do documento mudarem.

+ +

A URL base de um elemento

+ +

A URL base de um elemento em HTML é, normalmente,  igual  a URL base do documento onde o nó está.

+ +

Se o documento contém atributos xml:base ( que você não deve fazer em documento HTML), o element.baseURI recebe os atributos xml:base dos elementos pai into account when computing the base URL. Veja xml:base para mais detalhes.

+ +

Você pode usar {{domxref("element")}}.baseURI para obter a URL base de um elemento.

+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName( "DOM WHATWG", "#dom-node-baseuri", "baseURI" ) }}{{ Spec2( "DOM WHATWG" ) }} 
{{ SpecName( "DOM3 Core", "core.html#Node3-baseURI", "baseURI" ) }}{{ Spec2( "DOM3 Core" ) }}Introduzida
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/node/childnodes/index.html b/files/pt-br/web/api/node/childnodes/index.html new file mode 100644 index 0000000000..f89acb5d8c --- /dev/null +++ b/files/pt-br/web/api/node/childnodes/index.html @@ -0,0 +1,66 @@ +--- +title: Node.childNodes +slug: Web/API/Node/childNodes +translation_of: Web/API/Node/childNodes +--- +
+
{{ApiRef("DOM")}}
+
+ +

A propriedade somente leitura Node.childNodes retorna uma coleção viva de nós filhos de um dado elemento.

+ +

Sintaxe

+ +
var listaNos = noReferencia.childNodes;
+
+ +

listaNos é uma coleção ordenada de objetos node que são filhos do elemento corrente. Se o elemento não tem filhos, então listaNos não contém nenhum nó.

+ +

A listaNos é uma variável que armazena a lista de nós de childNodes. O tipo dessa lista é {{domxref("NodeList")}}.

+ +

Exemplo

+ +
// parg é uma referência de objeto a um elemento <p>
+
+if (parg.hasChildNodes()) {
+  // Primeiramente verificamos se o objeto não está vazio, se o objeto tem nós filhos
+  var filhos= parg.childNodes;
+
+  for (var i = 0; i < filhos.length; i++) {
+    // fazer algo com cada filho em filhos[i]
+    // NOTE: A lista é viva - adicionar ou remover filhos altera a lista
+  }
+}
+ +
+
// Esta é uma forma para remover todos os filhos de um nó
+// box é uma referência de objeto para um elemento com filhos
+
+while (box.firstChild) {
+    // A lista é VIVA, então ela re-indexará a cada chamada
+    box.removeChild(box.firstChild);
+}
+ +

Notas

+ +

Os itens na coleção de nós são objetos, não strings. Para recuperar dados dos objetos dos nós, você deve usar suas propriedades (e.g.,  noReferencia.childNodes[1].nodeName para recuperar o nome, etc.).

+ +

O objeto document tem 2 filhos: a declaração Doctype declaration e o elemento raiz, tipicamente referido como documentElement. (Em documentos (X)HTML este é o elemento HTML)

+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/node/clonenode/index.html b/files/pt-br/web/api/node/clonenode/index.html new file mode 100644 index 0000000000..fd62b8099d --- /dev/null +++ b/files/pt-br/web/api/node/clonenode/index.html @@ -0,0 +1,175 @@ +--- +title: Node.cloneNode() +slug: Web/API/Node/cloneNode +tags: + - API + - DOM + - Precisa de compatibilidade entre Browsers + - Referencia + - Referência DOM + - metodo +translation_of: Web/API/Node/cloneNode +--- +
{{APIRef("DOM")}}
+ +

O método Node.cloneNode() duplica um elemento node (nó) da estrutura de um documento DOM. Ele retorna um clone do elemento para o qual foi invocado.

+ +

Syntax

+ +
var dupNode = node.cloneNode(deep);
+
+ +
+
node
+
O elemento node (nó) a ser clonado 'duplicado'.
+
dupNode
+
O novo elemento node (nó) resultado da clonagem do elemento node.
+
deep {{optional_inline}} [1]
+
true se os elementos filhos do nó que está sendo clonado devem ser clonados juntos, ou false para clonar apenas o nó específico dispensando, assim, qualquer elemento DOM filho. Veja os exemplos abaixo.
+
+ +
+

Nota: Na especificação do DOM4 (implementado no Gecko 13.0 {{geckoRelease(13)}}), o argumento deep é opcional. Se omitido, por padrão, o método age como se o valor de deep fosse setado como true durante a sua execução.   Para criação de clones superficiais, o argumento deep deve ser setado como false.

+ +

Este comportamento foi alterado na última especificação. Se omitido o argumento deep, o método irá interpretar o valor de deep como se fosse false. Embora ele continue opcional, é recomendado que você sempre observe o argumento deep para fins de compatibilidade anterior e posterior. Com o Gecko 28.0 {{geckoRelease(28)}}), foi advertido aos desenvolvedores para não omitirem o argumento. Iniciado com o Gecko 29.0 {{geckoRelease(29)}}), um clone superficial é o padrão ao invés de um clone aprofundado.

+
+ +

Exemplo

+ +
<div id="paragrafos">
+    <p>Texto parágrafo</p>
+</div>
+
+//Obtém o elemento div
+var div_p = document.getElementById("paragrafos");
+
+//Obtém o primeiro filho do elemento div
+var p = div_p.firstChild;
+
+//Clona o elemento, no caso, um parágrafo
+var p_clone = p.cloneNode(true);
+
+//Adiciona o clone do elemento <p> ao elemento <div>
+div_p.appendChild(p_clone);
+
+
+ +

Notas

+ +

A clonagem de um elemento node copia todos os seus atributos e valores. Porém, não tem o mesmo comportamento em relação aos "event listeners".

+ +

O elmento node resultante da ação de clonagem não faz parte da estruturam DOM do documento até que ele seja adicionado utilizando o método appendChild() ou outro similar, conforme exemplo acima.

+ +

Se o argumento (deep) for setado como false, os nós filhos do elemento node clonado não serão clonados juntos, assim como os respectivos textos.

+ +

Se o argumento (deep) for setado como true, os nós filhos, toda a árvore DOM do elemento clonado, será clonada junto.

+ +
Cuidado: cloneNode() pode duplicar IDs em um documento.
+ +

Se o elemento node (nó) clonado tiver uma ID e o novo elemento node resultante da clonagem for ser inserido no mesmo documento, a ID de um dos nós deve ser alterada para que observem o princípio de unicidade. Em outras palavras, um mesmo documento não pode ter elementos com IDs iguais. Se for o caso de trabalhar com manipulação de elementos DOM através do atributo "name", tome cuidado em observá-lo.

+ +

Clonagem de node (nó)  para um documento diferente, use o seguinte método: {{domxref("Document.importNode()")}}.

+ +

Specificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaçãoStatusComentários
{{SpecName("DOM WHATWG", "#dom-node-clonenode", "Node.cloneNode()")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM3 Core", "core.html#ID-3A0ED0A4", "Node.cloneNode()")}}{{Spec2("DOM3 Core")}} 
{{SpecName("DOM2 Core", "core.html#ID-3A0ED0A4", "Node.cloneNode()")}}{{Spec2("DOM2 Core")}}Definição Inicial
+ +

Compatibilidade de Browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
(deep) como parâmetro opcional +

{{CompatVersionUnknown}}[1]

+
{{CompatGeckoDesktop("13.0")}}{{CompatVersionUnknown}}{{CompatUnknown}} +

{{CompatVersionUnknown}}[1]

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
(deep) como parâmetro opcional{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("13.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Valor padrão para o argumento (deep) é false.

diff --git a/files/pt-br/web/api/node/contains/index.html b/files/pt-br/web/api/node/contains/index.html new file mode 100644 index 0000000000..e468ac6bd3 --- /dev/null +++ b/files/pt-br/web/api/node/contains/index.html @@ -0,0 +1,98 @@ +--- +title: Node.contains +slug: Web/API/Node/contains +translation_of: Web/API/Node/contains +--- +
+
{{ApiRef("DOM")}}
+
+ +

Sumário

+ +

Indica se um nó é um descendente de um dado nó.

+ +

Sintaxe

+ +
node.contains( otherNode )
+
+ + + +

O valor de retorno é true se otherNode é um descendente de um nó ou o próprio nó. Caso contrário o valor de retorno é false.

+ +

Exemplo

+ +

Esta função verifica se um elemento está no corpo da página. As contains is inclusive and determining if the body contains itself isn't the intention of isInPage this case explicitly returns false.

+ +
function isInPage(node) {
+  return (node === document.body) ? false : document.body.contains(node);
+}
+ + + +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}5.0{{CompatVersionUnknown}}5.2.2 [1][2]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Especificação

+ + + +

Ver também

+ + diff --git "a/files/pt-br/web/api/node/entendendo_o_uso_do_m\303\251todo_appendchild-javascript/index.html" "b/files/pt-br/web/api/node/entendendo_o_uso_do_m\303\251todo_appendchild-javascript/index.html" new file mode 100644 index 0000000000..a05abeae88 --- /dev/null +++ "b/files/pt-br/web/api/node/entendendo_o_uso_do_m\303\251todo_appendchild-javascript/index.html" @@ -0,0 +1,55 @@ +--- +title: Entendendo o uso do método appendChild em javascript +slug: Web/API/Node/Entendendo_o_uso_do_método_AppendChild-javascript +--- +
{{ApiRef("DOM")}}
+ +

Resumo

+ +

Adiciona um nó ao final da lista de filhos de um nó pai especificado. Se o nó já existir no documento, ele é removido de seu nó pai atual antes de ser adicionado ao novo pai.

+ +

Sintaxe

+ +
var filho = elemento.appendChild(filho);
+ + + +

Descrição

+ +

O método appendChild devolve uma referência ao nó adicionado.

+ +

Exemplo

+ +
// Cria um novo elemento de parágrafo e adiciona-o ao final do documento
+var p = document.createElement("p");
+document.body.appendChild(p);
+ +

Notas

+ +

Se filho é uma referência a um nó existente no documento, appendChild vai movê-lo de sua posição atual para a nova posição (i.e, não é necessário remover o nó de seu pai atual antes de adicioná-lo a outro nó).

+ +

Isso também significa que um nó não pode estar em dois lugares do documento ao mesmo tempo. Assim, se o nó já tem um pai, ele é primeiro removido para, só então, ser adicionado na nova posição.

+ +

Você pode usar o método {{domxref("Node.cloneNode")}} para criar uma cópia do nó antes de adicioná-lo ao novo pai. (Note que cópias feitas com o método cloneNode não serão mantidas sincronizadas automaticamente)

+ +

Este método não permite mover nós entre documentos diferentes. Se você quiser adicionar um nó de um documento diferente (por exemplo para mostrar o resultado de uma requisição AJAX), você precisa primeiro usar o método {{domxref("document.importNode")}}.

+ +

appendChild() é um dos métodos fundamentais da programação para a web usando o DOM. O método appendChild() insere um novo nó na estrutura do DOM de um documento, e é a segunda parte do processo criar-e-adicionar tão importante na construção de páginas web programaticamente.

+ +

Especificação

+ + + +

Ver também

+ + diff --git a/files/pt-br/web/api/node/firstchild/index.html b/files/pt-br/web/api/node/firstchild/index.html new file mode 100644 index 0000000000..ab177549a8 --- /dev/null +++ b/files/pt-br/web/api/node/firstchild/index.html @@ -0,0 +1,66 @@ +--- +title: Node.firstChild +slug: Web/API/Node/firstChild +tags: + - API + - DOM + - Node + - Node.firstChild +translation_of: Web/API/Node/firstChild +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.firstChild é uma propriedade do tipo somente leitura que retorna o node (nó) do primeiro elemento filho de uma árvore DOM ou null no caso do elemento não ter filhos (children). 

+ +

Syntax

+ +
var childNode = node.firstChild;
+
+ +

node: elemento node (nó pai) de referência para busca do seu primeiro filho (firstChild) considerada a estrutura DOM.

+ +

childNode: elemento node (nó filho) considerado como primeiro filho (firstChild) de node (pai).

+ +

Descrição

+ +

childNode é uma referência para o primeiro filho (node) de uma estrutura DOM, um node (nó) que não tem filhos retornará null.

+ +

Exemplo

+ +

Este exemplo demonstra o uso do firstChild e como os espaços em branco "whitespace" de um node (nó) podem interferir. 

+ +
<p id="para-01">
+  <span>First span</span>
+</p>
+
+<script type="text/javascript">
+  var p01 = document.getElementById('para-01');
+  console.log(p01.firstChild.nodeName);
+</script>
+ +

No exemplo acima, o console.log() deverá exibir '#text' porque o nó de texto inserido mantém espaços em branco 'whitespace' entre a tag <p id="para-01"> e a tag <span>. Qualquer espaço em branco poderá causar '#text'.

+ +
+

"Tabs" também podem causar esse comportamento.

+
+ +

Se os espaços em branco for removidos do código, o '#text' não será mais considerado e a tag <span> se tornará o primeiro filho firstChild do parágrafo, conforme exemplo abaixo.

+ +
<p id="para-01"><span>First span</span></p>
+
+<script type="text/javascript">
+  var p01 = document.getElementById('para-01');
+  console.log(p01.firstChild.nodeName)
+</script>
+
+ +

Agora o console.log() irá exibir 'SPAN'.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/node/index.html b/files/pt-br/web/api/node/index.html new file mode 100644 index 0000000000..8b265cdbd5 --- /dev/null +++ b/files/pt-br/web/api/node/index.html @@ -0,0 +1,303 @@ +--- +title: Node +slug: Web/API/Node +translation_of: Web/API/Node +--- +
{{Apiref("DOM")}}
+ +

Node é uma interface da qual diversos tipos do DOM herdam, e que permite que esses tipos sejam tratados de forma similar, por exemplo, herdando os mesmos métodos ou sendo testados da mesma forma.
+
+ Todos os tipos a seguir herdam essa interface e seus métodos e propriedades (apesar de que alguns podem devolver null em casos particulares em que o método ou a propriedade não são relevantes; ou lançar uma exceção quando adicionando um filho a um tipo de nó que não pode ter filhos): {{domxref("Document")}}, {{domxref("Element")}}, {{domxref("Attr")}}, {{domxref("CharacterData")}} (do qual {{domxref("Text")}}, {{domxref("Comment")}}, e {{domxref("CDATASection")}} herdam), {{domxref("ProcessingInstruction")}}, {{domxref("DocumentFragment")}}, {{domxref("DocumentType")}}, {{domxref("Notation")}}, {{domxref("Entity")}}, {{domxref("EntityReference")}}

+ +

{{InheritanceDiagram}}

+ +

 

+ +

Propriedades

+ +

Herda propriedades de seus pais, {{domxref("EventTarget")}}.[1]

+ +
+
{{domxref("Node.baseURI")}} {{readonlyInline}}
+
Retorna uma {{domxref("DOMString")}} representando o URL base do nó. O conceito de URL base muda de uma linguagem para outra; no HTML, ela corresponde ao protocolo, ao nome de domínio e a estrutura de diretório; tudo isso até a última '/'.
+
{{domxref("Node.baseURIObject")}} {{Non-standard_inline()}} {{ Fx_minversion_inline("3") }}
+
Retorna um objeto {{ Interface("nsIURI") }}, representando o URL base do nó. (Indisponível para conteúdo Web)
+
{{domxref("Node.childNodes")}} {{readonlyInline}}
+
Retorna um objeto {{domxref("NodeList")}} "vivo" contendo todos os filhos deste nó. Dizer que um objeto {{domxref("NodeList")}} é vivo significa que se houver alguma mudança em um dos filhos deste nó, o objeto {{domxref("NodeList")}} é automaticamente atualizado com tais mudanças.
+
{{domxref("Node.firstChild")}} {{readonlyInline}}
+
Retorna um {{domxref("Node")}} representando o primeiro filho direto do nó ou null, caso o nó não tenha nenhum filho.
+
{{domxref("Node.lastChild")}} {{readonlyInline}}
+
Retorna um {{domxref("Node")}} representando o último filho direto do elemento ou null, caso o elemento não tenha nenhum filho.
+
{{domxref("Node.nextSibling")}} {{readonlyInline}}
+
Retorna um {{domxref("Node")}} representando o próximo elemento na árvore ou null, caso tal nó não exista.
+
{{domxref("Node.nodeName")}} {{readonlyInline}}
+
Retorna uma {{domxref("DOMString")}} contendo o nome do elemento, do Node. A estrutura do nome irá mudar conforme o tipo do elemento. Veja as diferenças na documentação do método {{domxref("Node.nodeName")}}.  
+
{{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}{{ Fx_minversion_inline("3") }}
+
Uma interface {{ Interface("nsIPrincipal") }} representando o nó principal.
+
{{domxref("Node.nodeType")}}{{readonlyInline}}
+
Retorna um unsigned short representando o tipo do nodo. Valores possíveis são:
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NomeValor
ELEMENT_NODE1
ATTRIBUTE_NODE2
TEXT_NODE3
CDATA_SECTION_NODE4
ENTITY_REFERENCE_NODE5
ENTITY_NODE6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE12
+ +
+
{{domxref("Node.nodeValue")}}
+
Retorna / Define o valor do nó atual
+
{{domxref("Node.ownerDocument")}} {{readonlyInline}}
+
Retorna o {{domxref("Document")}} qual esse nó pertence. Se o nó em si é um documento, retorna null.
+
{{domxref("Node.parentNode")}} {{readonlyInline}}
+
Retorna um {{domxref("Node")}} que é pai desse nó. Se não existe tal nó, como, por exemplo, se esse nó é o topo da árvore ou se ele não participa de uma árvore, essa propriedade retorna null.
+
{{domxref("Node.previousSibling")}} {{readonlyInline}}
+
Retorna um {{domxref("Node")}} representando o último nó em uma árvore ou null se não existe tal nodo.
+
{{domxref("Node.textContent")}}
+
Retorna / Define o conteúdo textual de um elemento e de todos os seus descendentes.
+
+  
+
+ +

Propriedades descontinuadas

+ +
+
{{domxref("Node.rootNode")}} {{readOnlyInline}} {{deprecated_inline}}
+
Retorna um objeto {{domxref("Node")}} representando o nó mais alto em uma árvore, ou o nó atual, se ele for o mais alto da árvore. Isso foi substituído por {{domxref("Node.getRootNode()")}}.
+
+

Propriedades obsoletas

+
+
{{domxref("Node.localName")}} {{obsolete_inline}}{{readonlyInline}}
+
Retorna um {{domxref("DOMString")}} representando a parte local do nome qualificado de um elemento. +
+

Nota: No Firefox 3.5 e nas versões anteriores, a propriedade coloca em caixa alta o nome local de elementos HTML (mas não elementos XHTML). Em versões posteriores, isso não acontece, então a propriedade está em caixa baixa para ambos HTML e XHTML. {{gecko_minversion_inline("1.9.2")}}

+
+
+
{{domxref("Node.namespaceURI")}} {{obsolete_inline}}{{readonlyInline}}
+
O espaço de nomes URI desse nó, ou null se não estiver no espaço de nomes. +
+

Nota: No Firefox 3.5 e nas versões anteriores, elementos HTML estão no espaço de nomes. Em versões posteriores, elementos HTML estão em http://www.w3.org/1999/xhtml/, nas árvores HTML e XML. {{gecko_minversion_inline("1.9.2")}}

+
+
+
{{domxref("Node.prefix")}} {{obsolete_inline}}{{readonlyInline}}
+
É um {{domxref("DOMString")}} representando o espaço de nomes do nó, ou null se nenhum prefixo é especificado.
+
+ +

Métodos

+ +

 

+ + + +

 

+ +

Constantes

+ +

Veja também {{domxref("Node.nodeType")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NomeValor
ELEMENT_NODE1
ATTRIBUTE_NODE2
TEXT_NODE3
DATA_SECTION_NODE4
ENTITY_REFERENCE_NODE5
ENTITY_NODE6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE12
DOCUMENT_POSITION_DISCONNECTED0x01
DOCUMENT_POSITION_PRECEDING0x02
DOCUMENT_POSITION_FOLLOWING0x04
DOCUMENT_POSITION_CONTAINS0x08
DOCUMENT_POSITION_CONTAINED_BY0x10
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC0x20
+ +

Exemplos de código

+ +

Recuperar todos os nós filhos

+ +

A função a seguir percorre todos os nós filhos de um nó recursivamente e executa uma função de callback em cada um deles (e no nó pai também).

+ +
function DOMComb (oParent, oCallback) {
+  if (oParent.hasChildNodes()) {
+    for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) {
+      DOMComb(oNode, oCallback);
+    }
+  }
+  oCallback.call(oParent);
+}
+ +

Sintaxe

+ +
DOMComb(parentNode, callbackFunction);
+ +

Descrição

+ +

Percorre todos os nós filhos de parentNode recursivamente e o próprio parentNode e executa a callbackFunction em cada um deles como this.

+ +

Parâmetros

+ +
+
parentNode
+
O nó pai (Object do tipo Node).
+
callbackFunction
+
A função de callback (Function).
+
+ +

Exemplo de uso

+ +

O exemplo a seguir envia para a função console.log o conteúdo textual do body:

+ +
function imprimeConteudo () {
+  if (this.nodeValue) { console.log(this.nodeValue); }
+}
+
+onload = function () {
+  DOMComb(document.body, imprimeConteudo);
+};
+ +

Especificações

+ + diff --git a/files/pt-br/web/api/node/innertext/index.html b/files/pt-br/web/api/node/innertext/index.html new file mode 100644 index 0000000000..1ab5e81027 --- /dev/null +++ b/files/pt-br/web/api/node/innertext/index.html @@ -0,0 +1,86 @@ +--- +title: Node.innerText +slug: Web/API/Node/innerText +translation_of: Web/API/HTMLElement/innerText +--- +
{{APIRef("DOM")}}
+ +

Resumo

+ +

Node.innerText é uma propriedade que representa o conteúdo textual "renderizado" de um nó e seus descendentes. Usada como getter, retorna de maneira aproximada o texto que o usuário obteria caso tivesse selecionado o conteúdo e copiado para a área de transferência. Este recurso fora introduzido originalmente pelo Internet Explorer, mas foi oficialmente especificado no padrão HTML apenas em 2016, sendo adotado por todos os principais navegadores a partir de então.

+ +

{{domxref("Node.textContent")}} é uma alternativa similar, embora existam diferenças significativas entre as duas.

+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'dom.html#the-innertext-idl-attribute', 'innerText')}}{{Spec2('HTML WHATWG')}}Introduzida, baseado no rascunho da especifição de innerText. Ver whatwg/html#465 e whatwg/compat#5 para histórico.
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico4{{ CompatGeckoDesktop(45) }}69.6 (provavelmente antes)3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico2.3 (provavelmente antes){{ CompatGeckoMobile(45) }}10 (provavelmente antes)124.1 (provavelmente antes)
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/node/insertbefore/index.html b/files/pt-br/web/api/node/insertbefore/index.html new file mode 100644 index 0000000000..d556885be7 --- /dev/null +++ b/files/pt-br/web/api/node/insertbefore/index.html @@ -0,0 +1,152 @@ +--- +title: Node.insertBefore +slug: Web/API/Node/insertBefore +translation_of: Web/API/Node/insertBefore +--- +
+
{{ApiRef("DOM")}}
+
+ +

O método Node.insertBefore() insere um nó antes do nó de referência como um filho de um nó pai especificado. Se o filho especificado for uma referência a um nó existente no documento, insertBefore() o moverá de sua posição atual para a nova posição (não há necessidade de remover o nó de seu nó pai antes de anexá-lo a outro nó).

+ +

Isso significa que um nó não pode estar em dois pontos do documento simultaneamente. Portanto, se o nó já tiver um pai, o nó será removido pela primeira vez e inserido na nova posição. O {{domxref("Node.cloneNode()")}} pode ser usado para fazer uma cópia do nó antes de anexá-lo ao novo pai. Note que as cópias feitas com cloneNode() não serão automaticamente mantidas em sincronia.

+ +

 

+ +

Se o nó de referência for null, o nó especificado será incluído no final da lista de filhos do nó pai especificado.

+ +

Se o filho especificado for um {{domxref("DocumentFragment")}}, todo o conteúdo do DocumentFragment será movido para a lista de filhos do nó pai especificado.

+ +

 

+ +

Sintaxe

+ +
var elementoInserido = elementoPai.insertBefore(novoElemento, elementoDeReferencia);
+
+ +

 

+ + + +

 

+ +

Se elementoDeReferencia for null, novoElemento será inserido no fim da lista de nós filhos.

+ +
+

elementoDeReferencia não é um parâmetro opcional - você deve passar explicitamente um Node ou null. Deixar de fornecer ou passar valores inválidos pode ter comportamento diferente em diferentes versões de navegadores.

+
+ +

 

+ +

Return value

+ +

O valor retornado é o filho incluído, exceto quando newNode é um {{domxref("DocumentFragment")}}, caso em que o {{domxref("DocumentFragment")}} vazio é retornado.

+ +

 

+ +

Exemplo

+ +
<div id="elementoPai">
+  <span id="elementoFilho">foo bar</span>
+</div>
+
+<script>
+// Cria um novo elemento <span> vazio
+var sp1 = document.createElement("span");
+
+// Guarda a referência do elemento atraś do qual nos queremos inserir o novo elemento
+var sp2 = document.getElementById("elementoFilho");
+// Guarda a referência do elemento pai
+var divPai = sp2.parentNode;
+
+// Insere o novo elemento no DOM antes de sp2
+divPai.insertBefore(sp1, sp2);
+</script>
+
+ +

Não existe um método insertAfter. Mas ele pode ser emulado combinando o método insertBefore com nextSibling.

+ +

No exemplo anterior, sp1 poderia ser inserido após sp2 desta forma:

+ +
divPai.insertBefore(sp1, sp2.nextSibling);
+ +

Se sp2 não possuir um próximo nó, significa que ele deve ser o último filho — sp2.nextSibling retorna null, e sp1 é inserido ao fim da  da lista de nós filhos (logo após sp2).

+ +

Exemplo 2

+ +

Inserir um elemento antes do primeiro nó filho, usando a propriedade firstChild.

+ +
// Guarda a referêncis do elemento no quela nóe queremos inserir o novo nó
+var elementoPai = document.getElementById('elementoPai');
+// Guarda a referência do primeiro filho
+var primeiroFilho = elementoPai.firstChild;
+
+// Cria um novo elemento
+var novoElemento = document.createElement("div");
+
+// Insere o novo elemento antes do primeiro filho
+elementoPai.insertBefore(novoElemento, primeiroFilho);
+
+ +

Quando o elemento não possui o primeiro filho, então firstChild é null. O elemento ainda será inserido no pai, mas após o último filho. Pois se o elemento pai não possui primeiro filho, ele também não possui o último filho. Conseqüentemente, o novo elemento será o único elemento após a inserção.

+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/node/isconnected/index.html b/files/pt-br/web/api/node/isconnected/index.html new file mode 100644 index 0000000000..52aee94508 --- /dev/null +++ b/files/pt-br/web/api/node/isconnected/index.html @@ -0,0 +1,118 @@ +--- +title: Node.isConnected +slug: Web/API/Node/isConnected +translation_of: Web/API/Node/isConnected +--- +
{{APIRef("DOM")}}
+ +

A propriedade somente-leitura isConnected da interface {{domxref("Node")}} retorna um boleano indicando se um nó está conectado (direta ou indiretamente) ao contexto do objeto, por exemplo o objeto {{domxref("Document")}} no caso da DOM normal, ou o {{domxref("ShadowRoot")}} no caso de uma shadow DOM.

+ +

Sintaxe

+ +
var isItConnected = nodeObjectInstance.isConnected
+ +

Retorno

+ +

Um {{domxref("Boolean")}} que é true se o nó está conectado ao contexto relevante do objeto, e false se não está.

+ +

Examples

+ +

Standard DOM

+ +

Um exemplo em um DOM padrão:

+ +
let test = document.createElement('p');
+console.log(test.isConnected); // Returns false
+document.body.appendChild(test);
+console.log(test.isConnected); // Returns true
+
+ +

Shadow DOM

+ +

Um exemplo em um Shadow DOM:

+ +
// Cria um raíz Shadow
+var shadow = this.attachShadow({mode: 'open'});
+
+// Cria um CSS para aplicar a Shadow DOm
+var style = document.createElement('style');
+console.log(style.isConnected); // retorna false
+
+style.textContent = `
+.wrapper {
+  position: relative;
+}
+
+.info {
+  font-size: 0.8rem;
+  width: 200px;
+  display: inline-block;
+  border: 1px solid black;
+  padding: 10px;
+  background: white;
+  border-radius: 10px;
+  opacity: 0;
+  transition: 0.6s all;
+  positions: absolute;
+  bottom: 20px;
+  left: 10px;
+  z-index: 3
+}
+`;
+
+// Anexa a estilização criada a Shadow DOM.
+
+shadow.appendChild(style);
+console.log(style.isConnected); // retorna true
+ +

Polyfill

+ +

Node.isConnected pode ser polyfilled com o seguinte código para IE10 e EdgeHTML:

+ +
/*
+ * Node.isConnected polyfill para IE and EdgeHTML
+ * 2020-02-04
+ *
+ * Por Eli Grey, https://eligrey.com
+ * Domínio Público.
+ * NENHUMA GARANTIA É EXPRESSADA OU IMPLÍCITA. USE AO SEU PRÓPRIO RISCO.
+ */
+
+if (!('isConnected' in Node.prototype)) {
+  Object.defineProperty(Node.prototype, 'isConnected', {
+    get() {
+      return (
+        !this.ownerDocument ||
+        !(
+          this.ownerDocument.compareDocumentPosition(this) &
+          this.DOCUMENT_POSITION_DISCONNECTED
+        )
+      );
+    },
+  });
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('DOM WHATWG','#dom-node-isconnected','isConnected')}}{{Spec2('DOM WHATWG')}}Definição Inicial.
+ +

Compatibilidade de Browser

+ +
+ + +

{{Compat("api.Node.isConnected")}}

+
diff --git a/files/pt-br/web/api/node/lastchild/index.html b/files/pt-br/web/api/node/lastchild/index.html new file mode 100644 index 0000000000..3bfccdafb0 --- /dev/null +++ b/files/pt-br/web/api/node/lastchild/index.html @@ -0,0 +1,34 @@ +--- +title: Node.lastChild +slug: Web/API/Node/lastChild +tags: + - API + - DOM + - Elements + - lastChild +translation_of: Web/API/Node/lastChild +--- +
{{APIRef("DOM")}}
+ +

Node.lastChild é uma propriedade do tipo somente leitura (read-only) que retorna o último elemento filho (node) de uma estrutura DOM. Se seu parentNode for um Element, ele retornará um Element node, um text node, ou um comment node. Retornará null se o elemento de referência não tiver elementos filhos child. É extremamente recomendável que você conheça a estrutura DOM para um melhor aprendizado e entendimento.

+ +

Syntax

+ +
var last_child = element.lastChild
+
+ +

Exemplo

+ +
// Obtém um elemento <ul>
+var ul = document.getElementById('lista');
+
+// Obtém o último <li> pertencente a estrutura <ul> obtida
+var li_last = ul.lastChild;
+
+ +

Specificações

+ + diff --git a/files/pt-br/web/api/node/nextsibling/index.html b/files/pt-br/web/api/node/nextsibling/index.html new file mode 100644 index 0000000000..5bdb2b888e --- /dev/null +++ b/files/pt-br/web/api/node/nextsibling/index.html @@ -0,0 +1,66 @@ +--- +title: Node.nextSibling +slug: Web/API/Node/nextSibling +translation_of: Web/API/Node/nextSibling +--- +
+
{{ApiRef("DOM")}}
+
+ +

Resumo

+ +

Retorna o nó seguinte ao especificado dentro do lista de filhos do seu pai({{domxref("Node.childNodes","childNodes")}}), ou null se o nó especificado for o último nó da lista.

+ +

Sintaxe

+ +
proximoNo = no.nextSibling
+
+ +

Exemplo

+ +
<div id="div-01">Aqui esta a div-01</div>
+<div id="div-02">Aqui esta a div-02</div>
+
+<script type="text/javascript">
+var el = document.getElementById('div-01').nextSibling;
+
+document.write('<p>Nós irmãos de div-01</p><ol>');
+
+while (el) {
+  document.write('<li>' + el.nodeName + '</li>');
+  el = el.nextSibling;
+}
+
+document.write('</ol>');
+</script>
+
+/**************************************************
+     O seguinte texto será escrito na página quando ela carregar:
+
+     Nós irmãos de div-01
+
+      1. #text
+      2. DIV
+      3. #text
+      4. SCRIPT
+      5. P
+      6. OL
+**************************************************/
+
+ +

No exemplo acima, pode ser visto que nós #text são inseridos no DOM onde espaços em branco aparecem na marcação entre as tags (ex.: após o fechamento da tag de um elemento e antes da abertura da próxima tag). Nenhum espaço em branco é criado entre  elementos inseridos pelo comando document.write.

+ +

A possível inclusão de nós de texto no DOM deve ser permitida quando navegar pelo mesmo usando nextSibling.

+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/node/parentnode/index.html b/files/pt-br/web/api/node/parentnode/index.html new file mode 100644 index 0000000000..e68aef8eca --- /dev/null +++ b/files/pt-br/web/api/node/parentnode/index.html @@ -0,0 +1,116 @@ +--- +title: Node.parentNode +slug: Web/API/Node/parentNode +tags: + - API + - DOM + - Node + - ParentNode +translation_of: Web/API/Node/parentNode +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.parentNode é uma propriedade DOM somente leitura que retorna o nó (node) parente de um Node referenciado na árvore DOM. É extremamente aconselhável que você conheça a estrutura DOM para um melhor estudo e aprendizado.

+ +

Syntax

+ +
parentNode = node.parentNode
+
+ +

parentNode é o node parente do node referenciado. O parente de um elemento é um Element node, um Document node, ou um DocumentFragment node. Será muito complicado entender tudo isso sem conhecer a estrutura DOM e seus Elements.

+ +

Exemplo

+ +
// Exemplo de como obter um elemento pai
+parente = node.parentNode; // Retorna o elemento pai
+
+// Obtém o primeiro <li> de uma lista
+var li = document.getElementsById('li-first');
+// A partir do <li> obtido, obtém o element <ul>
+var ul = li.parentNode;
+
+// Estrutura com parágrafos dentro de uma div
+var p = document.getElementsByTagName('p');
+var div = p[0].parentNode;
+
+if (node.parentNode) {
+  // remove um node da árvore (estrutura) DOM, a menos que
+  // ele já não exista não estrutura
+  node.parentNode.removeChild(node);
+}
+ +

Notas

+ +

Document e DocumentFragment nodes nunca podem ter um node parent, sendo assim parentNode sempre retornará null. Também retornará null se o node já tiver sido criado e não ainda não estiver anexado à estrutura DOM.

+ +

Compatibilidade entre Browsers

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Suporte Básico{{CompatGeckoDesktop(1.0)}}0.2{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Specificações

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/node/previoussibling/index.html b/files/pt-br/web/api/node/previoussibling/index.html new file mode 100644 index 0000000000..ad5a88c16c --- /dev/null +++ b/files/pt-br/web/api/node/previoussibling/index.html @@ -0,0 +1,46 @@ +--- +title: Node.previousSibling +slug: Web/API/Node/previousSibling +translation_of: Web/API/Node/previousSibling +--- +
+
{{ApiRef("DOM")}}
+
+ +

Resumo

+ +

Retorna o nó que precede o nó especificado na lista de childNodes do nó pai, retorna null se o nó especificado é o primeiro desta lista.

+ +

Sintaxe

+ +
previousNode = node.previousSibling;
+
+ +

Exemplo

+ +
// <a><b1 id="b1"/><b2 id="b2"/></a>
+
+alert(document.getElementById("b1").previousSibling); // null
+alert(document.getElementById("b2").previousSibling.id); // "b1"
+
+ +

Notas

+ +

Navegador baseados na engine Gecko inserem nós de texto no documento para representar espaços em branco na marcação do fonte. + Portanto um nó obtido, por exemplo, usando Node.firstChild ou Node.previousSibling pode fazer referência a um + espaço em banco ao invés do elemento que o autor pretendia obter.

+ +

Veja Whitespace in the DOM e + W3C DOM 3 FAQ: Why are some Text nodes empty? + Para mais informações. +

+ +

Para navegar no sentido contrário da lista de nós filhos use Node.nextSibling.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/node/removechild/index.html b/files/pt-br/web/api/node/removechild/index.html new file mode 100644 index 0000000000..9eb927294d --- /dev/null +++ b/files/pt-br/web/api/node/removechild/index.html @@ -0,0 +1,72 @@ +--- +title: Node.removeChild +slug: Web/API/Node/removeChild +translation_of: Web/API/Node/removeChild +--- +
+
{{ApiRef("DOM")}}
+
+ +

Sumário

+ +

Remove um nó filho do DOM. Devolve o nó removido.

+ +

Sintaxe

+ +
var filhoRemovido = elemento.removeChild(filho);
+elemento.removeChild(filho);
+
+ + + +

O nó filho removido ainda existe em memória, mas não é mais parte do DOM. Você pode reutilizar o nó removido mais tarde no seu código por meio da referência filhoRemovido.

+ +

Se filho não for um filho do nó elemento, o método lança uma exceção. Isto também acontecerá se filho era, de fato, um filho de elemento no momento da chamada, mas foi removido por um manipulador de eventos invocado enquanto o elemento estava sendo removido (por exemplo, blur).

+ +

Exemplos

+ +
<!--Código HTML de exemplo-->
+
+<div id="topo" align="center">
+  <div id="interno"></div>
+</div>
+
+ +
// Removendo um elemento específico quando se conhece seu pai
+var d = document.getElementById("topo");
+var d_interno = document.getElementById("interno");
+var noRemovido = d.removeChild(d_interno);
+
+ +
// Removendo um elemento específico sem precisar especificar seu pai
+var no = document.getElementById("interno");
+if (no.parentNode) {
+  no.parentNode.removeChild(no);
+}
+
+ +
// Removendo todos os nós filhos de um elemento
+var elemento = document.getElementById("topo");
+while (elemento.firstChild) {
+  elemento.removeChild(elemento.firstChild);
+}
+
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/node/replacechild/index.html b/files/pt-br/web/api/node/replacechild/index.html new file mode 100644 index 0000000000..e6d78e3121 --- /dev/null +++ b/files/pt-br/web/api/node/replacechild/index.html @@ -0,0 +1,69 @@ +--- +title: Node.replaceChild +slug: Web/API/Node/replaceChild +translation_of: Web/API/Node/replaceChild +--- +
+
{{ApiRef("DOM")}}
+
+ +

Sumário

+ +

Substitui o elemento filho especificado por outro.

+ +

Sintaxe

+ +
replacedNode = parentNode.replaceChild(newChild, oldChild);
+
+ + + +

Exemplo

+ +
// <div>
+//  <span id="childSpan">foo bar</span>
+// </div>
+
+// Cria um novo elemento vazio
+// sem ID, atributos ou conteúdo
+var sp1 = document.createElement("span");
+
+// Adiciona um ID 'newSpan' para o elemento
+sp1.setAttribute("id", "newSpan");
+
+// Adiciona contéudo para o elemento
+var sp1_content = document.createTextNode("new replacement span element.");
+
+// Coloca o conteúdo no elemento
+sp1.appendChild(sp1_content);
+
+// Procura o elemento que será substituído
+var sp2 = document.getElementById("childSpan");
+var parentDiv = sp2.parentNode;
+
+// Substituí o elemento que já existe (sp2) por o novo elemento (sp1)
+parentDiv.replaceChild(sp1, sp2);
+
+// resultado:
+// <div>
+//   <span id="newSpan">new replacement span element.</span>
+// </div>
+
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/node/textcontent/index.html b/files/pt-br/web/api/node/textcontent/index.html new file mode 100644 index 0000000000..0fb3c38bdb --- /dev/null +++ b/files/pt-br/web/api/node/textcontent/index.html @@ -0,0 +1,138 @@ +--- +title: Node.textContent +slug: Web/API/Node/textContent +tags: + - API + - DOM + - Property +translation_of: Web/API/Node/textContent +--- +
{{APIRef("DOM")}}
+ +
+ +

A propriedade textContent da interface {{domxref("Node")}} representa o conteúdo de texto de um nó e dos seus descendentes.

+ +
+

Nota: textContent e {{domxref("HTMLElement.innerText")}} são facilmente confundidos, mas os dois possuem importantes diferenças entre sí.

+
+ +

Sintaxe

+ +
var text = Node.textContent;
+Node.textContent = string;
+
+ +

Valor de retorno

+ +

Uma String ou null

+ +

Descrição

+ +

Ao obter valores desta propriedade:

+ + + +

Definir valores textContent em um nó, remove todos os nós filhos e os substituem por um único nó de texto cujo o valor é a string inserida.

+ +

Diferenças para o innerText

+ +

Não fique confuso pelas diferenças entre o Node.textContent e o {{domxref("HTMLElement.innerText")}}. Apesar dos nomes parecerem similares, eles possuem importantes diferenças:

+ + + +

Diferenças para o innerHTML

+ +

O {{domxref("Element.innerHTML")}} retorna HTML, Como seu próprio nome indica. As vezes as pessoas usam o innerHTML para obter ou escrever textos dentro de um elemento, mas o textContent possui melhor performance pois seus valores não são analisados como HTML. Além do mais, utilizar textContent pode prevenir ataques XSS.

+ +

Exemplos

+ +

Dado o seguinte fragmento HTML:

+ +
<div id="divA">Isto é<span>algum</span> texto!</div>
+ +

... Você pode usar textContent para obter o conteúdo de texto do elemento:

+ +
let text = document.getElementById('divA').textContent;
+// Agora a variável de texto é: 'Isto é algum texto!'
+ +

... Ou definir o conteúdo de texto do elemento:

+ +
document.getElementById('divA').textContent = 'Este texto é diferente!';
+// O HTML de divA agora é:
+// <div id="divA">Este texto é diferente!</div>
+
+ +

Polyfill para o IE8

+ +
// Fonte: Eli Grey @ https://eligrey.com/blog/post/textcontent-in-ie8
+if (Object.defineProperty
+  && Object.getOwnPropertyDescriptor
+  && Object.getOwnPropertyDescriptor(Element.prototype, "textContent")
+  && !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) {
+  (function() {
+    var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
+    Object.defineProperty(Element.prototype, "textContent",
+     // Passando innerText ou innerText.get diretamente não funciona,
+     // Função wrapper(que envolve) é necessária.
+     {
+       get: function() {
+         return innerText.get.call(this);
+       },
+       set: function(s) {
+         return innerText.set.call(this, s);
+       }
+     }
+   );
+  })();
+}
+
+ +

Browser compatibility

+ + + +

{{Compat("api.Node.textContent")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-node-textcontent','Node.textContent')}}{{Spec2('DOM WHATWG')}}Sem alterações vs. DOM4
{{SpecName('DOM4','#dom-node-textcontent','Node.textContent')}}{{Spec2('DOM4')}}
{{SpecName('DOM3 Core','core.html#Node3-textContent','Node.textContent')}}{{Spec2('DOM3 Core')}}Introduzida
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/nodefilter/index.html b/files/pt-br/web/api/nodefilter/index.html new file mode 100644 index 0000000000..7aaa6fb99b --- /dev/null +++ b/files/pt-br/web/api/nodefilter/index.html @@ -0,0 +1,163 @@ +--- +title: NodeFilter +slug: Web/API/NodeFilter +translation_of: Web/API/NodeFilter +--- +
{{APIRef("DOM")}}
+ +
Uma interface NodeFilter  representa um objeto usado para filtrar os nós (elementos), em uma iteração {{ domxref("NodeIterator") }} ou  {{ domxref("TreeWalker") }}. Essas interfaces não conhecem nada sobre o DOM ou sobre como percorrer ou atravessar, elementos; elas apenas sabem como avaliar se um único nó atende aos requisitos do filtro fornecido ou não.
+ +
 
+ +
+

O navegador não fornece nenhum objeto que implemente essa interface. É esperado que o desenvolvedor escreva tal objeto, utilizando o método acceptNode() conforme as suas necessidades, podendo mesclar com objetos do tipo {{domxref("TreeWalker")}} ou {{domxref("NodeIterator")}}  em sua implementação.. 

+
+ +

Properties

+ +

Essa interface não implementa, nem herda, nenhuma propriedade.

+ +

Methods

+ +

Essa interface não herda nenhum método.

+ +
+
{{domxref("NodeFilter.acceptNode()")}}
+
Returns an unsigned short that will be used to tell if a given {{domxref("Node")}} must be accepted or not by the {{ domxref("NodeIterator") }} or {{ domxref("TreeWalker") }} iteration algorithm. This method is expected to be written by the user of a NodeFilter. Possible return values are: + + + + + + + + + + + + + + + + + + + +
ConstantDescription
FILTER_ACCEPTValue returned by the {{ domxref("NodeFilter.acceptNode()") }} method when a node should be accepted.
FILTER_REJECTValue to be returned by the {{ domxref("NodeFilter.acceptNode()") }} method when a node should be rejected. For {{ domxref("TreeWalker") }}, child nodes are also rejected. For {{ domxref("NodeIterator") }}, this flag is synonymous with FILTER_SKIP.
FILTER_SKIPValue to be returned by {{ domxref("NodeFilter.acceptNode()") }} for nodes to be skipped by the {{ domxref("NodeIterator") }} or {{ domxref("TreeWalker") }} object. The children of skipped nodes are still considered. This is treated as "skip this node but not its children".
+
+
+ +

Example

+ +
var nodeIterator = document.createNodeIterator(
+  // Node to use as root
+  document.getElementById('someId'),
+
+  // Only consider nodes that are text nodes (nodeType 3)
+  NodeFilter.SHOW_TEXT,
+
+  // Object containing the function to use for the acceptNode method
+  // of the NodeFilter
+    { acceptNode: function(node) {
+      // Logic to determine whether to accept, reject or skip node
+      // In this case, only accept nodes that have content
+      // other than whitespace
+      if ( ! /^\s*$/.test(node.data) ) {
+        return NodeFilter.FILTER_ACCEPT;
+      }
+    }
+  },
+  false
+);
+
+// Show the content of every non-empty text node that is a child of root
+var node;
+
+while ((node = nodeIterator.nextNode())) {
+  alert(node.data);
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-nodefilter', 'NodeFilter')}}{{Spec2('DOM WHATWG')}} 
{{SpecName('DOM2 Traversal_Range', 'traversal.html#Traversal-NodeFilter', 'NodeFilter')}}{{Spec2('DOM2 Traversal_Range')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(1)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8.1")}}9.09.03.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8.1")}}{{CompatVersionUnknown}}9.03.0
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/nodelist/index.html b/files/pt-br/web/api/nodelist/index.html new file mode 100644 index 0000000000..d20d2978a9 --- /dev/null +++ b/files/pt-br/web/api/nodelist/index.html @@ -0,0 +1,155 @@ +--- +title: NodeList +slug: Web/API/NodeList +tags: + - API + - DOM + - Interface + - NodeList +translation_of: Web/API/NodeList +--- +
{{APIRef("DOM")}}
+ +

Objetos NodeList são coleções de nodos semelhantes aos objetos retornados pelos métodos {{domxref("Node.childNodes")}} e {{domxref("document.querySelectorAll()")}}.

+ +
+

Apesar de NodeList não ser um Array, é possível ser iterada usando o método forEach(). Muitos navegadores antigos ainda não implementaram este método.

+
+ +

Em alguns casos, NodeList é uma coleção viva, ou seja, toda alteração feita no {{ Glossary("DOM") }} reflete nos elementos da coleção. Por exemplo, {{ domxref("Node.childNodes") }} é uma coleção viva:

+ +
var parent = document.getElementById('parent');
+var child_nodes = parent.childNodes;
+console.log(child_nodes.length); // let's assume "2"
+parent.appendChild(document.createElement('div'));
+console.log(child_nodes.length); // should output "3"
+
+ +

Já em outros casos NodeList é um coleção estática, significando que toda alteração subsequente ao {{ Glossary("DOM") }} não afeta o conteúdo da coleção. {{domxref("document.querySelectorAll()")}} é um exemplo de método que retorna uma NodeList estática.

+ +

É aconselhável lembrar dessa distinção quando for escolher como iterar sobre os itens de uma NodeList, e como você faz o cache do tamanho dessa lista.

+ +

Propriedades

+ +
+
{{domxref("NodeList.length")}}
+
A quantidade de nodos na NodeList.
+
+ +

Métodos

+ +
+
{{domxref("NodeList.item()")}}
+
Retorna um item da lista pelo índice, ou null se o índice for inválido; pode ser usado como uma alternativa a nodeList[idx] (que retorna  undefined quando idx é inválido).
+
{{domxref("NodeList.entries()")}}
+
Retorna um {{jsxref("Iteration_protocols","iterador")}} que permite passar por todos os pares chave/valor contidos no objeto.
+
{{domxref("NodeList.forEach()")}}
+
Executa uma função recebida uma vez para cada elemento no NodeList.
+
{{domxref("NodeList.keys()")}}
+
Retorna um {{jsxref("Iteration_protocols","iterador")}} que permite passar por todas as chaves dos pares chave/valor contidos no objeto.
+
{{domxref("NodeList.values()")}}
+
Retorna um {{jsxref("Iteration_protocols","iterador")}} que permite passar por todos os valores dos pares chave/valor contidos no objeto.
+
+ +

Exemplo

+ +

É possivel iterar sobre os items de um NodeList usando:

+ +
for (var i = 0; i < myNodeList.length; ++i) {
+  var item = myNodeList[i];  // Calling myNodeList.item(i) isn't necessary in JavaScript
+}
+
+ +

Não caia na tentação de usar for...in ou for each...in para enumerar os items de uma lista, já que também serão enumeradas as propriedades length e item da NodeList, o que causará erros se o seu script assumir que processará apenas objetos {{ domxref("element") }}. Não esquecendo que for..in não garante a iteração nas propriedades de forma ordenada.

+ +

for...of iterará sobre os objetos da NodeList de maneira correta:

+ +
var list = document.querySelectorAll( 'input[type=checkbox]' );
+for (var item of list) {
+  item.checked = true;
+}
+ +

Navegadores modernos suportam métodos de iteração, {{ domxref("NodeList.forEach()", "forEach()") }}, bem como {{ domxref("NodeList.entries()", "entries()") }}, {{ domxref("NodeList.values()", "values()") }}, e {{ domxref("NodeList.keys()", "keys()") }}

+ +

Há também um jeito compatível com o Internet Explorer de usar {{ jsxref("Array.forEach()", "Array.prototype.forEach") }} para iteração.

+ +
var list = document.querySelectorAll( 'input[type=checkbox]' );
+Array.prototype.forEach.call(list, function (item) {
+  item.checked = true;
+});
+ +

NodeList prototype

+ +

Você também pode adicionar protótipos para NodeList:

+ +
var elements = document.querySelectorAll(".suggestions");
+
+NodeList.prototype.addEventListener = function(event, func) {
+    this.forEach(function(content, item) {
+       content.addEventListener(event, func);
+    });
+}
+
+function log() {
+    console.log(this, " was clicked");
+}
+
+elements.addEventListener("click", log);
+//or
+elements.addEventListener("click", function() {
+    console.log(this, "  awas clicked");
+});
+// output from both will be element was clicked the element would be HTML Element
+ +

Para mais informações sobre forEach veja {{ jsxref("Array.forEach()", "Array.prototype.forEach") }}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-nodelist', 'NodeList')}}{{ Spec2('DOM WHATWG') }} 
{{SpecName('DOM4', '#interface-nodelist', 'NodeList')}}{{ Spec2('DOM4') }} 
{{SpecName('DOM3 Core', 'core.html#ID-536297177', 'NodeList')}}{{ Spec2('DOM3 Core') }} 
{{SpecName('DOM2 Core', 'core.html#ID-536297177', 'NodeList')}}{{ Spec2('DOM2 Core') }} 
{{SpecName('DOM1', 'level-one-core.html#ID-536297177', 'NodeList')}}{{ Spec2('DOM1') }}Initial definition.
+ +

Compatibilidade nos navegadores

+ + + +

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

+ +
 
+ +
 
diff --git a/files/pt-br/web/api/notificacoes/index.html b/files/pt-br/web/api/notificacoes/index.html new file mode 100644 index 0000000000..9103aac190 --- /dev/null +++ b/files/pt-br/web/api/notificacoes/index.html @@ -0,0 +1,217 @@ +--- +title: Notificações +slug: Web/API/notificacoes +tags: + - API + - Interface + - Notificações +translation_of: Web/API/Notification +--- +

{{APIRef("Web Notifications")}}{{AvailableInWorkers}}{{securecontext_header}}

+ +

A interface da API de Notificações é usada para configurar e exibir notificações  na área de trabalho do usuário. A aparência e algumas funcionalidades específicas das notificações variam entre as plataformas mas geralmente eles fornecem uma forma assíncrona de prover informações para o usuário.

+ + +

Construtor

+ +
+
{{domxref("Notification.Notification", "Notification()")}}
+
Cria uma nova instancia do objeto {{domxref('Notification')}}.
+
+ +

Propriedades

+ +

Propriedades estáticas

+ +

Estas propriedades estão disponíveis apenas no próprio objeto  Notification.

+ +
+
{{domxref("Notification.permission")}} {{readonlyinline}}
+
+
+
+
+ +
+
Uma sequência de caracteres que representa a permissão atual para exibir notificações. Valor possíveis são: "denied" (o usuário se recusa a ter notificações exibidas), "granted" (o usuário aceita ter notificações exibidas) ou "default" (a escolha do usuário é desconhecido e, portanto, o navegador irá agir como se o valor foram negados).
+
+
+
+ +

Propriedades da instância

+ +

Estas propriedades estão disponíveis apenas em instâncias do objeto Notification.

+ +
+
{{domxref("Notification.title")}} {{readonlyinline}}
+
Retorna o título da notificação conforme foi definido no parâmetro opções do construtor.
+
{{domxref("Notification.dir")}} {{readonlyinline}}
+
A direção do texto da notificação, conforme especificado no parâmetro opções do construtor.
+
{{domxref("Notification.lang")}} {{readonlyinline}}
+
+
+
O código de idioma da notificação, conforme especificado no parâmetro opções do construtor.
+
+
+
{{domxref("Notification.body")}} {{readonlyinline}}
+
O corpo(mensagem) da notificação, conforme especificado no parâmetro opções do construtor.
+
{{domxref("Notification.tag")}} {{readonlyinline}}
+
O ID da notificação (se houver), conforme especificado no parâmetro opções do construtor.
+
{{domxref("Notification.icon")}} {{readonlyinline}}
+
A URL da imagem usada como um ícone da notificação, conforme especificado no parâmetro opções do construtor.
+
{{domxref("Notification.data")}} {{readonlyinline}}
+
Retorna um clone estruturado de dados da notificação.
+
{{domxref("Notification.silent")}} {{readonlyinline}}
+
+
+
Especifica se a notificação deve ser silenciosa, ou seja, sons ou vibrações não devem ser emitidos, independentemente das configurações do dispositivo.
+
+
+
+ +

Propriedades não suportadas

+ +

As propriedades a seguir estão listados na especificação mais up-to-date, mas não são suportadas em quaisquer navegadores ainda. É aconselhável manter a verificação de volta regularmente para ver se o status destes actualiza, e deixe-nos saber se você encontrar qualquer informações desatualizadas.

+ +
+
{{domxref("Notification.noscreen")}} {{readonlyinline}}
+
+
+
Especifica se o disparo notificação deve permitir que a tela do dispositivo ou não.
+
+
+
{{domxref("Notification.renotify")}} {{readonlyinline}}
+
+
+
Especifica se o usuário deve ser notificado após uma nova notificação substitui um antigo.
+
+
+
{{domxref("Notification.sound")}} {{readonlyinline}}
+
Especifica um recurso de som para reproduzir durante o disparo da notificação, em vez do som de notificação do sistema padrão.
+
{{domxref("Notification.sticky")}} {{readonlyinline}}
+
Especifica se a notificação deve ser "fixa", ou seja, não facilmente eliminável pelo usuário.
+
{{domxref("Notification.vibrate")}} {{readonlyinline}}
+
Especifica um padrão de vibração para dispositivos com hardware de vibração.
+
+ +

Manipuladores de Eventos

+ +
+
{{domxref("Notification.onclick")}}
+
O manipulador para o evento {{event("click")}} é acionado cada vez que o usuário clica sobre a notificação.
+
{{domxref("Notification.onerror")}}
+
O manipulador para o evento {{event("error")}} é acionado quando a notificação encontra um erro.
+
+ +

Manipuladores Obsoletos

+ +

Os seguintes manipuladores de eventos ainda são suportados, conforme listado na seção {{anch("browser compatibility")}}. Estes serão listados abaixo, mas não são listados na especificação atual. Saiba que eles são obsoletos, e pode parar de funcionar em versões futuras do navegador.

+ +
+
{{domxref("Notification.onclose")}}
+
Manipulador do evento {{event("close")}} é acionado quando a notificação é fechada.
+
{{domxref("Notification.onshow")}}
+
Manipulador do evento {{event("show")}}. é acionado quando a notificação é exibida.
+
+ +

Métodos

+ +

Métodos Estáticos

+ +

Estes métodos estão disponíveis apenas no próprio objeto Notification.

+ +
+
{{domxref("Notification.requestPermission()")}}
+
+
+
Solicita a permissão do usuário para exibir notificações.
+
+
+
+ +

Métodos de instância

+ +

Estas propriedades estão disponíveis apenas no objeto Notification ou através do seu prototype. O objeto de notificação também herda a interface {{domxref("EventTarget")}}.

+ +
+
{{domxref("Notification.close()")}}
+
Programaticamente fecha uma notificação.
+
+ +

Exemplos

+ +

Leve em conta este HTML básico:

+ +
<button onclick="notifyMe()">Notifique me!</button>
+ +

É possível enviar uma notificação da seguinte forma - aqui nós apresentamos um conjunto bastante detalhado e completo de código que você pode usar se você quiser verificar primeiro se as notificações são suportados, em seguida, verifique se a permissão foi concedida para a origem atual para enviar notificações, em seguida, solicitar permissão, se necessário, antes, em seguida, enviar uma notificação.

+ +
function notifyMe() {
+  // Verifica se o browser suporta notificações
+  if (!("Notification" in window)) {
+    alert("Este browser não suporta notificações de Desktop");
+  }
+
+  // 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!");
+      }
+    });
+  }
+
+  // At last, if the user has denied notifications, and you
+  // want to be respectful there is no need to bother them any more.
+}
+ +

{{EmbedLiveSample('Exemplo', '100%', 30)}}

+ +

Em muitos casos, você não precisa estar presente detalhado. Por exemplo, na nosso Emogotchi demo (veja o código fonte), basta simlesmente executar {{domxref("Notification.requestPermission")}} independentemente de se certificar de que pode obter permissão para enviar notificações:

+ +
Notification.requestPermission();
+ +

Em seguida executar um simples spawnNotification() quando queremos disparar uma notificação — este é passado argumentos para especificar o, ícone corpo e título que queremos, então ele cria as opções necessárias objeto e dispara a notificação usando o construtor {{domxref("Notification.Notification","Notification()")}}.

+ +
function spawnNotification(corpo,icone,titulo) {
+  var opcoes = {
+      body: corpo,
+      icon: icone
+  }
+  var n = new Notification(titulo,opcoes);
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Living standard
+ +

Compatibilidade dos Navegadores

+ + + +

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

+

Veja também

+ + diff --git a/files/pt-br/web/api/notificationaction/index.html b/files/pt-br/web/api/notificationaction/index.html new file mode 100644 index 0000000000..a7cb904ac5 --- /dev/null +++ b/files/pt-br/web/api/notificationaction/index.html @@ -0,0 +1,79 @@ +--- +title: NotificationAction +slug: Web/API/NotificationAction +translation_of: Web/API/NotificationAction +--- +
{{APIRef("Web Notifications")}}{{AvailableInWorkers}}{{securecontext_header}}
+ +

A interface NotificationAction de Notifications API é usada para representar botões de ação que o usuário pode clicar para intergair com as notificações. As aparências e as funcionalidades específicas dos botões variam entre plataformas, mas geralmente providenciam maneiras de mostrar ações assincronamente ao usuário, em forma de notificações.

+ +

Propriedades

+ +

Propriedades de instância

+ +

Essas propriedades estão disponíveis somente para instâncias do objeto Notification.

+ +
+
{{domxref("NotificationAction.action")}} {{readonlyinline}}
+
O nome da ação, que pode ser usado para identificar a ação clicada, similiar a input names.
+
{{domxref("NotificationAction.title")}} {{readonlyinline}}
+
Uma string descrevendo a ação que sera mosrada ao usuário.
+
{{domxref("NotificationAction.icon")}} {{readonlyinline}}
+
O URL da imagem usado para representar a notificação quando não houver espaço suficiente para mostrar a propria notificação.
+
+ +

Exemplo

+ +

Notifications can fire {{Event("notificationclick")}} events on the {{domxref("ServiceWorkerGlobalScope")}}.

+ +

Here a service worker shows a notification with a single "Archive" action, allowing users to perform this common task from the notification without having to open the website. The user can also click the main body of the notification to open their inbox instead.

+ +
self.registration.showNotification("New mail from Alice", {
+  actions: [
+    {
+      action: 'archive',
+      title: 'Archive'
+    }
+  ]
+});
+
+self.addEventListener('notificationclick', function(event) {
+  event.notification.close();
+  if (event.action === 'archive') {
+    // Archive action was clicked
+    archiveEmail();
+  } else {
+    // Main body of notification was clicked
+    clients.openWindow('/inbox');
+  }
+}, false);
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Living standard
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/offlineaudiocontext/index.html b/files/pt-br/web/api/offlineaudiocontext/index.html new file mode 100644 index 0000000000..2e0c205feb --- /dev/null +++ b/files/pt-br/web/api/offlineaudiocontext/index.html @@ -0,0 +1,150 @@ +--- +title: OfflineAudioContext +slug: Web/API/OfflineAudioContext +translation_of: Web/API/OfflineAudioContext +--- +
{{APIRef("Web Audio API")}}
+ +
A interface OfflineAudioContext é uma interface {{domxref("AudioContext")}} que representa um gráfico de processament de áudio construido a partir de conexões entre {{domxref("AudioNode")}}s. Em contraste com o padrão {{domxref("AudioContext")}}, um OfflineAudioContext não processa o áudio para o hardware do dispositivo; Em vez disso, ele gera, o mais rápido possível, e exibe o resultado para um {{domxref("AudioBuffer")}}.
+ +

{{InheritanceDiagram}}

+ +

Construtor

+ +
+
{{domxref("OfflineAudioContext.OfflineAudioContext()")}}
+
Cria uma nova instância OfflineAudioContext.
+
+ +

Propriedades

+ +

Também herda propriedades da sua entidade paterna, {{domxref("BaseAudioContext")}}.

+ +
+
{{domxref('OfflineAudioContext.length')}} {{readonlyinline}}
+
+

Um número inteiro que representa o tamanho do buffer em quadros de amostra.

+
+
+ +

Manipuladores de Eventos

+ +
+
{{domxref("OfflineAudioContext.oncomplete")}}
+
É uma chamada {{domxref("EventHandler")}} quando o processamento é encerrado, é quando o evento {{event("complete")}}  - do tipo {{domxref("OfflineAudioCompletionEvent")}} - é gerado, após a versão baseada em eventos do {{domxref("OfflineAudioContext.startRendering()")}} é usada.
+
+ +

Métodos

+ +

Também herda métodos da interface paterna, {{domxref("BaseAudioContext")}}.

+ +
+
{{domxref("OfflineAudioContext.resume()")}}
+
+

Programa uma suspensão da progressão do tempo no contexto de áudio no horário especificado e retorna uma promessa.

+
+
{{domxref("OfflineAudioContext.suspend()")}}
+
+

Agende uma suspensão da progressão do tempo no contexto de áudio no horário especificado e retorna uma promessa.

+
+
{{domxref("OfflineAudioContext.startRendering()")}}
+
+

Inicia a renderização do áudio, levando em consideração as conexões atuais e as mudanças programadas atuais. Esta página abrange a versão baseada em eventos e a versão baseada em promessas.

+
+
+ +

Exemplo

+ +

Nesse exemplo, declaramos um ambos {{domxref("AudioContext")}} e um OfflineAudioContext objeto. Nós usamos o AudioContext para carregar uma faixa de áudio via XHR ({{domxref("AudioContext.decodeAudioData")}}), então o OfflineAudioContext para renderizar o áudio em um {{domxref("AudioBufferSourceNode")}} e reproduzir a trilha. Depois que o gráfico de áudio off-line estiver configurado, você deve renderizá-lo para {{domxref("AudioBuffer")}} usando {{domxref("OfflineAudioContext.startRendering")}}.

+ +

Quando a 'promise' startRendering() é resolvida, a renderização foi concluída e a saída AudioBuffer é retornada fora da 'promise.

+ +

Neste ponto, criamos outro contexto de áudio, criamos um {{domxref("AudioBufferSourceNode")}} dentro dele e configuramos o buffer para ser igual à promessa AudioBuffer. Isso é jogado como parte de um gráfico de áudio padrão simples.

+ +
+

Nota: Para um exemplo de trabalho, veja nosso offline-audio-context-promise Github repo (veja o código fonte também.)

+
+ +
// define o contexto de áudio online e offline
+
+var audioCtx = new AudioContext();
+var offlineCtx = new OfflineAudioContext(2,44100*40,44100);
+
+source = offlineCtx.createBufferSource();
+
+// usa XHR para carregar uma faixa de áudio, e
+// decodeAudioData para decodificar e OfflineAudioContext para renderizar
+
+function getData() {
+  request = new XMLHttpRequest();
+
+  request.open('GET', 'viper.ogg', true);
+
+  request.responseType = 'arraybuffer';
+
+  request.onload = function() {
+    var audioData = request.response;
+
+    audioCtx.decodeAudioData(audioData, function(buffer) {
+      myBuffer = buffer;
+      source.buffer = myBuffer;
+      source.connect(offlineCtx.destination);
+      source.start();
+      //source.loop = true;
+      offlineCtx.startRendering().then(function(renderedBuffer) {
+        console.log('Rendering completed successfully');
+        var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+        var song = audioCtx.createBufferSource();
+        song.buffer = renderedBuffer;
+
+        song.connect(audioCtx.destination);
+
+        play.onclick = function() {
+          song.start();
+        }
+      }).catch(function(err) {
+          console.log('Rendering failed: ' + err);
+          // Nota: A promessa deve rejeitar quando o StartRendering é chamado uma segunda vez em um OfflineAudioContext
+      });
+    });
+  }
+
+  request.send();
+}
+
+// Run getData to start the process off
+
+getData();
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#OfflineAudioContext', 'OfflineAudioContext')}}{{Spec2('Web Audio API')}}Initial definition
+ +

Compatibilidade de Navegadores/Browser

+ +
+ + +

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

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/page_visibility_api/index.html b/files/pt-br/web/api/page_visibility_api/index.html new file mode 100644 index 0000000000..1fc2222ad0 --- /dev/null +++ b/files/pt-br/web/api/page_visibility_api/index.html @@ -0,0 +1,209 @@ +--- +title: Page Visibility API +slug: Web/API/Page_Visibility_API +tags: + - DOM + - Intermediário + - Tutoriais + - Visibilidade +translation_of: Web/API/Page_Visibility_API +--- +

{{DefaultAPISidebar("Page Visibility API")}}

+ +

API de visibilidade de página deixa você saber quando uma página da web está visível ou em foco. Com a navegação em abas, existem razões para que quaisquer páginas da web que estejam sendo executadas em segundo plano e não visíveis para o usuário. Quando o usuário minimiza a página ou muda para outra aba, a API envia um evento {{event("visibilitychange")}} informando o estado de visibilidade da página. Você pode detectar o evento e realizar algumas ações ou modificar o seu comportamento. Por exemplo, se a sua aplicação web estiver reproduzindo um video, ela pode pausar durante o momento que o usuário estiver olhando para outra aba, e reproduz novamente quando o usuário retorna para a aba. O usuário não perde nenhuma parte do video e pode continuar assistindo.

+ +

Benefícios

+ +

A API é particularmente util para economizar recursos dando aos desenvolvedores a oportunidade de não realizar tarefas desnecessárias quando a página não está visível.

+ +

Casos de uso

+ +

Alguns exemplos:

+ + + +

Desenvolvedores têm historicamente usado alternativas de se detectar isto. Por exemplo, registrando um handler onblur/onfocus na janela te ajuda a saber quando a sua página não é a ativa, mas isto não te diz se a sua página não está visível para o usuário. Já a API de Visibilidade de Página faz isto. (Quando comparada com a técnica de registrar handlers de onblur/onfocus na janela, uma diferencia chave é que a página não fica escondida quando outra janela é ativada e a janela do navegador perde o foco. A página só fica escondida quando o usuário troca para uma aba diferente ou minimiza a janela do navegador.)

+ +

Exemplo

+ +

Veja exemplo em caso real (video com som).

+ +

O exemplo, que pausa o video quando você troca para outra aba e volta a reproduzir quando você retorna, foi criado com o seguinte código:

+ +
// Configura o nome da propriedade hidden e o evento de mudança para visibilidade
+var hidden, visibilityChange;
+if (typeof document.hidden !== "undefined") { // Suporte para Opera 12.10 e Firefox 18 em diante
+  hidden = "hidden";
+  visibilityChange = "visibilitychange";
+} else if (typeof document.mozHidden !== "undefined") {
+  hidden = "mozHidden";
+  visibilityChange = "mozvisibilitychange";
+} 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");
+
+// Se a página está escondida, pausa o video;
+// Se a página está visível, reproduz o video
+function handleVisibilityChange() {
+  if (document[hidden]) {
+    videoElement.pause();
+  } else {
+    videoElement.play();
+  }
+}
+
+// Alerta se o navegador não suporta addEventListener ou a API de visibilidade da página
+if (typeof document.addEventListener === "undefined" ||
+  typeof document[hidden] === "undefined") {
+  alert("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
+} else {
+  // Manipula o evento de mudança da visibilidade da página
+  document.addEventListener(visibilityChange, handleVisibilityChange, false);
+
+  // Reverte para o favicon existente para o site quando a página é fechada;
+  // caso contrário, o favicon continua como paused.png
+  window.addEventListener("unload", function(){
+    favicon.change("/favicon.ico");
+  }, false);
+
+  // Quando o video é pausado, configura o favicon.
+  // Isso mostra a imagem paused.png
+  videoElement.addEventListener("pause", function(){
+    favicon.change("images/paused.png");
+  }, false);
+
+  // Quando o video é reproduzido, configura o favicon.
+  videoElement.addEventListener("play", function(){
+    favicon.change("images/playing.png");
+  }, false);
+
+  // Configura o título da aba com o tempo atual do video
+  videoElement.addEventListener("timeupdate", function(){
+    document.title = Math.floor(videoElement.currentTime) + " segundo(s)";
+  }, false);
+}
+
+ +

Visão geral das propriedades

+ +

document.hidden Somented leitura 

+ +

Retorna true se a página está escondida para o usuário, caso contrário, retorna false.

+ +

document.visibilityState Somente leitura 

+ +

É a cadeia de caracteres que denota a visibilidade do documento. Possíveis valores:

+ + + +
//startSimulation e pauseSimulation definidas em outro lugar
+function handleVisibilityChange() {
+  if (document.hidden) {
+    pauseSimulation();
+  } else  {
+    startSimulation();
+  }
+}
+
+document.addEventListener("visibilitychange", handleVisibilityChange, false);
+
+ +

Nota

+ +

Os estados de visibilidade de {{HTMLElement("iframe")}} são os mesmos do documento pai. Esconder o iframe com propriedades CSS não ativa os eventos de visibilidade nem muda o estado do documento do conteúdo.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Page Visibility API')}}{{Spec2('Page Visibility API')}} 
+ +

Compatibilidade com navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13 {{property_prefix("webkit")}}
+ 33
{{CompatGeckoDesktop(10)}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop(18)}}
1012.10[1]7
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico4.4 {{property_prefix("webkit")}}{{CompatGeckoMobile(10)}} {{property_prefix("moz")}}
+ {{CompatGeckoMobile(18)}}
1012.10[1]7
+
+ +

[1] Não ativa o evento visibilitychange quando a janela do navegador é minimizada, nem configura hidden como true.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/parentnode/childelementcount/index.html b/files/pt-br/web/api/parentnode/childelementcount/index.html new file mode 100644 index 0000000000..dea1fed6cd --- /dev/null +++ b/files/pt-br/web/api/parentnode/childelementcount/index.html @@ -0,0 +1,98 @@ +--- +title: ParentNode.childElementCount +slug: Web/API/ParentNode/childElementCount +tags: + - Child + - DOM + - JavaScript + - ParentNode +translation_of: Web/API/ParentNode/childElementCount +--- +
{{ APIRef("DOM") }}
+ +

A propriedade ParentNode.childElementCount, do tipo "somente leitura" (read-only), tem como retorno um unsigned long que representa q quantidade de elementos filhos de um outro determinado elemento.

+ +
+

Essa propriedade foi inicialmente definida na interface pura {{domxref("ElementTraversal")}}. Como essa interface continha dois conjuntos distintos de propriedades, sendo uma destinada para {{domxref("Node")}} que tem filhos, e outra destinada para aqueles que são filhos de fato, essas propriedades foram movidas para duas interfaces puras distintas: {{domxref("ParentNode")}} e {{domxref("ChildNode")}}. Nesse caso, childElementCount foi movido para {{domxref("ParentNode")}}.  Essa é uma alteração bastante técnica que não deve afetar a compatibilidade.

+
+ +

Sintaxe

+ +
var count = node.childElementCount;
+
+ +
+
count
+
variável que recebe o valor retornado pelo método, sendo esse valor do tipo unsigned long (simplesmente um número inteiro).
+
node
+
Objeto que representa {{domxref("Document")}}, {{domxref("DocumentFragment")}}, ou {{domxref("Element")}}.
+
+ +

Exemplo

+ +
var foo = document.getElementById('foo');
+if (foo.childElementCount > 0) {
+  // Faz algo
+}
+
+ +

Utilizando Polyfill no IE8, IE9 e Safari

+ +

Essa propriedade não é suportada em versões anteriores ao IE9. Já no IE9 ou Safari, não será suportada somente por Objetos de Document e DocumentFragment.

+ +
;(function(constructor) {
+  if (constructor &&
+      constructor.prototype &&
+      constructor.prototype.childElementCount == null) {
+    Object.defineProperty(constructor.prototype, 'childElementCount', {
+      get: function() {
+        var i = 0, count = 0, node, nodes = this.childNodes;
+        while (node = nodes[i++]) {
+          if (node.nodeType === 1) count++;
+        }
+        return count;
+      }
+    });
+  }
+})(window.Node || window.Element);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentários
{{SpecName('DOM WHATWG', '#dom-parentnode-childelementcount', 'ParentNode.childElementCount')}}{{Spec2('DOM WHATWG')}}Divide a interface ElementTraversal entre {{domxref("ChildNode")}} e ParentNode. Esse método é definido ao final.
+ {{domxref("Document")}} e {{domxref("DocumentFragment")}} implementam essas novas interfaces.
{{SpecName('Element Traversal', '#attribute-childElementCount', 'ElementTraversal.childElementCount')}}{{Spec2('Element Traversal')}} +

Adicionada sua definição inicial à interface pura do ElementTraversal e use-a em {{domxref("Element")}}.

+
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.ParentNode.childElementCount")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/parentnode/children/index.html b/files/pt-br/web/api/parentnode/children/index.html new file mode 100644 index 0000000000..755cff62a5 --- /dev/null +++ b/files/pt-br/web/api/parentnode/children/index.html @@ -0,0 +1,131 @@ +--- +title: ParentNode.children +slug: Web/API/ParentNode/children +translation_of: Web/API/ParentNode/children +--- +

{{ APIRef("DOM") }}

+ +

Node.children é uma propriedade exclusivamente de leitura que retorna uma coleção {{domxref("HTMLCollection")}} dos elementos filhos do .

+ +

Sintaxe

+ +
var elList = elementNodeReference.children; 
+ +

elList é uma {{ domxref("HTMLCollection") }}, que é uma lista ordenada de uma coleção de elementos do DOM que são filhos do elementNodeReference. Se não existir nenhum elemento filho, o elList não terá elemento algum sua propriedade length será 0.

+ +

Exemplo

+ +
// pEl é uma referência à um elemento <p>
+var elementChildren = pEl.children;
+for (var i = 0; i < elementChildren.length; i++) {
+    console.log(elementChildren[i].tagName);
+    // NOTE: elementChildren é uma lista viva, adicionar ou remover filhos de pEl
+    // mudará instantaneamente o valor retornado por elementChildren
+}
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('DOM WHATWG', '#dom-parentnode-children', 'ParentNode.children')}}{{Spec2('DOM WHATWG')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support (on {{domxref("Element")}})1.0{{CompatGeckoDesktop("1.9.1")}}9.0 [1]38.010.04.0
Support on {{domxref("Document")}} and {{domxref("DocumentFragment")}} {{experimental_inline}}29.0{{CompatGeckoDesktop("25.0")}}{{CompatNo}}{{CompatNo}}16.0{{CompatNo}}
Support on {{domxref("SVGElement")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (on {{domxref("Element")}}){{ CompatVersionUnknown() }}{{CompatGeckoMobile("1.9.1")}}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Support on {{domxref("Document")}} and {{domxref("DocumentFragment")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatGeckoMobile("25.0")}}{{CompatNo}}16.0{{CompatNo}}
+
+ +

[1] Internet Explorer 6, 7 e 8 suportaram esse método, mas erroneamente incluiam nós de {{domxref("Comment")}}.

+ +

See also

+ + diff --git a/files/pt-br/web/api/parentnode/index.html b/files/pt-br/web/api/parentnode/index.html new file mode 100644 index 0000000000..ac2ca6c4ba --- /dev/null +++ b/files/pt-br/web/api/parentnode/index.html @@ -0,0 +1,163 @@ +--- +title: ParentNode +slug: Web/API/ParentNode +tags: + - API + - DOM + - NeedsTranslation + - TopicStub +translation_of: Web/API/ParentNode +--- +
{{APIRef("DOM")}}
+ +

The ParentNode interface contains methods that are particular to {{domxref("Node")}} objects that can have children.

+ +

ParentNode is a raw interface and no object of this type can be created; it is implemented by {{domxref("Element")}}, {{domxref("Document")}}, and {{domxref("DocumentFragment")}} objects.

+ +

Properties

+ +
+
{{ domxref("ParentNode.children") }} {{experimental_inline}} {{readonlyInline}}
+
Returns a live {{domxref("HTMLCollection")}} containing all objects of type {{domxref("Element")}} that are children of this ParentNode.
+
{{ domxref("ParentNode.firstElementChild") }} {{experimental_inline}} {{readonlyInline}}
+
Returns the {{domxref("Element")}} that is the first child of this ParentNode, or null if there is none.
+
{{ domxref("ParentNode.lastElementChild") }} {{experimental_inline}} {{readonlyInline}}
+
Returns the {{domxref("Element")}} that is the last child of this ParentNode, or null if there is none.
+
{{ domxref("ParentNode.childElementCount") }} {{experimental_inline}} {{readonlyInline}}
+
Returns an unsigned long giving the amount of children that the object has.
+
+ +

Methods

+ +
+
{{ domxref("ParentNode.append()") }} {{experimental_inline}}
+
Inserts a set of {{domxref("Node")}} objects or {{domxref("DOMString")}} objects after the last child of the ParentNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
{{ domxref("ParentNode.prepend()") }} {{experimental_inline}}
+
Inserts a set of {{domxref("Node")}} objects or {{domxref("DOMString")}} objects before the first child of the ParentNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
+ +

Specification

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-parentnode-firstelementchild', 'ParentNode.firstElementChild')}}{{Spec2('DOM WHATWG')}}Splitted the ElementTraversal interface in {{domxref("ChildNode")}} and ParentNode. The firstElementChild, lastElementChild, and childElementCount properties are now defined on the latter.
+ The {{domxref("Document")}} and {{domxref("DocumentFragment")}} implemented the new interfaces.
+ Added the children property.
+ Added the append() and prepend() methods.
{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}{{Spec2('Element Traversal')}}Added the initial definition of its properties to the ElementTraversal pure interface and use it on {{domxref("Element")}}.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (on {{domxref("Element")}}){{CompatChrome(1.0)}}{{CompatGeckoDesktop("1.9.1")}}9.0 [1]10.04.0
Support on {{domxref("Document")}} and {{domxref("DocumentFragment")}} {{experimental_inline}}{{CompatChrome(29.0)}}{{CompatGeckoDesktop(25)}}{{CompatNo}}16.0{{CompatNo}}
append() and prepend() {{experimental_inline}}{{CompatChrome(54.0)}}{{CompatGeckoDesktop(49)}}{{CompatVersionUnknown}}{{CompatOpera(39)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Mobile
Basic support (on {{domxref("Element")}}){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Support on {{domxref("Document")}} and {{domxref("DocumentFragment")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(25)}}{{CompatNo}}16.0{{CompatNo}}{{CompatVersionUnknown}}
append() and prepend() {{experimental_inline}}{{CompatNo}}{{CompatChrome(54.0)}}{{CompatGeckoMobile(49)}}{{CompatNo}}{{CompatOperaMobile(39)}}{{CompatNo}}{{CompatChrome(54.0)}}
+
+ +

[1] Internet Explorer 6, 7 and 8 supported it, but erroneously returns {{domxref("Comment")}} nodes as part of the results.

+ +

See also

+ + diff --git a/files/pt-br/web/api/parentnode/queryselector/index.html b/files/pt-br/web/api/parentnode/queryselector/index.html new file mode 100644 index 0000000000..0e719e1a73 --- /dev/null +++ b/files/pt-br/web/api/parentnode/queryselector/index.html @@ -0,0 +1,101 @@ +--- +title: ParentNode.querySelector() +slug: Web/API/ParentNode/querySelector +tags: + - PrecisaDeExemplo + - Projeto + - Referencia + - Seletores + - metodo +translation_of: Web/API/ParentNode/querySelector +--- +

{{APIRef("DOM")}}{{Draft}}

+ +

O {{DOMxRef("ParentNode")}} mixin define o querySelector() método como retornar um {{DOMxRef("Element")}} representando o primeiro elemento que corresponde ao grupo especificado de seletores que são descendentes do objeto no qual o método foi chamado.

+ +

Se você precisar de todos os elementos correspondentes à lista de seletores, use{{DOMxRef("ParentNode.querySelectorAll", "querySelectorAll()")}} instead.

+ +
+

Nota: Este método é implementado como {{DOMxRef("Document.querySelector()")}}, {{DOMxRef("DocumentFragment.querySelector()")}} e {{DOMxRef("Element.querySelector()")}}.

+
+ +

Sintaxe

+ +
element = parentNode.querySelector(selectors);
+
+ +

Parâmetros

+ +
+
selectors
+
Um {{DOMxRef("DOMString")}} contendo um ou mais seletores para comparar. Essa sequência deve ser um válido lista de seletores compostos suportado pelo navegador; se não for, um SyntaxError exceção é lançada. Veja Localizando elementos DOM usando seletores para obter mais informações sobre o uso de seletores para identificar elementos. Vários seletores podem ser especificados, separando-os usando vírgulas.
+
+ +
+

Nota: Os caracteres que não fazem parte da sintaxe CSS padrão devem ser escapados usando um caractere de barra invertida. Como o JavaScript também usa escape de backspace, deve-se tomar cuidado especial ao escrever literais de string usando esses caracteres. Veja {{anch("Escaping special characters")}} Para maiores informações.

+
+ +

Valor de retorno

+ +

O primeiro {{DOMxRef("Element")}} que corresponda a pelo menos um dos seletores ou null se esse elemento não for encontrado.

+ +
+

Nota: Se o especificado selectors inclua um CSS pseudo-elemento, o valor retornado é sempre null.

+
+ +

Exceções

+ +
+
SyntaxError
+
A sintaxe do especificado selectors string não é válida.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("DOM WHATWG", "#dom-parentnode-queryselector", "ParentNode.querySelector()")}}{{Spec2("DOM WHATWG")}}Padrão de vida
{{SpecName("Selectors API Level 2", "#dom-parentnode-queryselector", "ParentNode.querySelector()")}}{{Spec2("Selectors API Level 2")}}Sem alteração
{{SpecName("DOM4", "#dom-parentnode-queryselector", "ParentNode.querySelector()")}}{{Spec2("DOM4")}}Definição inicial
{{SpecName("Selectors API Level 1", "#interface-definitions", "document.querySelector()")}}{{Spec2("Selectors API Level 1")}}Definição original
+ +

Compatibilidade do navegador

+ + + +

{{Compat("api.ParentNode.querySelector")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/path2d/index.html b/files/pt-br/web/api/path2d/index.html new file mode 100644 index 0000000000..65f626f8f6 --- /dev/null +++ b/files/pt-br/web/api/path2d/index.html @@ -0,0 +1,82 @@ +--- +title: Path2D +slug: Web/API/Path2D +tags: + - Canvas + - Compatibilidade + - Interface + - JavaScript + - Métodos + - Pacote 2D + - Path2D + - Referencia +translation_of: Web/API/Path2D +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

Path2D interface da API Canvas 2D é usada para declarar caminhos que são usados ​​posteriormente em objetos {{domxref("CanvasRenderingContext2D")}}. Os métodos de caminho da interface CanvasRenderingContext2D também estão presentes nessa interface e permitem criar caminhos que você pode reter e reproduzir conforme necessário em uma tela.

+ +

Construtores

+ +
+
{{domxref("Path2D.Path2D", "Path2D()")}}
+
Path2D construtor. Cria um novo objeto Path2D.
+
+ +

Metodos

+ +
+
{{domxref("Path2D.addPath()")}}
+
Adiciona um caminho ao caminho atual.
+
{{domxref("CanvasRenderingContext2D.closePath", "Path2D.closePath()")}}
+
Faz com que o ponto da caneta retorne ao início do sub-caminho atual. Ele tenta desenhar uma linha reta desde o ponto atual até o início. Se a forma já foi fechada ou tem apenas um ponto, essa função não faz nada.
+
{{domxref("CanvasRenderingContext2D.moveTo()", "Path2D.moveTo()")}}
+
Move o ponto inicial de um novo subcaminho para as coordenadas (x, y).
+
{{domxref("CanvasRenderingContext2D.lineTo()", "Path2D.lineTo()")}}
+
Conecta o último ponto no subcaminho às coordenadas x, y com uma linha reta.
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo()", "Path2D.bezierCurveTo()")}}
+
Adiciona uma curva cúbica de Bézier ao caminho. Requer três pontos. Os dois primeiros pontos são pontos de controle e o terceiro é o ponto final. O ponto de partida é o último ponto no caminho atual, que pode ser alterado usando moveTo () antes de criar a curva Bézier.
+
{{domxref("CanvasRenderingContext2D.quadraticCurveTo()", "Path2D.quadraticCurveTo()")}}
+
Adiciona uma curva quadrática de Bézier ao caminho atual.
+
{{domxref("CanvasRenderingContext2D.arc()", "Path2D.arc()")}}
+
Adiciona um arco ao caminho que é centralizado na posição (x, y) com raio r iniciando em startAngle e terminando em endAngle indo na direção dada no sentido anti-horário (padrão no sentido horário).
+
{{domxref("CanvasRenderingContext2D.arcTo()", "Path2D.arcTo()")}}
+
Adiciona um arco ao caminho com os pontos de controle e raio dados, conectados ao ponto anterior por uma linha reta.
+
{{domxref("CanvasRenderingContext2D.ellipse()", "Path2D.ellipse()")}}
+
Adiciona uma elipse ao caminho que é centralizado na posição (x, y) com os raios radiusX e radiusY começando em startAngle e terminando em endAngle indo na direção determinada no sentido anti-horário (padrão no sentido horário).
+
{{domxref("CanvasRenderingContext2D.rect()", "Path2D.rect()")}}
+
Cria um caminho para um retângulo na posição (x, y) com um tamanho determinado por width e height.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-path2d", "Path2D")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade com o Navegador

+ +
+ + +

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

+
+ +

Veja também:

+ + diff --git a/files/pt-br/web/api/performance/index.html b/files/pt-br/web/api/performance/index.html new file mode 100644 index 0000000000..28e3a63c06 --- /dev/null +++ b/files/pt-br/web/api/performance/index.html @@ -0,0 +1,138 @@ +--- +title: Performance +slug: Web/API/Performance +tags: + - API + - Interface + - Navigation Timing + - NeedsTranslation + - Performance + - Reference + - TopicStub + - Web Performance +translation_of: Web/API/Performance +--- +
{{APIRef("High Resolution Time")}}
+ +

The Performance interface represents timing-related performance information for the given page.

+ +

An object of this type can be obtained by calling the {{domxref("Window.performance")}} read-only attribute.

+ +
+

Note: This interface and its members are available in Web Workers, except where indicated below. Note that some available parts of the interface are not yet documented (see the Performance Timeline and User Timing specs for more details.) Also note that performance markers and measures are per context. If you create a mark on the main thread (or other worker), you cannot see it in a worker thread, and vice versa.

+
+ +

Properties

+ +

The Performance interface doesn't inherit any properties.

+ +
+
{{domxref("Performance.navigation")}} {{readonlyInline}}
+
Is a {{domxref("PerformanceNavigation")}} object representing the type of navigation that occurs in the given browsing context, like the amount of redirections needed to fetch the resource. Not available in workers.
+
{{domxref("Performance.onframetimingbufferfull")}}
+
TBD
+
{{domxref("Performance.onresourcetimingbufferfull")}}
+
Is an {{domxref("EventTarget")}} which is a callback that will be called when the {{event("resourcetimingbufferfull")}} event is fired.
+
{{domxref("Performance.timing")}} {{readonlyInline}}
+
Is a {{domxref("PerformanceTiming")}} object containing latency-related performance information. Not available in workers.
+
+ +

Methods

+ +

The Performance interface doesn't inherit any method.

+ +
+
{{domxref("Performance.clearFrameTimings()")}}
+
TBD
+
{{domxref("Performance.clearMarks()")}}
+
Removes the given mark from the browser's performance entry buffer.
+
{{domxref("Performance.clearMeasures()")}}
+
Removes the given measure from the browser's performance entry buffer.
+
{{domxref("Performance.clearResourceTimings()")}}
+
Removes all {{domxref("PerformanceEntry","performance entries")}} with a {{domxref("PerformanceEntry.entryType","entryType")}} of "resource" from the browser's performance data buffer.
+
{{domxref("Performance.getEntries()")}}
+
Returns a list of {{domxref("PerformanceEntry")}} objects based on the given filter.
+
{{domxref("Performance.getEntriesByName()")}}
+
Returns a list of {{domxref("PerformanceEntry")}} objects based on the given name and entry type.
+
{{domxref("Performance.getEntriesByType()")}}
+
Returns a list of {{domxref("PerformanceEntry")}} objects of the given entry type.
+
{{domxref("Performance.mark()")}}
+
Creates a {{domxref("DOMHighResTimeStamp","timestamp")}} in the browser's performance entry buffer with the given name.
+
{{domxref("Performance.measure()")}}
+
Creates a named {{domxref("DOMHighResTimeStamp","timestamp")}} in the browser's performance entry buffer between two specified marks (known as the start mark and end mark, respectively).
+
{{domxref("Performance.now()")}}
+
Returns a {{domxref("DOMHighResTimeStamp")}} representing the amount of milliseconds elapsed since a reference instant.
+
{{domxref("Performance.setFrameTimingBufferSize()")}}
+
TBD
+
{{domxref("Performance.setResourceTimingBufferSize()")}}
+
Sets the browser's resource timing buffer size to the specified number of "resource" {{domxref("PerformanceEntry.entryType","type")}} {{domxref("PerformanceEntry","performance entry")}} objects.
+
{{domxref("Performance.toJSON()")}}
+
Is a jsonizer returning a json object representing the Performance object.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time Level 2', '#the-performance-interface', 'toJSON()')}}{{Spec2('Highres Time Level 2')}}Defines toJson() method.
{{SpecName('Highres Time', '#the-performance-interface', 'Performance')}}{{Spec2('Highres Time')}}Defines now() method.
{{SpecName('Navigation Timing', '#sec-window.performance-attribute', 'Performance')}}{{Spec2('Navigation Timing')}}Defines timing and navigation properties.
{{SpecName('Performance Timeline Level 2', '#extensions-to-the-performance-interface', 'Performance extensions')}}{{Spec2('Performance Timeline Level 2')}}Changes getEntries() interface.
{{SpecName('Performance Timeline', '#sec-window.performance-attribute', 'Performance extensions')}}{{Spec2('Performance Timeline')}}Defines getEntries(), getEntriesByType() and getEntriesByName() methods.
{{SpecName('Resource Timing', '#extensions-performance-interface', 'Performance extensions')}}{{Spec2('Resource Timing')}}Defines clearResourceTimings() and setResourceTimingBufferSize() methods and the onresourcetimingbufferfull property.
{{SpecName('User Timing Level 2', '#extensions-performance-interface', 'Performance extensions')}}{{Spec2('User Timing Level 2')}}Clarifies mark(), clearMark(), measure() and clearMeasure() methods.
{{SpecName('User Timing', '#extensions-performance-interface', 'Performance extensions')}}{{Spec2('User Timing')}}Defines mark(), clearMark(), measure() and clearMeasure() methods.
{{SpecName('Frame Timing', '#extensions-performance-interface','Performance extensions')}}{{Spec2('User Timing')}}Defines clearFrameTimings(), setFrameTimingBufferSize(), and onframetimingbufferfull methods.
+ +

Browser compatibility

+ +
+
+ + +

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

+
+
diff --git a/files/pt-br/web/api/performance/now/index.html b/files/pt-br/web/api/performance/now/index.html new file mode 100644 index 0000000000..b6539ebebe --- /dev/null +++ b/files/pt-br/web/api/performance/now/index.html @@ -0,0 +1,160 @@ +--- +title: performance.now() +slug: Web/API/Performance/now +translation_of: Web/API/Performance/now +--- +
{{APIRef("High Resolution Timing")}}
+ +

O método performance.now() retorna {{domxref("DOMHighResTimeStamp")}}, medido em milisegundos, com precisão de cinco milésimos de milissegundo (5 microsegundos).

+ +

O valor retornado representa o tempo decorrido desde o time origin (the {{domxref("PerformanceTiming.navigationStart")}} property). Em um web worker, o tempo inicial é o momento em que o contexto da execução(e.g. thread ou processo) é criado. Em uma janela, é o tempo em que o usuário iniciou a navegação neste documento. Tenha em mente que:

+ + + +

Sintaxe

+ +
t = performance.now();
+ +

Exemplo

+ +
var t0 = performance.now();
+doSomething();
+var t1 = performance.now();
+console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
+
+ +

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

+ +

Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time Level 2', '#dom-performance-now', 'performance.now()')}}{{Spec2('Highres Time Level 2')}}Stricter definitions of interfaces and types.
{{SpecName('Highres Time', '#dom-performance-now', 'performance.now()')}}{{Spec2('Highres Time')}}Initial definition
+ +

Compatibilidade de Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("20.0")}} {{property_prefix("webkit")}}
+ {{CompatChrome("24.0")}} [1]
{{CompatVersionUnknown}}{{CompatGeckoDesktop("15.0")}}10.0{{CompatOpera("15.0")}}{{CompatSafari("8.0")}}
on Web workers{{CompatChrome("33")}}{{CompatUnknown}}{{CompatGeckoDesktop("34.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
now() in a dedicated worker is now separate from the main context's now().{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("45.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatAndroid("4.0")}}{{CompatChrome("25.0")}}{{CompatVersionUnknown}}{{CompatGeckoMobile("15.0")}}10.0{{CompatNo}}9{{CompatChrome("25.0")}}
on Web workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("34.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
now() in a dedicated worker is now separate from the main context's now().{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("45.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Windows versions of Chrome 20 through 33 return performance.now() only to millisecond precision.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/performance/tojson/index.html b/files/pt-br/web/api/performance/tojson/index.html new file mode 100644 index 0000000000..2dac99f0f5 --- /dev/null +++ b/files/pt-br/web/api/performance/tojson/index.html @@ -0,0 +1,61 @@ +--- +title: Performance.toJSON() +slug: Web/API/Performance/toJSON +translation_of: Web/API/Performance/toJSON +--- +
{{APIRef("High Resolution Timing")}}
+ +

O método toJSON() da interface {{domxref("Performance")}} é um serializador padrão: Ele retorna uma representação em JSON das propriedades do objeto performance.

+ +

Sintaxe

+ +
minhaPerf = performance.toJSON()
+
+ +

Argumentos

+ +
+
Nenhum
+
 
+
+ +

Valor de retorno

+ +
+
minhaPerf
+
Um objeto JSON que é a serialização do objeto {{domxref("Performance")}}.
+
+ +

Exemplo

+ +
var js;
+js = window.performance.toJSON();
+console.log("json = " + JSON.stringify(js));
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time Level 2', '#the-performance-interface', 'toJSON() serializer')}}{{Spec2('Highres Time Level 2')}}Define toJson().
+ +

Compatibilidade de navegadores

+ +
+
+ + +

{{Compat("api.Performance.toJSON")}}

+
+
diff --git a/files/pt-br/web/api/positionoptions/index.html b/files/pt-br/web/api/positionoptions/index.html new file mode 100644 index 0000000000..5e7012e976 --- /dev/null +++ b/files/pt-br/web/api/positionoptions/index.html @@ -0,0 +1,109 @@ +--- +title: PositionOptions +slug: Web/API/PositionOptions +translation_of: Web/API/PositionOptions +--- +
{{APIRef("Geolocation API")}}
+ +
 
+ +
A interface PositionOptions consiste em um objeto que contém propriedades opcionais para passar como um parâmetro de {{domxref("Geolocation.getCurrentPosition()")}} e {{domxref("Geolocation.watchPosition()")}}.
+ +
 
+ +

Propriedades

+ +

A interface PositionOptions não herda qualquer propriedade.

+ +
+
{{domxref("PositionOptions.enableHighAccuracy")}}
+
É um {{domxref("Boolean")}} que indica se a aplicação deve receber os melhores (mais exatos) resultados possíveis. Se o valor for true e o dispositivo puder disponibilizar uma posição mais exata, ele o fará. Note que isto pode resultar em respostas mais lentas ou aumentar o consumo de bateria. (GPS em um dispositivo mobile). Se o valor for false, o dispositivo toma a liberdade de salvar os recursos respondendo mais rapidamente e/ou utilizando menos bateria. Default: false
+
{{domxref("PositionOptions.timeout")}}
+
É um valor long positivo que representa o tamanho máximo do tempo (em milissegundos) que o dispositivo deve levar para retornar uma posição. O valor default é Infinity, o que significa que getCurrentPosition() não terá retorno até que a posição esteja disponível.
+
{{domxref("PositionOptions.maximumAge")}}
+
É um valor long positivo indicando o valor máximo em milissegundos de uma possível posição em cache aceitável para retornar. Se o valor for 0, significa que o dispositivo não deve utilizar uma posição em cache e deve tentar obter a posição atual real. Se o valor for Infinity o dispositivo deve retornar uma posição em cache, independente de seu tempo de expiração. Default: 0.
+
+ +

Métodos

+ +

A interface PositionOptions  não implementa ou herda nenhum método.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#positionoptions', 'PositionOptions')}}{{Spec2('Geolocation')}}Initial definition
+ + + +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{CompatGeckoDesktop("1.9.1")}}910.60
+ {{CompatNo}} 15.0
+ 16.0
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("4")}}{{CompatUnknown}}10.60{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/processinginstruction/index.html b/files/pt-br/web/api/processinginstruction/index.html new file mode 100644 index 0000000000..94fdff0a2f --- /dev/null +++ b/files/pt-br/web/api/processinginstruction/index.html @@ -0,0 +1,39 @@ +--- +title: ProcessingInstruction +slug: Web/API/ProcessingInstruction +tags: + - API + - DOM +translation_of: Web/API/ProcessingInstruction +--- +
{{APIRef("DOM")}}
+ +

Uma ProcessingInstruction (Instrução de Processamento) incorpora instruções específicas de aplicações em XML que pode ser ignorada por outras aplicações que não as reconhece. Mesmo se um processador XML ignora as instruções de processamento, irá dá-los um lugar no DOM. 

+ +

Uma instrução de processamento é diferente de uma declaração XML, que fornece informação sobre o documento como por exemplo codificação de caracteres, e pode somente aparecer como o primeiro item em um documento.

+ +

Instruções de processamento definidas por usuário não podem começar com 'xml', pois estes são reservados (como <?xml-stylesheet ?>).

+ +

Instruções de processamento herdam métodos e propriedades do Node

+ +

{{InheritanceDiagram(700,70)}}

+ +

Atributos

+ + + +

Especificações

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/pushmanager/index.html b/files/pt-br/web/api/pushmanager/index.html new file mode 100644 index 0000000000..12c2452bae --- /dev/null +++ b/files/pt-br/web/api/pushmanager/index.html @@ -0,0 +1,187 @@ +--- +title: PushManager +slug: Web/API/PushManager +tags: + - API + - API de armazenamento + - Experimental + - Interface + - Referencia + - Service Workers + - Subir dados +translation_of: Web/API/PushManager +--- +

{{SeeCompatTable}}{{ApiRef("Push API")}}

+ +

A PushManagerinterface da API Push fornece uma maneira de receber notificações de servidores de terceiros, bem como solicitar URLs para notificações push.

+ +

Essa interface é acessada através da propriedade {{domxref ("ServiceWorkerRegistration.pushManager")}}.

+ +
+

Nota : Esta interface substitui a funcionalidade anteriormente oferecida pela interface obsoleta {{domxref ("PushRegistrationManager")}}.

+
+ +

Propriedades

+ +
+
{{domxref ("PushManager.supportedContentEncodings")}}
+
Retorna uma série de codificações de conteúdo suportadas que podem ser usadas para criptografar a carga útil de uma mensagem push.
+
+ +

Métodos

+ +
+
{{domxref ("PushManager.getSubscription ()")}}
+
Recupera uma assinatura de envio existente. Retorna uma {{jsxref ("Promise")}} que resolve um objeto {{domxref ("PushSubscription")}} contendo detalhes de uma assinatura existente. Se não existe uma subscrição existente, isso resolve um nullvalor.
+
{{domxref ("PushManager.permissionState ()")}}
+
Retorna uma {{jsxref ( "Promise")}} que resolve para o estado de permissão do atual {{domxref ( "PushManager")}}, que será um dos 'granted', 'denied'ou 'prompt'.
+
{{domxref ("PushManager.subscribe ()")}}
+
Assine um serviço push. Retorna uma {{jsxref ("Promise")}} que resolve um objeto {{domxref ("PushSubscription")}} contendo detalhes de uma inscrição de envio. Uma nova assinatura de envio é criada se o trabalhador de serviço atual não tiver uma assinatura existente.
+
+ +

Métodos depreciados

+ +
+
{{domxref ("PushManager.hasPermission ()")}} {{deprecated_inline}}
+
Retorna uma {{jsxref ( "Promise")}} que resolve para o PushPermissionStatusdo webapp requerente, que será um dos granted, deniedou default. Substituído por {{domxref ("PushManager.permissionState ()")}}.
+
{{domxref ("PushManager.register ()")}} {{deprecated_inline}}
+
Assina uma assinatura de envio. Substituído por {{domxref ("PushManager.subscribe ()")}}.
+
{{domxref ("PushManager.registrations ()")}} {{deprecated_inline}}
+
Recupera as assinaturas de envio existentes. Substituído por {{domxref ("PushManager.getSubscription ()")}}.
+
{{domxref ("PushManager.unregister ()")}} {{deprecated_inline}}
+
Anula e exclui um ponto final de assinatura especificado. Na API atualizada, uma assinatura não está registrada chamando o método {{domxref ("PushSubscription.unsubscribe ()")}}.
+
+ +

Exemplo

+ +
this.onpush = function(event) {
+  console.log(event.data);
+  // From here we can write the data to IndexedDB, send it to any open
+  // windows, display a notification, etc.
+}
+
+navigator.serviceWorker.register('serviceworker.js').then(
+  function(serviceWorkerRegistration) {
+    serviceWorkerRegistration.pushManager.subscribe().then(
+      function(pushSubscription) {
+        console.log(pushSubscription.subscriptionId);
+        console.log(pushSubscription.endpoint);
+        // The push subscription details needed by the application
+        // server are now available, and can be sent to it using,
+        // for example, an XMLHttpRequest.
+      }, function(error) {
+        // During development it often helps to log errors to the
+        // console. In a production environment it might make sense to
+        // also report information about errors back to the
+        // application server.
+        console.log(error);
+      }
+    );
+  });
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Push API','#pushmanager-interface','PushManager')}}{{Spec2('Push API')}}Definição inicial.
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerÓperaSafari (WebKit)
Suporte básico{{CompatChrome(42)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop (44.0)}} [1]{{CompatNo}}{{CompatOpera (29)}}{{CompatNo}}
supportedContentEncodings propriedade{{CompatChrome (60)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatOpera (47)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroid WebviewChrome para AndroidEdgeFirefox Mobile (Gecko)SO FirefoxIE MobileOpera MobileSafari Mobile
Suporte básico{{CompatChrome (42)}}{{CompatChrome (42)}}{{CompatVersionUnknown}}{{CompatGeckoMobile (48)}} [2]{{CompatNo}}{{CompatNo}}{{CompatOperaMobile (29)}}{{CompatNo}}
supportedContentEncodings propriedade{{CompatChrome (60)}}{{CompatChrome (60)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatOperaMobile (47)}}{{CompatNo}}
+
+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/randomsource/getrandomvalues/index.html b/files/pt-br/web/api/randomsource/getrandomvalues/index.html new file mode 100644 index 0000000000..7e54e933ed --- /dev/null +++ b/files/pt-br/web/api/randomsource/getrandomvalues/index.html @@ -0,0 +1,116 @@ +--- +title: RandomSource.getRandomValues() +slug: Web/API/RandomSource/getRandomValues +translation_of: Web/API/Crypto/getRandomValues +--- +

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

+ +

O método RandomSource.getRandomValues() permite que você obtenha valores criptográficos randômicos. O array passado como parametro é preenchido com números randômicos (randômicos no sentido criptográfico).

+ +

Para garantir performance suficiente, as implementações não estão usando um gerador de número randômico de verdade, mas estão usando um gerador de número pseudo-randômico alimentado com um valor com {{Glossary("entropia")}} suficiente. Os PRNG (pseudo-random number generator - gerador de número pseudo-randômico) usados diferem de uma implementação para a outra, mas são adequadas para usos criptográficos. As implementações precisam ter um valor de alimentação com entropia suficiente, como uma fonte de entropia a nível de sistema.

+ +

Sintaxe

+ +
cryptoObj.getRandomValues(typedArray);
+ +

Parâmetros

+ +
+
typedArray
+
É uma {{jsxref("TypedArray")}} de números inteiros, que pode ser {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}}, ou {{jsxref("Uint32Array")}}. Todos os elementos no array serão sobrescristos com números randômicos.
+
+ +

Exceções

+ + + +

Exemplo

+ +
/* assumindo que window.crypto.getRandomValues está disponível */
+
+var array = new Uint32Array(10);
+window.crypto.getRandomValues(array);
+
+console.log("Seus números da sorte são:");
+for (var i = 0; i < array.length; i++) {
+    console.log(array[i]);
+}
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Web Crypto API', '#RandomSource-method-getRandomValues')}}{{Spec2('Web Crypto API')}}Definição inicial
+ + + +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support11.0 {{ webkitbug("22049") }}21.011.015.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}23.021.011.0{{ CompatNo() }}6
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/randomsource/index.html b/files/pt-br/web/api/randomsource/index.html new file mode 100644 index 0000000000..8678075371 --- /dev/null +++ b/files/pt-br/web/api/randomsource/index.html @@ -0,0 +1,108 @@ +--- +title: RandomSource +slug: Web/API/RandomSource +tags: + - API + - Interface + - RandomSource + - Referencia + - Web Crypto API +translation_of: Web/API/Crypto/getRandomValues +--- +

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

+ +

RandomSource representa uma fonte criptografada segura de números aleatórios. É disponível via objeto {{domxref("Crypto")}} do objeto global: {{domxref("Window.crypto")}} em páginas Web, {{domxref("WorkerGlobalScope.crypto")}} em trabalhadores.

+ +

RandomSource não é uma interface e nenhum objeto deste tipo pode ser criado.

+ +

Propriedades

+ +

RandomSource não define ou herda nenhuma propriedade.

+ +
+
+ +

Métodos

+ +
+
{{ domxref("RandomSource.getRandomValues()") }}
+
Completa o {{ domxref("ArrayBufferView") }} com valores aleatoriamente criptografados.
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Crypto API', '#dfn-RandomSource')}}{{Spec2('Web Crypto API')}}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico11.0 {{ webkitbug("22049") }}{{CompatGeckoDesktop(21)}} [1]11.015.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatNo() }}23{{CompatGeckoMobile(21)}}{{ CompatNo() }}{{ CompatNo() }}6
+
+ +

[1] Apesar da RandomSource estar disponível apenas a partir da versão Firefox 26, ela já estava implementada na versão Firefox 21.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/request/index.html b/files/pt-br/web/api/request/index.html new file mode 100644 index 0000000000..3c29999829 --- /dev/null +++ b/files/pt-br/web/api/request/index.html @@ -0,0 +1,167 @@ +--- +title: Request +slug: Web/API/Request +tags: + - API + - Experimental + - Fetch + - Fetch API + - Requisições + - request +translation_of: Web/API/Request +--- +
{{APIRef("Fetch")}}
+ +

A interface Request da Fetch API representa uma requisição de recursos.

+ +

Você pode criar um novo objeto Request usando o construtor {{domxref("Request.Request()")}}, porém é mais provável que você encontre um objeto Request que seja retornado como resultado de outra operação de API, como um service worker {{domxref("FetchEvent.request")}}.

+ +

Construtor

+ +
+
{{domxref("Request.Request()")}}
+
Cria um novo objeto Request.
+
+ +

Propriedades

+ +
+
{{domxref("Request.method")}} {{readonlyInline}}
+
Contém o método da requisição (GET, POST etc.)
+
{{domxref("Request.url")}} {{readonlyInline}}
+
Contém a URL da requisição.
+
{{domxref("Request.headers")}} {{readonlyInline}}
+
Contém o objeto {{domxref("Headers")}} associado à requisição.
+
{{domxref("Request.context")}} {{readonlyInline}} {{deprecated_inline()}}
+
Contém o contexto da requisição (ex., audio, image, iframe etc.)
+
{{domxref("Request.referrer")}} {{readonlyInline}}
+
Contém a referência da requisição (ex., client).
+
{{domxref("Request.referrerPolicy")}} {{readonlyInline}}
+
Contém a política de referência da requisição (ex., no-referrer).
+
{{domxref("Request.mode")}} {{readonlyInline}}
+
Contém o modo da requisição (ex., cors, no-cors, same-origin, navigate.)
+
{{domxref("Request.credentials")}} {{readonlyInline}}
+
Contém a credencial da requisição (Ex., omit, same-origininclude).
+
{{domxref("Request.redirect")}} {{readonlyinline}}
+
Contém o modo de como os redirecionamentos serão tratados. Pode ser: follow, error ou manual.
+
{{domxref("Request.integrity")}} {{readonlyInline}}
+
Contém o valor da subresource integrity da requisição (ex., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
+
{{domxref("Request.cache")}} {{readonlyInline}}
+
Contém o modo de cache da requisição (ex., default, reload, no-cache).
+
+ +

Request implementa {{domxref("Body")}}, então também possui as seguintes propriedades disponíveis:

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
Um simples "getter" para ler o conteúdo do corpo através da interface {{domxref("ReadableStream")}}.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
Armazena um {{domxref("Boolean", "Booleano")}} que declara se o corpo da requisição já foi utilizado em uma resposta.
+
+ +

Métodos

+ +
+
{{domxref("Request.clone()")}}
+
Cria uma cópia atual do objeto Request.
+
+ +

Request implementa {{domxref("Body")}}, então também possui os seguintes métodos disponíveis:

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Retorna um objeto do tipo promise que resolve um {{domxref("ArrayBuffer")}} com a representação do corpo da requisição.
+
{{domxref("Body.blob()")}}
+
Retorna um objeto do tipo promise que resolve um {{domxref("Blob")}} com a representação do corpo da requisição.
+
{{domxref("Body.formData()")}}
+
Retorna um objeto do tipo promise que resolve um {{domxref("FormData")}} com a representação do corpo da requisição.
+
{{domxref("Body.json()")}}
+
Retorna um objeto do tipo promise que resolve um {{domxref("JSON")}} com a representação do corpo da requisição.
+
{{domxref("Body.text()")}}
+
Retorna um objeto do tipo promise que resolve um {{domxref("USVString")}} (texto) com a representação do corpo da requisição.
+
+ +
+

Nota: Os métodos de {{domxref("Body")}}  só poderão ser executadas apenas uma vez; As chamadas subsequentes serão resolvidas com strings/ArrayBuffers vazias.

+
+ +

Exemplos

+ +

No exemplo a seguir, nós criamos uma nova requisição utilizando o construtor Request() (para um arquivo de imagem no mesmo diretório do código) e, em seguida, nos retorna alguns valores das propriedades da requisição:

+ +
const myRequest = new Request('http://localhost/flowers.jpg');
+
+const myURL = myRequest.url; // http://localhost/flowers.jpg
+const myMethod = myRequest.method; // GET
+const myCred = myRequest.credentials; // omit
+
+ +

Você poderá, então, solicitar uma nova requisição passando o objeto Request como parâmetro para a chamada {{domxref("GlobalFetch.fetch()")}}, por exemplo:

+ +
fetch(myRequest)
+  .then(response => response.blob())
+  .then(blob => {
+    myImage.src = URL.createObjectURL(blob);
+  });
+ +

No exemplo a seguir, nós criamos uma nova requisição utilizando o construtor Request() com alguns valores iniciais e contendo o corpo para APIs que precisam processar essas informações:

+ +
const myRequest = new Request('http://localhost/api', {method: 'POST', body: '{"foo":"bar"}'});
+
+const myURL = myRequest.url; // http://localhost/api
+const myMethod = myRequest.method; // POST
+const myCred = myRequest.credentials; // omit
+const bodyUsed = myRequest.bodyUsed; // true
+
+ +
+

Nota: O tipo do corpo poderá ser apenas: {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("USVString")}} ou {{domxref("ReadableStream")}}. Para adicionar um objeto JSON ao corpo, é necessário converter esse objeto para string.

+
+ +

Você poderá, então, solicitar uma nova requisição passando o objeto Request como parâmetro para a chamada {{domxref("GlobalFetch.fetch()")}}, por exemplo, e poderá capturar a resposta da seguinte forma:

+ +
fetch(myRequest)
+  .then(response => {
+    if (response.status === 200) {
+      return response.json();
+    } else {
+      throw new Error('Ops! Houve um erro em nosso servidor.');
+    }
+  })
+  .then(response => {
+    console.debug(response);
+    // ...
+  }).catch(error => {
+    console.error(error);
+  });
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#request-class','Request')}}{{Spec2('Fetch')}}Initial definition
+ +

Compatibilidade entres navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/request/request/index.html b/files/pt-br/web/api/request/request/index.html new file mode 100644 index 0000000000..ac46f16fd3 --- /dev/null +++ b/files/pt-br/web/api/request/request/index.html @@ -0,0 +1,155 @@ +--- +title: Request() +slug: Web/API/Request/Request +translation_of: Web/API/Request/Request +--- +
{{APIRef("Fetch")}}
+ +

O construtor Request() cria um novo objeto {{domxref("Request")}}.

+ +

Sintaxe

+ +
var myRequest = new Request(input[, init]);
+ +

Parâmetros

+ +
+
input
+
Define o recurso que você deseja buscar. Isso pode ser: +
    +
  • Um {{domxref("USVString")}} contendo o URL direto do recurso que você deseja buscar.
  • +
  • Um objeto {{domxref("Request")}}, criando efetivamente uma cópia. Observe as seguintes atualizações comportamentais para reter a segurança e, ao mesmo tempo, tornar o construtor menos propenso a gerar exceções: +
      +
    • Se esse objeto existir em outra origem para a chamada do construtor, o {{domxref("Request.referrer")}} será removido.
    • +
    • Se esse objeto tiver um {{domxref("Request.mode")}} de navegação, o valor do modo será convertido para a mesma origem.
    • +
    +
  • +
+
+
init {{optional_inline}}
+
Um objeto de opções contendo quaisquer configurações personalizadas que você deseja aplicar à solicitação. As opções possíveis são: +
    +
  • method: O método de request, ex: GET, POST.
  • +
  • headers: Quaisquer cabeçalhos que você deseja adicionar à sua solicitação, contidos em um objeto {{domxref("Headers")}} ou em um objeto literal com valores de {{domxref("ByteString")}}.
  • +
  • body: Qualquer corpo que você deseja adicionar à sua solicitação: isso pode ser um {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("USVString")}}, ou objeto {{domxref("ReadableStream")}}. Observe que uma solicitação usando o método GET ou HEAD não pode ter um corpo.
  • +
  • mode: O modo que você deseja usar para a solicitação, por exemplo: cors, no-cors, same-origin, or navigate. O padrão é cors. No Chrome o padrão é no-cors antes do Chrome 47 e same-origin do Chrome 47 em diante.
  • +
  • credentials: As credenciais de solicitação que você deseja usar para a solicitação: omit, same-origin, ou include. O padrão é omit. No Chrome o padrão é same-origin antes do Chrome 47 e include do Chrome 47 em diante.
  • +
  • cache: O cache mode  que você deseja usar para a solicitação.
  • +
  • redirect: O modo de redirecionamento para usar: follow, error, or manual. No Chrome o padrão é follow (antes do Chrome 47 foi padronizado manual).
  • +
  • referrer: Um {{domxref("USVString")}} especificando no-referrer, client, ou uma URL. O padrão é client.
  • +
  • integrity: Contém o valor de integridade do sub-recurso da solicitação (exemplo: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
  • +
+
+
+ +

Erros

+ + + + + + + + + + + + + + +
TipoDescrição
TypeErrorDesde Firefox 43, Request() lançará um TypeError se o URL tiver credenciais, tal como http://user:password@example.com.
+ +

Exemplo

+ +

Em nosso exemplo Fetch Request (veja Fetch Request live) nós criamos um novo objeto Request usando o construtor, em seguida, busque-o usando uma chamada {{domxref("GlobalFetch.fetch")}}. Como estamos buscando uma imagem, executamos o {{domxref("Body.blob")}} na resposta para fornecer o tipo MIME adequado para que ela seja manipulada corretamente. Em seguida, criamos uma URL do objeto e a exibimos em um Elemento {{htmlelement("img")}}.

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  return response.blob();
+}).then(function(response) {
+  var objectURL = URL.createObjectURL(response);
+  myImage.src = objectURL;
+});
+ +

Em nosso Fetch Request with init example (veja Fetch Request init live) nós fazemos a mesma coisa, exceto que passamos em um objeto init quando invocamos fetch():

+ +
var myImage = document.querySelector('img');
+
+var myHeaders = new Headers();
+myHeaders.append('Content-Type', 'image/jpeg');
+
+var myInit = { method: 'GET',
+               headers: myHeaders,
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg',myInit);
+
+fetch(myRequest).then(function(response) {
+  ...
+});
+ +

Observe que você também pode passar o objeto init para a chamada fetch para obter o mesmo efeito, por exemplo:

+ +
fetch(myRequest,myInit).then(function(response) {
+  ...
+});
+ +

Você também pode usar um literal de objeto como headers em init.

+ +
var myInit = { method: 'GET',
+               headers: {
+                   'Content-Type': 'image/jpeg'
+               },
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg', myInit);
+
+ +

Você também pode passar um objeto {{domxref ("Request")}} para o construtor Request() para criar uma cópia do Request (isso é semelhante a chamar o método {{domxref("Request.clone", "clone()")}} .)

+ +
+
var copy = new Request(myRequest);
+
+
+ +
+

Nota: Este último uso é provavelmente útil apenas em ServiceWorkers.

+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Fetch','#dom-request','Request()')}}{{Spec2('Fetch')}} 
+ +

Compatibilidade de Browser

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/response/index.html b/files/pt-br/web/api/response/index.html new file mode 100644 index 0000000000..554edd15db --- /dev/null +++ b/files/pt-br/web/api/response/index.html @@ -0,0 +1,130 @@ +--- +title: Response +slug: Web/API/Response +tags: + - API + - Experimental + - Fetch + - Fetch API + - Interface + - Reference + - Referencia + - Response + - Resposta +translation_of: Web/API/Response +--- +
{{APIRef("Fetch API")}}
+ +

A interface Response da Fetch API representa a resposta para uma requisição.

+ +

Você pode criar um novo objeto Response usando o construtor {{domxref("Response.Response()")}}, porém é mais provável você encontrar um objeto Response sendo retornado como o resultado de uma outra operação da API, por exemplo um service worker {{domxref("Fetchevent.respondWith")}}, ou um simples {{domxref("GlobalFetch.fetch()")}}.

+ +

Construtor

+ +
+
{{domxref("Response.Response","Response()")}}
+
Cria um novo objeto Response.
+
+ +

Propriedades

+ +
+
{{domxref("Response.headers")}} {{readonlyinline}}
+
Contém o objeto {{domxref("Headers")}} associado à resposta.
+
{{domxref("Response.ok")}} {{readonlyinline}}
+
Contém um valor booleano indicando se a resposta foi bem sucedida ("status" no intervalo 200-299) ou não.
+
{{domxref("Response.redirected")}} {{ReadOnlyInline}}
+
Indica se a resposta é ou não o resultado de um redirecionamento; isto é, sua lista de URL tem mais de uma entrada.
+
{{domxref("Response.status")}} {{readonlyinline}}
+
Contém o código de "status" da resposta (ex., 200 para um sucesso).
+
{{domxref("Response.statusText")}} {{readonlyinline}}
+
Contém a mensagem de "status" correspondente ao código de "status" (ex., OK para 200).
+
{{domxref("Response.type")}} {{readonlyinline}}
+
Contém o tipo da resposta (ex., basic, cors).
+
{{domxref("Response.url")}} {{readonlyinline}}
+
Contém a URL de resposta.
+
{{domxref("Response.useFinalURL")}}
+
Contém um valor boleano indicando se essa é a URL final da resposta.
+
+ +

Response implementa {{domxref("Body")}}, por isso também tem as seguintes propriedades disponíveis:

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
Um simples "getter" para ler do conteúdo do corpo através da interface {{domxref("ReadableStream")}}.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
Armazena um {{domxref("Boolean")}} que indica se o corpo já foi utilizado em uma resposta.
+
+ +

Métodos

+ +
+
{{domxref("Response.clone()")}}
+
Cria uma cópia do objeto Response.
+
{{domxref("Response.error()")}}
+
Retorna um novo objeto Response associado a um erro de rede.
+
{{domxref("Response.redirect()")}}
+
Cria uma nova resposta com uma URL diferente.
+
+ +

Response implementa {{domxref("Body")}}, por isso também tem as seguintes propriedades disponíveis:

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Recebe um "stream" {{domxref("Response")}} e lê até a conclusão. Retorna uma "promise" que resolve com um  {{domxref("ArrayBuffer")}}.
+
{{domxref("Body.blob()")}}
+
Recebe um "stream" {{domxref("Response")}} e lê até a conclusão. Retorna uma "promise" que resolve com um {{domxref("Blob")}}.
+
{{domxref("Body.formData()")}}
+
Recebe um "stream" {{domxref("Response")}} e lê até a conclusão. Retorna uma "promise" que resolve com um objeto {{domxref("FormData")}}.
+
{{domxref("Body.json()")}}
+
Recebe um "stream" {{domxref("Response")}} e lê até a conclusão. Retorna uma "promise" que resolve com o resultado do parseamento do texto do corpo como {{jsxref("JSON")}}.
+
{{domxref("Body.text()")}}
+
Recebe um "stream" {{domxref("Response")}} e lê até a conclusão. Retorna uma "promise" que resolve com um {{domxref("USVString")}} (texto).
+
+ +

Exemplos

+ +

Em nosso exemplo básico fetch (executar exemplo live) nós usamos uma simples chamada fetch() para pegar uma imagem e exibi-la em uma tag {{htmlelement("img")}}. A chamada fetch() retorna uma "promise", que resolve com o objeto Response associado com o recurso da operação "fetch". Você irá notar que como estamos solicitando uma imagem, nós precisamos executar {{domxref("Body.blob")}} ({{domxref("Response")}} implementa o "body") para dar à resposta seu tipo MIME correto.

+ +
var myImage = document.querySelector('.my-image');
+fetch('flowers.jpg').then(function(response) {
+  return response.blob();
+}).then(function(blob) {
+  var objectURL = URL.createObjectURL(blob);
+  myImage.src = objectURL;
+});
+ +

Você também pode usar o construtor {{domxref("Response.Response()")}} para criar seu objeto Response personalizado:

+ +
var myResponse = new Response();
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Fetch','#response-class','Response')}}{{Spec2('Fetch')}}Initial definition
+ +

Compatibilidade entre Navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/rtccertificate/index.html b/files/pt-br/web/api/rtccertificate/index.html new file mode 100644 index 0000000000..a0ecf39c65 --- /dev/null +++ b/files/pt-br/web/api/rtccertificate/index.html @@ -0,0 +1,47 @@ +--- +title: RTCCertificate +slug: Web/API/RTCCertificate +tags: + - API + - Comunicação em tempo-real + - Interface + - RTCCertificate + - Refenrência + - WebRTC +translation_of: Web/API/RTCCertificate +--- +

{{APIRef("WebRTC")}}

+ +

A interface da WebRTC API fornece um objeto representando um certificado que uma {{domxref("RTCPeerConnection")}} usa para autênticar.

+ +

Propriedades

+ +
+
{{domxref("RTCCertificate.expires")}} {{readonlyinline}}
+
Retorna a data de expiração do certificado.
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}definição inicial.
+ +

Compatibilidade de Browser

+ +
+ + +

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

+
diff --git a/files/pt-br/web/api/rtcdatachannel/index.html b/files/pt-br/web/api/rtcdatachannel/index.html new file mode 100644 index 0000000000..27514ba598 --- /dev/null +++ b/files/pt-br/web/api/rtcdatachannel/index.html @@ -0,0 +1,130 @@ +--- +title: RTCDataChannel +slug: Web/API/RTCDataChannel +tags: + - Compatibilidade + - Navegadores + - Referencia +translation_of: Web/API/RTCDataChannel +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

A interface RTCDataChannel representa um canal de rede que pode ser usado para transferências bidirecionais de dados arbitrários de ponto a ponto. Todo canal de dados está associado a {{domxref("RTCPeerConnection")}}, e cada conexão de pares pode ter até um máximo teórico de 65,534 canais de dados (o limite real pode variar de navegador para navegador).

+ +

Para criar um canal de dados e pedir a um ponto remoto para se juntar a você, chame os metodos {{domxref("RTCPeerConnection")}}'s {{domxref("RTCPeerConnection.createDataChannel", "createDataChannel()")}}.  O interlocutor que está sendo convidado a trocar dados recebe um evento {{event("datachannel")}} (que possui o tipo {{domxref("RTCDataChannelEvent")}}) para informá-lo de que o canal de dados foi adicionado à conexão.

+ +

{{InterfaceOverview("WebRTC")}}

+ +

Exemplo

+ +
var pc = new RTCPeerConnection();
+var dc = pc.createDataChannel("my channel");
+
+dc.onmessage = function (event) {
+  console.log("received: " + event.data);
+};
+
+dc.onopen = function () {
+  console.log("datachannel open");
+};
+
+dc.onclose = function () {
+  console.log("datachannel close");
+};
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('WebRTC 1.0', '#idl-def-RTCDataChannel', 'RTCDataChannel') }}{{ Spec2('WebRTC 1.0') }}Especificação inicial
+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown }}{{ CompatGeckoDesktop(22) }} [1]{{ CompatNo }}{{ CompatVersionUnknown }}{{ CompatUnknown }}
onbufferedamountlow{{CompatChrome(56)}}{{ CompatNo }}{{ CompatNo }}{{CompatOpera(43)}}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(29)}}{{CompatChrome(29)}}{{ CompatGeckoMobile(22) }} [1]{{ CompatNo }}{{ CompatVersionUnknown }}{{ CompatNo }}
onbufferedamountlow{{CompatChrome(56)}}{{CompatChrome(56)}}{{ CompatNo }}{{CompatUnknown}}{{CompatOperaMobile(43)}}{{CompatUnknown}}
+
+ +

[1] A interface é chamada DataChannel e não RTCDataChannel no Firefox. No entanto, uma ligação foi implementada desde o Firefox 24 para que qualquer um dos nomes funcione.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/rtcicetransport/index.html b/files/pt-br/web/api/rtcicetransport/index.html new file mode 100644 index 0000000000..008822d95c --- /dev/null +++ b/files/pt-br/web/api/rtcicetransport/index.html @@ -0,0 +1,91 @@ +--- +title: RTCIceTransport +slug: Web/API/RTCIceTransport +tags: + - API + - Audio + - Interface + - RTCIceTransport + - Referencia + - Video + - WebRTC + - WebRTC API + - rtc +translation_of: Web/API/RTCIceTransport +--- +
{{APIRef("WebRTC")}}
+ +

A interface RTCIceTransport fornece informação a respeito da camada de transporte {{Glossary("ICE")}} na qual os dados estão sendo enviados e recebidos. Isso é particulamente útil se você precisa acessar as informações de estado da conexão.

+ +

Propriedades

+ +

A interface RTCIceTransport herda propriedades de sua interface pai, {{domxref("EventTarget")}}. ele também oferta as seguintes propriedades:

+ +
+
{{domxref("RTCIceTransport.component", "component")}} {{ReadOnlyInline}}
+
O componente ICE que esta sendo usado pela transporte. O valor é uma das strings do {{domxref("RTCIceTransport")}} tipo enumerável: {{Glossary("RTP", '"RTP"')}} ou "RTSP".
+
{{domxref("RTCIceTransport.gatheringState", "gatheringState")}} {{ReadOnlyInline}}
+
O {{domxref("DOMString")}} indica em qual estado de recolhimento o agente ICE esta atualmente. O valor é um dos incluidos no {{domxref("RTCIceGathererState")}} tipo enumerável: "new", "gathering", ou "complete".
+
{{domxref("RTCIceTransport.role", "role")}} {{ReadOnlyInline}}
+
Retorna uma {{domxref("DOMString")}} cujo valor é um membro do tipo enumerável {{domxref("RTCIceRole")}}: "controlling" ou "controlled"; Isso indica se o agente ICE é aquele que toma a decisão final quanto ao par candidato a ser usado ou não.
+
{{domxref("RTCIceTransport.state", "state")}} {{ReadOnlyInline}}
+
O {{domxref("DOMString")}} indica qual o atual estado do agente ICE. O valor do state pode ser usado para determinar se o agente ICE fez uma conecxão inicial usando uma par de candidatos viável ("connected"), fez a seleção final do par de candidatos ("completed"), ou em um estado de erro ("failed"), além de outros estados. Veja o tipo enumerável {{domxref("RTCIceTransportState")}} para uma lista completa de estados.
+
+ +

Métodos

+ +

Também inclui métodos da interface pai {{domxref("EventTarget")}}.

+ +
+
{{domxref("RTCIceTransport.getLocalCandidates", "getLocalCandidates()")}}
+
Retorna um array de objetos {{domxref("RTCIceCandidate")}}, cada descrevendo um dos candidatos ICE que foram reunidos para o dispositivo local até o momento. Esses são os mesmos candidatos que já foram enviados para o peer remoto, enviando um evento {{event("icecandidate")}} ao {{domxref("RTCPeerConnection")}} para transmissão.
+
{{domxref("RTCIceTransport.getLocalParameters", "getLocalParameters()")}}
+
Retorna o objeto {{domxref("RTCIceParameters")}} descrevendo o parâmetro ICE estabelecido através de uma ligação ao método {{domxref("RTCPeerConnection.setLocalDescription()")}}. Retorna null se os parâmetros ainda não foram recebidos.
+
{{domxref("RTCIceTransport.getRemoteCandidates", "getRemoteCandidates()")}}
+
Retorna um array de objetos {{domxref("RTCIceCandidate")}}, um para cada candidato do dispositivo remoto, que foram recebidos pelo local final da {{domxref("RTCPeerConnection")}} e entrega ao ICE através da chamada {{domxref("RTCPeerConnection.addIceCandidate()", "addIceCandidate()")}}.
+
{{domxref("RTCIceTransport.getRemoteParameters", "getRemoteParameters()")}}
+
Retorna um objeto {{domxref("RTCIceParameters")}} contendo os parâmetros ICE para o dispositivo remoto, como definido por uma chamada para {{domxref("RTCPeerConnection.setRemoteDescription()")}}. Se setRemoteDescription() não foi chamada ainda, o retorno será null.
+
{{domxref("RTCIceTransport.getSelectedCandidatePair", "getSelectedCandidatePair()")}}
+
Retorna um objeto {{domxref("RTCIceCandidatePair")}} que identifica os dois candidatos — um para cada conexão — que foram selecionados até o momento. É possível que um par melhor sejá encontrado e selecionado posteriormente; Se você precisar acompanhar isso, veja o evento {{event("selectedcandidatepairchange")}}. Se nenhum par de candidatos foi selecionado ainda o valor retornado será null.
+
+ +

Eventos

+ +

Escute esses eventos usando {{domxref("EventTarget.addEventListener", "addEventListener()")}} ou atribuindo um event listener para oneventname propriedade dessa interface.

+ +
+
{{domxref("RTCIceTransport.gatheringstatechange_event", "gatheringstatechange")}}
+
Enviado ao objeto {{domxref("RTCIceTransport")}} para indicar que o valor da propriedade {{domxref("RTCIceTransport.gatheringState", "gatheringState")}} foi alterado, indicando uma mudança no processo de negociação de candidatos ICE deste transporte.
+ Também esta disponível através da propriedade event handler {{domxref("RTCIceTransport.ongatheringstatechange", "ongatheringstatechange")}}.
+
{{domxref("RTCIceTransport.selectedcandidatepairchange_event", "selectedcandidatepairchange")}}
+
Enviado para o RTCIceTransport quando um novo, melhor par de candidatos foi selecionado para descrever a conectividade entre os dois peers. Isso pode ocorrer durante a negotiação ou a renegociação, incluindo depois de um ICE restart, que reusa os objetos RTCIceTransport existentes. O par de candidatos atuais pode ser obtido usando {{domxref("RTCIceTransport.getSelectedCandidatePair", "getSelectedCandidatePair()")}}.
+ Também esta disponível através da propriedade event handler {{domxref("RTCIceTransport.onselectedcandidatepairchange", "onselectedcandidatepairchange")}}.
+
{{domxref("RTCIceTransport.statechange_event", "statechange")}}
+
Enviado par a instancia do RTCIceTransport quando o valor da propriedade {{domxref("RTCIceTransport.state", "state")}} foi alterada, indicando que o processo de recolhimento ICE mudou de estado.
+ Também esta disponível através da propriedade event handler {{domxref("RTCIceTransport.onstatechange", "onstatechange")}}.
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('WebRTC 1.0', '#dom-rtcicetransport', 'RTCIceTransport')}}{{Spec2('WebRTC 1.0')}}Definição initial.
+ +

Compatibilidade de Browser

+ +
+ + +

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

+
diff --git a/files/pt-br/web/api/rtcpeerconnection/connectionstate/index.html b/files/pt-br/web/api/rtcpeerconnection/connectionstate/index.html new file mode 100644 index 0000000000..102b310ecd --- /dev/null +++ b/files/pt-br/web/api/rtcpeerconnection/connectionstate/index.html @@ -0,0 +1,64 @@ +--- +title: RTCPeerConnection.connectionState +slug: Web/API/RTCPeerConnection/connectionState +translation_of: Web/API/RTCPeerConnection/connectionState +--- +

{{APIRef("WebRTC")}}

+ +

A propriedade connectionState do tipo somente leitura da interface {{domxref("RTCPeerConnection")}} indica o estado atual da conexão em par, devolvendo um valor em string específicado por um enum {{domxref("RTCPeerConnection")}}.

+ +

Quando o valor da propriedade muda, o evento {{event("connectionstatechange")}} é enviado para a intância {{domxref("RTCPeerConnection")}}.

+ + + +

Syntax

+ +
var connectionState = RTCPeerConnection.connectionState;
+ +

Value

+ +

O estado atual da conexão, como um valor do enum RTCPeerConnectionState.

+ +

{{page("/en-US/docs/Web/API/RTCPeerConnection", "RTCPeerConnectionState enum", 0, 1)}}

+ +

Example

+ +
var pc = new RTCPeerConnection(configuration);
+
+/* ... */
+
+var connectionState = pc.connectionState;
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-connectionState', 'RTCPeerConnection.connectionState') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

Browser compatibility

+ + + +

{{Compat("api.RTCPeerConnection.connectionState")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/rtcpeerconnection/index.html b/files/pt-br/web/api/rtcpeerconnection/index.html new file mode 100644 index 0000000000..b7cd9c92fb --- /dev/null +++ b/files/pt-br/web/api/rtcpeerconnection/index.html @@ -0,0 +1,360 @@ +--- +title: RTCPeerConnection +slug: Web/API/RTCPeerConnection +translation_of: Web/API/RTCPeerConnection +--- +
{{APIRef('WebRTC')}}
+ +

A interface RTCPeerConnection cria uma conexão WebRTC entre um computador local e um ponto remoto. Esta interface fornece métodos que possibilitam a conexão a um ponto remoto, mantendo e monitorando a conexão, e fechando-a quando não for mais necessária.

+ +

{{InheritanceDiagram}}

+ +

{{InterfaceOverview("WebRTC")}}

+ +

Método obsoleto

+ +

O método a seugir está obsoleto há muito tempo e nunca foi implementado nos principais navegadores.

+ +
+
{{domxref("RTCPeerConnection.createDTMFSender()")}} {{obsolete_inline}}
+
Cria um novo {{domxref("RTCDTMFSender")}},associado ao específico {{domxref("MediaStreamTrack")}}, que irá permitir enviar {{Glossary("DTMF")}} sinal de telefone pela conexão
+
+ +

Eventos

+ +

Monitore esses eventos utilizando {{domxref("EventTarget.addEventListener", "addEventListener()")}} ou atribuindo um ouvinte de evento à propriedade oneventname dessa interface.

+ + + +
+
{{domxref("RTCPeerConnection.connectionstatechange_event", "connectionstatechange")}}
+
Enviado ao objeto RTCPeerConnection quando o status de conectividade geral do RTCPeerConnection é alterado.
+ Também disponível através da propriedade do manipulador de eventos {{domxref ("RTCPeerConnection.onconnectionstatechange", "onconnectionstatechange")}}.
+
+ + + + + +
+
{{domxref("RTCPeerConnection.datachannel_event", "datachannel")}}
+
Sent to the RTCPeerConnection object when the remote peer adds an {{domxref("RTCDataChannel")}} to the connection.
+ Also available through the {{domxref("RTCPeerConnection.ondatachannel", "ondatachannel")}} event handler property.
+
{{domxref("RTCPeerConnection.icecandidate_event", "icecandidate")}}
+
Sent to the object when a new ICE candidate arrives during negotiation.
+ Also available using the {{domxref("RTCPeerConnection.onicecandidate", "onicecandidate")}} event handler property.
+
{{domxref("RTCPeerConnection.iceconnectionstatechange_event", "iceconnectionstatechange")}}
+
Sent to the RTCPeerConnection when the state of the ICE connection changes, such as when it disconnects.
+ Also available using the {{domxref("RTCPeerConnection.oniceconnectionstatechange", "oniceconnectionstatechange")}} event handler property.
+
{{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}}
+
Sent to the RTCPeerConnection when it's time to perform ICE negotiation. This can happen both when first opening a connection as well as any time it's necessary to adapt to changing network conditions.
+ Also available using the {{domxref("RTCPeerConnection.onnegotiationneeded", "onnegotiationneeded")}} event handler property.
+
{{domxref("RTCPeerConnection.icecandidate_event", "icecandidate")}}
+
Sent to the peer connection to request that the specified candidate be transmitted to the remote peer.
+ Also available through the {{domxref("RTCPeerConnection.onicecandidate", "onicecandidate")}} event handler property.
+
{{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}}
+
Sent to the RTCPeerConnection when negotiation or renegotiation of the ICE connection needs to be performed. The receiver should respond by creating an offer and sending it to the other peer.
+ Also available as the {{domxref("RTCPeerConnection.onnegotiationneeded", "onnegotiationneeded")}} event handler property.
+
{{domxref("RTCPeerConnection.signalingstatechange_event", "signalingstatechange")}}
+
The signalingstatechange event is sent to the RTCPeerConnection when the connection's ICE signaling state changes.
+ Also available through the {{domxref("RTCPeerConnection.onsignalingstatechange", "onsignalingstatechange")}} event handler property.
+
{{domxref("RTCPeerConnection.track_event", "track")}}
+
The track event is sent after a new track has been added to one of the {{domxref("RTCRtpReceiver")}} instances which comprise the connection.
+ Available as the {{domxref("RTCPeerConnection.ontrack", "ontrack")}} event handler property.
+
+ +

Obsolete events

+ +
+
{{domxref("RTCPeerConnection.addstream_event", "addstream")}} {{obsolete_inline}}
+
Sent when a new {{domxref("MediaStream")}} has been added to the connection. Instead of watching for this obsolete event, you should watch each for {{domxref("RTCPeerConnection.track_event", "track")}} events; one is sent for each {{domxref("MediaStreamTrack")}} added to the connection.
+ Available as the {{domxref("RTCPeerConnection.onaddstream", "onaddstream")}} event handler property.
+
{{domxref("RTCPeerConnection.identityresult_event", "identityresult")}} {{obsolete_inline}}
+
In old versions of the WebRTC specification, this event was used to indicate that an identity assertion is available. Now, you should instead wait for a the promise returned by {{domxref("RTCPeerConnection.peerIdentity", "peerIdentity")}} to resolve with an identity.
+ Also available using the {{domxref("RTCPeerConnection.onidentityresult", "onidentityresult")}} event handler property.
+
{{domxref("RTCPeerConnection.idpassertionerror_event", "idpassertionerror")}} {{obsolete_inline}}
+
In old versions of the WebRTC specification, this event was used to indicate that an error occurred while attempting to generate an identity assertion. Now, you should instead wait for a the promise returned by {{domxref("RTCPeerConnection.peerIdentity", "peerIdentity")}} to be rejected with an error.
+ Also available as the {{domxref("RTCPeerConnection.onidpassertionerror", "onidpinsertionerror")}} event handler property.
+
{{domxref("RTCPeerConnection.idpvalidationerror_event", "idpvalidationerror")}} {{obsolete_inline}}
+
In old versions of the WebRTC specification, this event was used to indicate that an error occurred while attempting to validate an identity assertion. Now, you should instead wait for a the promise returned by {{domxref("RTCPeerConnection.peerIdentity", "peerIdentity")}} to be rejected with an error.
+ Also available using the {{domxref("RTCPeerConnection.onpeeridentity", "onpeerdentity")}} event handler property.
+
{{domxref("RTCPeerConnection.peeridentity_event", "peeridentity")}} {{obsolete_inline}}
+
In old versions of the WebRTC specification, this event was used to deliver a received identity. Now, you should instead wait for a the promise returned by {{domxref("RTCPeerConnection.peerIdentity", "peerIdentity")}} to resolve with an identity.
+
{{domxref("RTCPeerConnection.removestream_event", "removestream")}} {{obsolete_inline}}
+
Sent to the RTCPeerConnection when a {{domxref("MediaStream")}} is removed from the connection. Instead of watching for this obsolete event, you should watch each stream for {{domxref("MediaStream.removetrack_event", "removetrack")}} events on each stream within the RTCPeerConnection.
+ Also available as the {{domxref("RTCPeerConnection.onremovestream", "onaddstream")}} event handler property.
+
+ +

Constants

+ +

RTCBundlePolicy enum

+ +

The RTCBundlePolicy enum defines string constants which are used to request a specific policy for gathering ICE candidates if the remote peer isn't compatible with the SDP BUNDLE standard for bundling multiple media streams on a single transport link.

+ +
+

Note: In technical terms, a BUNDLE lets all media flow between two peers flow across a single 5-tuple; that is, from the same IP and port on one peer to the same IP and port on the other peer, using the same transport protocol.

+
+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
"balanced"On BUNDLE-aware connections, the ICE agent should gather candidates for all of the media types in use (audio, video, and data). Otherwise, the ICE agent should only negotiate one audio and video track on separate transports.
"max-compat"The ICE agent should gather candidates for each track, using separate transports to negotiate all media tracks for connections which aren't BUNDLE-compatible.
"max-bundle"The ICE agent should gather candidates for just one track. If the connection isn't BUNDLE-compatible, then the ICE agent should negotiate just one media track.
+ +

RTCIceConnectionState enum

+ +

The RTCIceConnectionState enum defines the string constants used to describe the current state of the ICE agent and its connection to the ICE server (that is, the {{Glossary("STUN")}} or {{Glossary("TURN")}} server).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
"new"The ICE agent is gathering addresses or is waiting to be given remote candidates through calls to {{domxref("RTCPeerConnection.addIceCandidate()")}} (or both).
"checking"The ICE agent has been given one or more remote candidates and is checking pairs of local and remote candidates against one another to try to find a compatible match, but has not yet found a pair which will allow the peer connection to be made. It's possible that gathering of candidates is also still underway.
"connected"A usable pairing of local and remote candidates has been found for all components of the connection, and the connection has been established. It's possible that gathering is still underway, and it's also possible that the ICE agent is still checking candidates against one another looking for a better connection to use.
"completed"The ICE agent has finished gathering candidates, has checked all pairs against one another, and has found a connection for all components.
"failed"The ICE candidate has checked all candidates pairs against one another and has failed to find compatible matches for all components of the connection. It is, however, possible that the ICE agent did find compatible connections for some components.
"disconnected"Checks to ensure that components are still connected failed for at least one component of the {{domxref("RTCPeerConnection")}}. This is a less stringent test than "failed" and may trigger intermittently and resolve just as spontaneously on less reliable networks, or during temporary disconnections. When the problem resolves, the connection may return to the "connected" state.
"closed"The ICE agent for this {{domxref("RTCPeerConnection")}} has shut down and is no longer handling requests.
+ +

RTCIceGatheringState enum

+ +

The RTCIceGatheringState enum defines string constants which reflect the current status of ICE gathering, as returned using the {{domxref("RTCPeerConnection.iceGatheringState")}} property. You can detect when this value changes by watching for an event of type {{event("icegatheringstatechange")}}.

+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
"new"The peer connection was just created and hasn't done any networking yet.
"gathering"The ICE agent is in the process of gathering candidates for the connection.
"complete"The ICE agent has finished gathering candidates. If something happens that requires collecting new candidates, such as a new interface being added or the addition of a new ICE server, the state will revert to "gathering" to gather those candidates.
+ +

RTCIceTransportPolicy enum

+ +

The RTCIceTransportPolicy enum defines string constants which can be used to limit the transport policies of the ICE candidates to be considered during the connection process.

+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
"all"All ICE candidates will be considered.
"public" {{obsolete_inline}}Only ICE candidates with public IP addresses will be considered. Removed from the specification's May 13, 2016 working draft.
"relay"Only ICE candidates whose IP addresses are being relayed, such as those being passed through a TURN server, will be considered.
+ +

RTCPeerConnectionState enum

+ +

The RTCPeerConnectionState enum defines string constants which describe states in which the RTCPeerConnection may be. These values are returned by the {{domxref("RTCPeerConnection.connectionState", "connectionState")}} property. This state essentially represents the aggregate state of all ICE transports (which are of type {{domxref("RTCIceTransport")}} or {{domxref("RTCDtlsTransport")}}) being used by the connection.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
"new"At least one of the connection's ICE transports ({{domxref("RTCIceTransport")}}s or {{domxref("RTCDtlsTransport")}}s) are in the "new" state, and none of them are in one of the following states: "connecting", "checking", "failed", or "disconnected", or all of the connection's transports are in the "closed" state.
"connecting"One or more of the ICE transports are currently in the process of establishing a connection; that is, their RTCIceConnectionState is either "checking" or "connected", and no transports are in the "failed" state. <<< Make this a link once I know where that will be documented
"connected"Every ICE transport used by the connection is either in use (state "connected" or "completed") or is closed (state "closed"); in addition, at least one transport is either "connected" or "completed".
"disconnected"At least one of the ICE transports for the connection is in the "disconnected" state and none of the other transports are in the state "failed", "connecting", or "checking".
"failed"One or more of the ICE transports on the connection is in the "failed" state.
"closed" +

The RTCPeerConnection is closed.

+ +

This value was in the RTCSignalingState enum (and therefore found by reading the value of the {{domxref("RTCPeerConnection.signalingState", "signalingState")}}) property until the May 13, 2016 draft of the specification.

+
+ +

RTCRtcpMuxPolicy enum

+ +

The RTCRtcpMuxPolicy enum defines string constants which specify what ICE candidates are gathered to support non-multiplexed RTCP. <<<add a link to info about multiplexed RTCP.

+ + + + + + + + + + + + + + + + + + +
ConstantDescription
"negotiate"Instructs the ICE agent to gather both {{Glossary("RTP")}} and {{Glossary("RTCP")}} candidates. If the remote peer can multiplex RTCP, then RTCP candidates are multiplexed atop the corresponding RTP candidates. Otherwise, both the RTP and RTCP candidates are returned, separately.
"require"Tells the ICE agent to gather ICE candidates for only RTP, and to multiplex RTCP atop them. If the remote peer doesn't support RTCP multiplexing, then session negotiation fails.
+ +

RTCSignalingState enum

+ +

The RTCSignalingState enum specifies the possible values of {{domxref("RTCPeerConnection.signalingState")}}, which indicates where in the process of signaling the exchange of offer and answer the connection currently is.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
"stable"There is no ongoing exchange of offer and answer underway. This may mean that the {{domxref("RTCPeerConnection")}} object is new, in which case both the {{domxref("RTCPeerConnection.localDescription", "localDescription")}} and {{domxref("RTCPeerConnection.remoteDescription", "remoteDescription")}} are null; it may also mean that negotiation is complete and a connection has been established.
"have-local-offer"The local peer has called {{domxref("RTCPeerConnection.setLocalDescription()")}}, passing in SDP representing an offer (usually created by calling {{domxref("RTCPeerConnection.createOffer()")}}), and the offer has been applied successfully.
"have-remote-offer"The remote peer has created an offer and used the signaling server to deliver it to the local peer, which has set the offer as the remote description by calling {{domxref("RTCPeerConnection.setRemoteDescription()")}}.
"have-local-pranswer"The offer sent by the remote peer has been applied and an answer has been created (usually by calling {{domxref("RTCPeerConnection.createAnswer()")}}) and applied by calling {{domxref("RTCPeerConnection.setLocalDescription()")}}. This provisional answer describes the supported media formats and so forth, but may not have a complete set of ICE candidates included. Further candidates will be delivered separately later.
"have-remote-pranswer"A provisional answer has been received and successfully applied in response to an offer previously sent and established by calling setLocalDescription().
"closed" {{obsolete_inline}} +

A conexão é fechada.

+ +
+

Note: This value moved into the RTCPeerConnectionState enum in the May 13, 2016 draft of the specification, as it reflects the state of the RTCPeerConnection, not the signaling connection. You now detect a closed connection by checking for {{domxref("RTCPeerConnection.connectionState", "connectionState")}} to be "closed" instead.

+
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0', '#interface-definition', 'RTCPeerConnection')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git "a/files/pt-br/web/api/sele\303\247\303\243o/index.html" "b/files/pt-br/web/api/sele\303\247\303\243o/index.html" new file mode 100644 index 0000000000..9cac677942 --- /dev/null +++ "b/files/pt-br/web/api/sele\303\247\303\243o/index.html" @@ -0,0 +1,206 @@ +--- +title: Seleção +slug: Web/API/Seleção +tags: + - API + - Experimental + - Interface + - Referencia + - Seleção +translation_of: Web/API/Selection +--- +
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+ +

Um objeto Selection representa um intervalo do texto selecionado pelo usuário ou a posição atual do cursor. Para obter o objeto Selection para inspecionar ou modificar, use {{DOMxRef("Window.getSelection()")}}.

+ +

O usuário pode fazer a seleção da esquerda para a direita (na orientação do documento) ou da direita para a esquerta (orientação inversa do documento). O atributo anchor (âncora) é onde o usuário iniciou a seleção e o atributo focus (foco) é onde o usuário terminou a seleção. Se você fizer a seleção utilizando um mouse no desktop, o anchor é definido onde você pressionou o botão do mouse e o focus é definido onde você soltou o botão do mouse. Anchor e focus não devem ser confundidos com a posição inicial e final da seleção, pois o anchor pode ser definido antes do focus ou vice versa, dependendo da direção em que você fez sua seleção.

+ +

Propriedades

+ +
+
{{DOMxRef("Selection.anchorNode")}}{{ReadOnlyInline}}
+
Retorna o {{DOMxRef("Node")}} onde a seleção começou.
+
{{DOMxRef("Selection.anchorOffset")}}{{ReadOnlyInline}}
+
Retorna um número representando o deslocamento do anchor dentro do elemento Se o elemento for do tipo text node, o número retornado será o número de caracteres no elemento que precedem o anchor (clique inicial da seleção). Se o elemento for do tipo element (qualquer tag html que não seja text node), o número retornado será o número de nós filhos do elemento que precedem o anchor.
+
{{DOMxRef("Selection.focusNode")}}{{ReadOnlyInline}}
+
Retorna o {{DOMxRef("Node")}} onde a seleção termina.
+
{{DOMxRef("Selection.focusOffset")}}{{ReadOnlyInline}}
+
Retorna um número representando o deslocamento do focus dentro do elemento Se o elemento for do tipo text node, o número retornado será o número de caracteres no elemento que precedem o focus (posição onde o mouse foi solto). Se o elemento for do tipo element (qualquer tag html que não seja text node), o número retornado será o número de nós filhos do elemento que precedem o focus.
+
{{DOMxRef("Selection.isCollapsed")}}{{ReadOnlyInline}}
+
Retorna um valor booleano indicando se o início e o final da seleção são a mesma posição, ou seja, começou e terminou no mesmo lugar.
+
{{DOMxRef("Selection.rangeCount")}}{{ReadOnlyInline}}
+
Retorna no número de intervalos da seleção.
+
{{DOMxRef("Selection.type")}}{{ReadOnlyInline}}
+
Retorna um {{DOMxRef("DOMString")}} descrevento o tipo da seleção atual.
+
+ +

Métodos

+ +
+
{{DOMxRef("Selection.addRange()")}}
+
Um objeto {{DOMxRef("Range")}} que será adicionado na seleção.
+
{{DOMxRef("Selection.collapse()")}}
+
Colapsa a seleção atual em um único ponto.
+
{{DOMxRef("Selection.collapseToEnd()")}}
+
Colapsa a seleção para o final do último intervalo na seleção.
+
{{DOMxRef("Selection.collapseToStart()")}}
+
Colapsa a seleção para o início do primeiro intervalo na seleção.
+
{{DOMxRef("Selection.containsNode()")}}
+
Indica se um certo nó é parte da seleção.
+
{{DOMxRef("Selection.deleteFromDocument()")}}
+
Apaga o conteúdo da seleção do documento.
+
{{DOMxRef("Selection.empty()")}}
+
Remove todos os intervalos da seleção. Este é um apelido para removeAllRanges() — Veja {{DOMxRef("Selection.removeAllRanges()")}} para mais detalhes.
+
{{DOMxRef("Selection.extend()")}}
+
Move o focus (final da seleção) para um ponto específico.
+
{{DOMxRef("Selection.getRangeAt()")}}
+
Retorna um objeto {{DOMxRef("Range")}} represetando um dos intervalos atualmente selecionados.
+
{{DOMxRef("Selection.modify()")}}{{Non-standard_Inline}}
+
Altera a seleção atual.
+
{{DOMxRef("Selection.removeRange()")}}
+
Remove um intervalo da seleção.
+
{{DOMxRef("Selection.removeAllRanges()")}}
+
Remove todos os intervalos da seleção.
+
{{DOMxRef("Selection.selectAllChildren()")}}
+
Adiciona todos os filhos do nó especificado para a seleção.
+
{{DOMxRef("Selection.setBaseAndExtent()")}}
+
Define que a seleção será um intervalo incluindo todos ou partes dos dois nós DOM especificados, e qualquer conteúdo entre esses nós.
+
{{DOMxRef("Selection.setPosition()")}}
+
Colapsa a seleção atual para um único ponto. Este é um apelido para collapse() — Veja {{DOMxRef("Selection.collapse()")}} para mais detalhes.
+
{{DOMxRef("Selection.toString()")}}
+
Retorna uma string atualmente representada pelo objeto selection, i.e. o texto atualmente selecionado.
+
+ +

Notas

+ +

Representação da seleção em formato de String

+ +

Chamando a função {{DOMxRef("Selection.toString()")}} retorna o texto selecionado, e.g.:

+ +
var selObj = window.getSelection();
+window.alert(selObj);
+
+ +

Perceba que usando um objeto selection como argumento de window.alert executará o metodo toString automaticamente.

+ +

Multiplos intervalos em uma seleção

+ +

Um objeto selection representa os {{DOMxRef("range","intervalos")}} que o usuário selecionou.
+ Normalmente é apenas um intervalo, acessado da seguinte forma:

+ +
+
var selObj = window.getSelection();
+var range  = selObj.getRangeAt(0);
+
+ + + +

Como consta nas Especificações da API de seleção, a API foi inicialmente criada pela Netscape e usados multiplos intervalos, por instância, para permitir ao usuário selecionar uma coluna de uma {{HTMLElement("table")}}. Outros navegadores como Gecko não implementaram multiplos intervalos, e a especificação exige que a seleção sempre tenha um único intervalo.

+ +

Seleção e foco de input

+ +

Seleção e foco de input (indicado por {{DOMxRef("Document.activeElement")}}) tem uma relação complexa, que depende do navegador. Para um código compatível com vários navegadores, o melhor é manter os códigos separados.

+ +

O Safari e o Chrome (ao contrário do Firefox) historicamente foca no elemento contendo a seleção quando a seleção é modificada programaticamente, mas isto pode mudar no futuro (veja W3C bug 14383 e {{WebKitBug("38696")}}).

+ +

Comportamento da API de Seleção em termos de edição e alterações de foco do host

+ +

A API de Seleção tem um comportamento comum (i.e. compartilhado entre navegadores) que define como o comportamento do foco muda para elemento editável, após alguns desses métodos serem executados.

+ +

Os comportamentos são que um elemento editado recebe o foco se anteriormente a seleção estiver fora dele, então um método da API de seleção é executado e causa uma nova seleção que será feita em um único intervalo dentro do elemento sendo editado. O foco então é movido para o final do elemento.

+ +
+

Nota: Os métodos da API de seleção, move o foco apenas para o elemento sendo editado, não para outro elemento que pode receber o foco (e.g. {{HTMLElement("a")}}).

+
+ +

O comportamento acima é aplicado para as seleções feitas usando os seguintes métodos:

+ + + +

e quando o intervalo é modificado usando os seguintes métodos:

+ + + +

Glossário

+ +

Outras palavras chaves usadas nesta seção.

+ +
+
anchor
+
O anchor de uma seleção é o ponto inicial da seleção. Quando a seleção é feita com um mouse, é onde o botão do mouse é inicialmente pressionado. Quando o usuário altera a seleção usando o mouse ou teclado, o anchor não move.
+
Elemento editável
+
Um elemento editável — i.e. um elemento HTML com o atributo {{htmlattrxref("contenteditable")}} definido, ou o HTML filho de um documento estiver com o {{DOMxRef("Document.designMode", "designMode")}} habilitado.
+
foco de uma seleção
+
O foco da seleção é o ponto final da seleção. Quando feita a seleção com um mouse, o focus é onde o botão do mouse foi solto. Quando o usuário muda a seleção usando o mouse ou teclado, o focus é o final da seleção que move. Nota: Não é o mesmo que o elemento selecionado do documento, como retornado em {{DOMxRef("document.activeElement")}}.
+
intervalo
+
Um intervalo é uma parte contínua do documento. Um intervalo pode conter nós inteiros ou partes de nós, como uma parte de um text node. Um usuário normalmente irá selecionar um único intervalo por vez, mas é possível que o usuário selecione multiplos intervalos (e.g. usando a tecla Control). Um intervalo pode ser obtido de uma seleção como um objeto {{DOMxRef("range")}}. Um objeto de intervalo pode ser criado no DOM e programaticamente adicionada ou removida de uma seleção.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Selection API", "#selection-interface", "Seleção")}}{{Spec2("Selection API")}}A especificação da API de Seleção é baseada na especificação da API de edição HTML e focada na funcionalidade relacionada à seleção.
{{SpecName("HTML Editing", "#selection", "Seleção")}}{{Spec2("HTML Editing")}}Definição incial (antiga).
+ +

Compatibilidade de navegadores

+ + + +

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

+ +

Veja também

+ + + +

Notas da Gecko

+ + + +
+
diff --git a/files/pt-br/web/api/sensor/index.html b/files/pt-br/web/api/sensor/index.html new file mode 100644 index 0000000000..afc91f60d5 --- /dev/null +++ b/files/pt-br/web/api/sensor/index.html @@ -0,0 +1,89 @@ +--- +title: Sensor +slug: Web/API/Sensor +tags: + - API + - Generic Sensor API + - Interface + - NeedsTranslation + - Reference + - Sensor + - Sensor APIs + - Sensors + - TopicStub +translation_of: Web/API/Sensor +--- +
{{APIRef("Generic Sensor API")}}
+ +

The Sensor interface of the the Sensor APIs is the base class for all the other sensor interfaces. This interface cannot be used directly. Instead it provides properties, event handlers, and methods accessed by interfaces that inherit from it.

+ +

If a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. This is not something that would ever be shown to a user. See {{httpheader('Feature-Policy')}} for implementation instructions.

+ +

Interfaces based on Sensor

+ +

Below is a list of interfaces based on the Sensor interface.

+ +
+ +
+ +

Properties

+ +
+
{{domxref('Sensor.activated')}} {{readonlyinline}}
+
Returns a {{jsxref("Boolean")}} indicating whether the sensor is active.
+
{{domxref('Sensor.hasReading')}} {{readonlyinline}}
+
Returns a {{jsxref("Boolean")}} indicating whether the sensor has a reading.
+
{{domxref('Sensor.timestamp')}} {{readonlyinline}}
+
Returns the time stamp of the latest sensor reading.
+
+ +

Event handlers

+ +
+
{{domxref('Sensor.onerror')}}
+
Called when an error occurs on one of the child interfaces of the Sensor interface.
+
{{domxref('Sensor.onreading')}}
+
Called when a reading is taken on one of the child interfaces of the Sensor interface.
+
{{domxref('Sensor.onactivate')}}
+
Called when one of the Sensor interface's becomes active.
+
+ +

Methods

+ +
+
{{domxref('Sensor.start()')}}
+
Activates one of the sensors based on Sensor.
+
{{domxref('Sensor.stop()')}}
+
Deactivates one of the sensors based on Sensor.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Generic Sensor','#the-sensor-interface','Sensor')}}{{Spec2('Generic Sensor')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

diff --git a/files/pt-br/web/api/server-sent_events/index.html b/files/pt-br/web/api/server-sent_events/index.html new file mode 100644 index 0000000000..4a7f8eb1b7 --- /dev/null +++ b/files/pt-br/web/api/server-sent_events/index.html @@ -0,0 +1,79 @@ +--- +title: Server-sent events +slug: Web/API/Server-sent_events +tags: + - API + - NeedsTranslation + - Overview + - SSE + - Server-sent events + - TopicStub +translation_of: Web/API/Server-sent_events +--- +

{{DefaultAPISidebar("Server Sent Events")}}

+ +

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.

+ +

Concepts and usage

+ +

To learn how to use server-sent events, see our article Using server-sent events.

+ +

Interfaces

+ +
+
{{domxref("EventSource")}}
+
Defines all the features that handle connecting to a server, receiving events/data, errors, closing a connection, etc.
+
+ +

Examples

+ + + +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#server-sent-events', 'Server-sent events')}}{{Spec2('HTML WHATWG')}} 
+ +

See also

+ +

Tools

+ + + + + + + +

Other resources

+ + diff --git a/files/pt-br/web/api/server-sent_events/using_server-sent_events/index.html b/files/pt-br/web/api/server-sent_events/using_server-sent_events/index.html new file mode 100644 index 0000000000..1a7b084ab6 --- /dev/null +++ b/files/pt-br/web/api/server-sent_events/using_server-sent_events/index.html @@ -0,0 +1,189 @@ +--- +title: Using server-sent events +slug: Web/API/Server-sent_events/Using_server-sent_events +translation_of: Web/API/Server-sent_events/Using_server-sent_events +--- +

{{DefaultAPISidebar("Server Sent Events")}}

+ +
+

É fácil desenvolver um aplicativo Web que usa server-sent events. Você precisára de um pouco de código no servidor para transmitir eventos para o front-end, mas o código do lado do cliente funciona quase de forma idêntica aos websockets em questão de tratamento de eventos recebidos. Essa é uma conexão unidirecional, portanto você não pode enviar eventos de um cliente para um servidor.

+
+ +

Receiving events from the server

+ +

The server-sent event API is contained in the {{domxref("EventSource")}} interface; to open a connection to the server to begin receiving events from it, create a new EventSource object with the URL of a script that generates the events. For example:

+ +
const evtSource = new EventSource("ssedemo.php");
+ +

If the event generator script is hosted on a different origin, a new EventSource object should be created with both the URL and an options dictionary. For example, assuming the client script is on example.com:

+ +
const evtSource = new EventSource("//api.example.com/ssedemo.php", { withCredentials: true } );
+ +

Once you've instantiated your event source, you can begin listening for messages from the server by attaching a handler for the {{event("message")}} event:

+ +
evtSource.onmessage = function(event) {
+  const newElement = document.createElement("li");
+  const eventList = document.getElementById("list");
+
+  newElement.innerHTML = "message: " + event.data;
+  eventList.appendChild(newElement);
+}
+
+ +

This code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's HTML.

+ +

You can also listen for events with addEventListener():

+ +
evtSource.addEventListener("ping", function(event) {
+  const newElement = document.createElement("li");
+  const time = JSON.parse(event.data).time;
+  newElement.innerHTML = "ping at " + time;
+  eventList.appendChild(newElement);
+});
+
+ +

This code is similar, except that it will be called automatically whenever the server sends a message with the event field set to "ping"; it then parses the JSON in the data field and outputs that information.

+ +
+

When not used over HTTP/2, SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is per browser and set to a very low number (6). The issue has been marked as "Won't fix" in Chrome and Firefox. This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to www.example1.com and another 6 SSE connections to www.example2.com. (from Stackoverflow). When using HTTP/2, the maximum number of simultaneous HTTP streams is negotiated between the server and the client (defaults to 100).

+
+ +

Sending events from the server

+ +

The server-side script that sends events needs to respond using the MIME type text/event-stream. Each notification is sent as a block of text terminated by a pair of newlines. For details on the format of the event stream, see {{ anch("Event stream format") }}.

+ +

The {{Glossary("PHP")}} code for the example we're using here follows:

+ +
date_default_timezone_set("America/New_York");
+header("Cache-Control: no-cache");
+header("Content-Type: text/event-stream");
+
+$counter = rand(1, 10);
+while (true) {
+  // Every second, send a "ping" event.
+
+  echo "event: ping\n";
+  $curDate = date(DATE_ISO8601);
+  echo 'data: {"time": "' . $curDate . '"}';
+  echo "\n\n";
+
+  // Send a simple message at random intervals.
+
+  $counter--;
+
+  if (!$counter) {
+    echo 'data: This is a message at time ' . $curDate . "\n\n";
+    $counter = rand(1, 10);
+  }
+
+  ob_end_flush();
+  flush();
+  sleep(1);
+}
+
+ +

The code above generates an event every second, with the event type "ping". Each event's data is a JSON object containing the ISO 8601 timestamp corresponding to the time at which the event was generated. At random intervals, a simple message (with no event type) is sent.

+ +
+

Note: You can find a full example that uses the code shown in this article on GitHub — see Simple SSE demo using PHP.

+
+ +

Error handling

+ +

When problems occur (such as a network timeout or issues pertaining to access control), an error event is generated. You can take action on this programmatically by implementing the onerror callback on the EventSource object:

+ +
evtSource.onerror = function(err) {
+  console.error("EventSource failed:", err);
+};
+
+ +

Closing event streams

+ +

By default, if the connection between the client and server closes, the connection is restarted. The connection is terminated with the .close() method.

+ +
evtSource.close();
+ +

Event stream format

+ +

The event stream is a simple stream of text data which must be encoded using UTF-8. Messages in the event stream are separated by a pair of newline characters. A colon as the first character of a line is in essence a comment, and is ignored.

+ +
Note: The comment line can be used to prevent connections from timing out; a server can send a comment periodically to keep the connection alive.
+ +

Each message consists of one or more lines of text listing the fields for that message. Each field is represented by the field name, followed by a colon, followed by the text data for that field's value.

+ +

Fields

+ +

Each message received has some combination of the following fields, one per line:

+ +
+
event
+
A string identifying the type of event described. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the website source code should use addEventListener() to listen for named events. The onmessage handler is called if no event name is specified for a message.
+
data
+
The data field for the message. When the EventSource receives multiple consecutive lines that begin with data:, it will concatenate them, inserting a newline character between each one. Trailing newlines are removed.
+
id
+
The event ID to set the EventSource object's last event ID value.
+
retry
+
The reconnection time to use when attempting to send the event. This must be an integer, specifying the reconnection time in milliseconds. If a non-integer value is specified, the field is ignored.
+
+ +

All other field names are ignored.

+ +
Note: If a line doesn't contain a colon, the entire line is treated as the field name with an empty value string.
+ +

Examples

+ +

Data-only messages

+ +

In the following example, there are three messages sent. The first is just a comment, since it starts with a colon character. As mentioned previously, this can be useful as a keep-alive if messages may not be sent regularly.

+ +

The second message contains a data field with the value "some text". The third message contains a data field with the value "another message\nwith two lines". Note the newline special character in the value.

+ +
: this is a test stream
+
+data: some text
+
+data: another message
+data: with two lines
+
+ +

Named events

+ +

This example sends some named events. Each has an event name specified by the event field, and a data field whose value is an appropriate JSON string with the data needed for the client to act on the event. The data field could, of course, have any string data; it doesn't have to be JSON.

+ +
event: userconnect
+data: {"username": "bobby", "time": "02:33:48"}
+
+event: usermessage
+data: {"username": "bobby", "time": "02:34:11", "text": "Hi everyone."}
+
+event: userdisconnect
+data: {"username": "bobby", "time": "02:34:23"}
+
+event: usermessage
+data: {"username": "sean", "time": "02:34:36", "text": "Bye, bobby."}
+
+ +

Mixing and matching

+ +

You don't have to use just unnamed messages or typed events; you can mix them together in a single event stream.

+ +
event: userconnect
+data: {"username": "bobby", "time": "02:33:48"}
+
+data: Here's a system message of some kind that will get used
+data: to accomplish some task.
+
+event: usermessage
+data: {"username": "bobby", "time": "02:34:11", "text": "Hi everyone."}
+ +

Browser compatibility

+ +
+

EventSource

+ +
+ + +

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

+
+
diff --git a/files/pt-br/web/api/service_worker_api/index.html b/files/pt-br/web/api/service_worker_api/index.html new file mode 100644 index 0000000000..05ae2f90c8 --- /dev/null +++ b/files/pt-br/web/api/service_worker_api/index.html @@ -0,0 +1,322 @@ +--- +title: API do Service Worker +slug: Web/API/Service_Worker_API +translation_of: Web/API/Service_Worker_API +--- +

{{ServiceWorkerSidebar}}

+ +

Essencialmente, um service worker se comporta como um servidor proxy situado entre uma aplicação web, o navegador e a rede (quando esta estiver disponível). Eles servem, dentre outras coisas, para possibilitar a criação de experiências offline eficientes, interceptar requisições de rede – agindo adequadamente de acordo com o status atual da conexão – e atualizar os assets que residem no servidor. Service workers também permitem o acesso às APIs de push notification e background sync.

+ +

Service worker - Conceitos e uso

+ +

Um service worker é um tipo especial de worker baseado em eventos, o qual é registrado para um determinado path e origem. Na prática, ele é um arquivo JavaScript que pode controlar as páginas do site ao qual ele está associado, interceptando e modificando requisições e a navegação em si. Ele também faz cache dos recursos trafegados de maneira bastante granular, visando oferecer controle total sobre como a sua aplicação se comporta em determinadas situações (o exemplo mais óbvio, naturalmente, é quando não há conexão de rede disponível).

+ +

Assim como outros tipos de worker, um service worker é executado em um contexto isolado. Dessa forma, não tem acesso ao DOM e roda em uma thread completamente separada, sendo incapaz de realizar operações blocantes. Service workers foram projetados para ser totalmente assíncronos; como consequência disso, não permitem o acesso a APIs como XHR síncrono e localStorage.  

+ +

Por questões de segurança, service workers funcionam apenas em sites servidos via HTTPS. A possibilidade de modificar requisições em um domínio desprotegido contra ataques do tipo man-in-the-middle seria desastrosa. No Firefox, é vetado o acesso à API de service workers para sites abertos no Modo de navegação privativa.

+ +
+

Nota: Os service workers superaram tentativas anteriores de resolver problemas semelhantes, como o AppCache. Há uma explicação simples para eles terem sido bem-sucedidos: Service workers não tentam adivinhar o que você está tentando fazer e, muito menos, deixam de funcionar caso não tenham adivinhado corretamente. Pelo contrário, você tem o controle milimétrico de tudo.    

+
+ +
+

Nota: Service workers fazem uso intenso de promessas, uma vez que eles têm de esperar por respostas assíncronas para, após retornadas, poderem executar a ação apropriada (de sucesso ou erro). A arquitetura de promessas é ideal para esse tipo de cenário.

+
+ +

 

+ +

Registrando

+ +

O registro inicial de um service worker é feito através do método {{domxref("ServiceWorkerContainer.register()")}}. Se bem-sucedido, seu service worker será descarregado no cliente e então ocorrerá a tentativa de instalação/ativação para as URLs acessadas pelo usuário sob a origem registrada ou, caso deseje, apenas dentro de um subconjunto limitado por você.

+ +

Download, instalação e ativação

+ +

Nesse estágio, seu service worker seguirá o seguinte ciclo de vida:

+ +
    +
  1. Download
  2. +
  3. Instalação
  4. +
  5. Ativação
  6. +
+ +

Quando o usuário acessa pela primeira vez um site ou página controlado por um service worker, ele é descarregado imediatamente.

+ +

Após isso, serão feitos novos downloads em intervalos de aproximadamente 24 horas. O download pode ocorrer mais frequentemente, mas ele precisa ser feito a cada 24 horas para prevenir que scripts ruins sejam um problema por períodos muito extensos. 

+ +

A tentativa de instalação é feita sempre que o arquivo descarregado é identificado como novo – seja por diferir dos service workers pré-existentes (é feita uma comparação binária nessa etapa) ou por ser o primeiro descoberto para a página ou site em questão.

+ +

Na primeira vez que um service worker é disponibilizado, é feita a tentativa de instalação. Se bem-sucedida, ele é ativado.

+ +

Se, por outro lado, já existe um service worker pré-instalado para uma página ou site e for disponibilizada uma nova versão, ela será descarregada, mas não imediatamente ativada. Isso é chamado de worker em espera. Só será efetuada a ativação da versão atualizada quando não houver mais páginas utilizando a anterior. Após isso, ele passa a ser o worker ativo. Caso necessário, é possível pular a etapa de espera com o método {{domxref("ServiceWorkerGlobalScope.skipWaiting()")}}. Em seguida, o novo worker ativo pode reivindicar as páginas existentes usando {{domxref("Clients.claim()")}}. 

+ +

Você pode adicionar um listener para o evento {{domxref("InstallEvent")}}. Uma ação padrão, quando esse evento é disparado, é preparar o seu service worker para ser utilizado (por exemplo: criado um cache usando a API de storage nativa e armazenando nela os assets que você quer que permaneçam disponíveis caso a aplicação fique offline).

+ +

Há também o evento activate. O momento em que ele é disparado é geralmente o ideal para limpar caches antigos e outras coisas associadas com a versão anterior do seu service worker.

+ +

Seu service worker pode responder a requisições usando o {{domxref("FetchEvent")}}. Você pode manipular a resposta a essas requisições da maneira que quiser, através do método {{domxref("FetchEvent.respondWith")}}.

+ +
+

Nota: Como oninstall e onactivate podem demorar a serem concluídos, a especificação de service workers disponibiliza um método waitUntil. Ele recebe como parâmetro uma promessa, notificando o navegador que há trabalho em andamento até que aquela promessa seja resolvida. O navegador, portanto, não deverá encerrar o service worker durante esse período de espera. 

+
+ +

Para um tutorial completo, mostrando como construir seu primeiro exemplo do zero, leia Usando Service Workers.

+ +

Outras ideias de usos possíveis

+ + + +

No futuro, service workers serão capazes de fazer várias outras coisas úteis para a plataforma web, deixando-a mais próxima de apps nativos em.

+ +

É interessante mencionar que outras especificações podem e irão passar a usar o contexto de service workers, por exemplo:

+ + + +

Interfaces

+ +
+
{{domxref("Cache")}}
+
Representa o armazenamento para os pares de objeto {{domxref("Request")}} e {{domxref("Response")}}, os quais são cacheados como parte do ciclo de vida do {{domxref("ServiceWorker")}}.
+
{{domxref("CacheStorage")}}
+
Representa o armazenamento para objetos {{domxref("Cache")}}. Ele disponibiliza um diretório-mestre com todos os caches nomeados que um {{domxref("ServiceWorker")}} pode acessar, mantendo o mapeamento de nomes para os objetos {{domxref("Cache")}} correspondentes.
+
{{domxref("Client")}}
+
Representa o escopo do cliente de um service worker. Um cliente pode ser um documento no contexto de um navegador ou um {{domxref("SharedWorker")}}, o qual é controlado por um worker ativo.
+
{{domxref("Clients")}}
+
Representa o container para uma lista de objetos {{domxref("Client")}}. É a principal forma de acessar os clientes na origem atual para o service worker ativo.
+
{{domxref("ExtendableEvent")}}
+
Estende a vida dos eventos install e activate disparados no {{domxref("ServiceWorkerGlobalScope")}}, como parte do ciclo de vida do service worker. Isso garante que qualquer evento funcional (como o {{domxref("FetchEvent")}}) não seja despachado para o {{domxref("ServiceWorker")}} até que ele conclua as ações em andamento, como por exemplo: atualizar esquemas de banco de dados, apagar caches defasados, etc.
+
{{domxref("ExtendableMessageEvent")}}
+
O objeto de evento do {{event("message_(ServiceWorker)","message")}}, o qual é disparado em um service worker (quando uma mensagem de canal é recebida no {{domxref("ServiceWorkerGlobalScope")}} a partir de outro contexto) — estende o tempo de vida desses eventos.
+
{{domxref("FetchEvent")}}
+
O parâmetro recebido no handler  {{domxref("ServiceWorkerGlobalScope.onfetch")}}. O FetchEvent representa uma ação de descarregamento que é despachada no {{domxref("ServiceWorkerGlobalScope")}} de um  {{domxref("ServiceWorker")}}. Ele contém informações sobre a requisição e a resposta resultante, além de disponibilizar o método {{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}}, o qual nos permite devolver uma resposta customizada para a página que está sendo controlada.
+
{{domxref("InstallEvent")}}
+
O parâmetro recebido no handler  {{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}}. A interface InstallEvent representa uma ação de instalação que é despachada no {{domxref("ServiceWorkerGlobalScope")}} de um  {{domxref("ServiceWorker")}}. Como deriva do {{domxref("ExtendableEvent")}}, ele assegura que eventos funcionais, como o {{domxref("FetchEvent")}}, não sejam despachados durante a instalação. 
+
{{domxref("NavigationPreloadManager")}}
+
Disponibiliza métodos para gerenciar o pré-carregamento de recursos com um service worker. 
+
{{domxref("Navigator.serviceWorker")}}
+
Retornar um objeto {{domxref("ServiceWorkerContainer")}}, o qual permite accesso ao registro, remoção, atualização e comunicação com os objetos {{domxref("ServiceWorker")}} para o documento associado.
+
{{domxref("NotificationEvent")}}
+
O parâmetro recebido no handler  {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}}. A interface NotificationEvent representa um evento de click em uma notificação que é despachado no {{domxref("ServiceWorkerGlobalScope")}} de um {{domxref("ServiceWorker")}}.
+
{{domxref("ServiceWorker")}}
+
Representa um service worker. Diferentes contextos de navegação (ex: páginas, workers, etc.) podem ser associados com o mesmo objeto ServiceWorker.
+
{{domxref("ServiceWorkerContainer")}}
+
Disponibiliza um objeto representando o service worker como uma unidade global no ecossistema de rede, incluindo métodos para registrar, desregistrar e atualizar service workers, além de poder acessar o status de cada worker e seus registros.
+
{{domxref("ServiceWorkerGlobalScope")}}
+
Representa o contexto de execução global de um service worker.
+
{{domxref("ServiceWorkerMessageEvent")}} {{deprecated_inline}}
+
Representa uma mensagem enviada a um {{domxref("ServiceWorkerGlobalScope")}}. Vale ressaltar que essa interface está defasada em navegadores modernos. As mensagens de service worker agora usam a interface {{domxref("MessageEvent")}} para manter consistência com outras funcionalidades de messageria da web.
+
{{domxref("ServiceWorkerRegistration")}}
+
Representa o registro de um service worker.
+
{{domxref("ServiceWorkerState")}} {{experimental_inline}}
+
Associado com o estado do ServiceWorker.
+
{{domxref("SyncEvent")}} {{non-standard_inline}}
+
+

A interface SyncEvent representa uma ação de sincronização que é despachada no {{domxref("ServiceWorkerGlobalScope")}} de um ServiceWorker. 

+
+
{{domxref("SyncManager")}} {{non-standard_inline}}
+
Disponibiliza uma interface para registrar e listar registros de sincronização.
+
{{domxref("WindowClient")}}
+
Representa o escopo de um cliente de service worker que é um documento em um contexto de navegador, o qual é controlado por um worker ativo. Esse é um tipo especial de objeto {{domxref("Client")}}, como alguns métodos e propriedades adicionais disponíveis.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Compatibilidade de Navegador

+ +

{{ CompatibilityTable() }}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoDesktop("44.0") }}[2]{{ CompatNo() }}24{{ CompatNo() }}[3]
Eventos install/activate{{ CompatChrome(40) }}{{CompatNo}}[1]{{ CompatGeckoDesktop("44.0") }}[2]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
Evento fetch/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")}} defasado em favor {{domxref("MessageEvent")}} +

{{CompatChrome(57)}}

+
{{ CompatNo() }}{{ CompatGeckoDesktop("55.0") }}[2]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
NavigationPreloadManager{{CompatChrome(59)}}{{ CompatNo() }} {{ CompatNo() }}{{CompatOpera(46)}}{{ CompatNo() }}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursosAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{ CompatNo() }}{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoMobile("44.0") }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}[3]
Eventos install/activate{{ CompatNo() }}{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoMobile("44.0") }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
Evento fetch/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")}} defasado em favor de {{domxref("MessageEvent")}}{{ CompatNo() }} +

{{CompatChrome(57)}}

+
{{ CompatNo() }}{{ CompatGeckoMobile("55.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
NavigationPreloadManager{{ CompatNo() }}{{CompatChrome(59)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{CompatOperaMobile(46)}}{{ CompatNo() }}
+ +

[1] Esse recurso ainda não é suportado, apesar de já estar em desenvolvimento.

+ +

[2] Service workers (e Push) foram desabilitados no Firefox, nas versões 45 & 52 Extended Support Releases (ESR.)

+ +

[3] Esse recurso ainda não é suportado, apesar de já estar em desenvolvimento.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/service_worker_api/using_service_workers/index.html b/files/pt-br/web/api/service_worker_api/using_service_workers/index.html new file mode 100644 index 0000000000..983b352d82 --- /dev/null +++ b/files/pt-br/web/api/service_worker_api/using_service_workers/index.html @@ -0,0 +1,522 @@ +--- +title: Usando Service Workers +slug: Web/API/Service_Worker_API/Using_Service_Workers +translation_of: Web/API/Service_Worker_API/Using_Service_Workers +--- +

{{ServiceWorkerSidebar}}

+ +

{{ SeeCompatTable() }}

+ +
+

Esse artigo contém informações de como começar com service workers, incluindo a arquitetura básica, registro de um service worker, o processo de instalação e ativação de um novo service worker, atualização de seu service worker, controle de cache e respostas customizadas, tudo isso no contexto de um simples app com a funcionalidade offline.

+
+ +

A premissa dos Service Workers

+ +

O principal problema que os usuários da web sofreram durante anos foi a perda de conexão. Até mesmo melhor web app do mundo terá uma péssima experiência de usuário se você não conseguir baixa-lá. Houveram várias tentativas de criar tecnologias para resolver esse problema, como mostra nossa página Offline, e algumas questões foram resolvidas. Mas o maior problema é que, no geral, ainda não há um bom mecanismo de controle para caching de assets e requisições de rede personalizadas.
+
+ A tentativa anterior — AppCache — parecia uma boa ideia, pois permitia especificar facilmente os assets para cache. Porém, fazia várias suposições sobre o que você estava tentando fazer e depois quebrava horrivelmente quando seu app não seguia exatamente tais suposições. Leia Application Cache is a Douchebag de Jake Archibald para mais detalhes.

+ +
+

Nota: A partir do Firefox 44, quando AppCache é usado para fornecer suporte offline  uma página, um aviso é exibido no console para que os desenvolvedores usem Service workers ({{bug("1204581")}}.)

+
+ +

Service workers devem finalmente corrigir esses problemas. A sintaxe do service worker é mais complexa do que a do AppCache, mas a vantagem é que você pode usar Javascript para controlar os comportamentos implícitos do AppCache com um bom grau de granularidade, permitindo que você lide com esse problema e muitos outros. Usando Service Worker você pode facilmente configurar um app para usar primeiro assets em cache, provendo uma experiência padronizada mesmo que esteja offline, antes de obter mais dados da rede (mais conhecido como Offline First). Isso já está disponível em apps nativos, que é uma das principais razões pelas quais apps nativos são frequentemente mais escolhidos do que web apps.

+ +

Configuração para usar service workers

+ +

Várias características de service workers estão habilitadas por padrão em versões mais recentes dos navegadores suportados. Se, no entanto, encontrar um código de demonstração que não está funcionando na suas versões instaladas, você precisará habilitar essa preferência:

+ + + +

Você também precisa fornecer seu código via HTTPS — Service workers estão restritos a rodar apenas via HTTPS por motivos de segurança. GitHub serve como um bom host para os experimentos, pois suporta HTTPS. Para facilitar o desenvolvimento local, localhost também é considerado uma origem segura pelos navegadores. 

+ +

Arquitetura Básica

+ +

Com service workers, os seguintes passos geralmente são observados como configuração básica:

+ +
    +
  1. A URL do service worker é buscada e registrada via {{domxref("serviceWorkerContainer.register()")}}.
  2. +
  3. Em caso de sucesso, o service worker é executado em um {{domxref("ServiceWorkerGlobalScope") }}; isto é basicamente um tipo especial de contexto do worker, que é executado fora da thread de execução do script principal, sem acesso ao DOM.
  4. +
  5. O service worker agora está pronto para processar eventos.
  6. +
  7. A tentativa de instalação do worker acontece quando as páginas controladas pelo service worker são acessadas. O evento de instalação é sempre o primeiro a ser enviado ao service worker (isto pode ser usado para iniciar o processode preencher um IndexedDB, e armazenar em cache os assets do site). Este é realmente o mesmo tipo de procedimento para instalação de um aplicativo nativo ou do Firefox OS — disponibilizando tudo offline.
  8. +
  9. Quando o manipulador oninstall estiver completo, considera-se que o service worker está instalado.
  10. +
  11. O próximo é a ativação. Quando um service worker é instalado, ele recebe um evento de ativação. O uso primário do onactivate é para limpeza de recursos usado em versões anterioires do script de um Service worker.
  12. +
  13. O Service worker agora vai controlar páginas, mas apenas aquelas abertas após o register() tiver sido bem-sucedido. Isto é, um documento inicia a vida com ou sem Service worker e mantém isso durante seu tempo de vida. Logo, documentos terão de ser recarregados para serem controlados.
  14. +
+ +

+ +

O gráfico abaixo mostra um resumo dos eventos de service worker disponíveis:

+ +

install, activate, message, fetch, sync, push

+ +

Promises

+ +

Promises são um ótimo mecanismo para executar operações assíncronas, onde o sucesso de uma depende do sucesso das outras. Isto é o fundamento para o modo como os service workers trabalham.
+
+ Promises pode fazer uma variedade de coisas, mas tudo o que precisa saber agora é que, se algo retorna uma promise, você pode inserir .then() ao final e incluir dentro dela callback para casos de sucesso ou poder inserir .catch() ao final, se quiser incluir um callback para falha.

+ +

Vamos comparar a estrutura de um callback tradicional síncrono para uma promise assíncrona equivalente.

+ +

sync

+ +
try {
+  var value = myFunction();
+  console.log(value);
+} catch(err) {
+  console.log(err);
+}
+ +

async

+ +
myFunction().then(function(value) {
+  console.log(value);
+}).catch(function(err) {
+  console.log(err);
+});
+ +

No primeiro exemplo, temos que esperar myFunction() executar e retornar value antes que qualquer código adicional possa ser executado. No segundo exemplo, myFunction() retorna uma promessa para value, então o resto do código pode ser executado logo em seguida. Quando a promessa é atendida, o código dentro do método then será executado, assincronamente.
+
+ Agora para um exemplo real — e se quiséssemos carregar imagens dinamicamente, mas quiséssemos ter certeza que as imagens estão carregadas antes de tentar mostrá-las? É uma coisa padrão que estamos querendo fazer, mas pode ser um pouco complicado. Podemos usar .onload para somente mostrar a imagem após ela ter carregado, mas e para os eventos que aconteceram antes de começarmos a ouvi-los? Podemos tentar contornar isso usando .complete, mas ainda não é a prova de falhas, e para várias imagens? E, ummm, ainda é síncrono, portanto bloqueia a thread principal.
+
+ Ao invés disso, podemos contruir nossa própria promessa para lidar com casos deste tipo. (Veja o exemplo Promises test para o código fonte, ou veja rodando live.)

+ +

{{note("Uma implementação real de service worker usaria caching e onfetch ao invés da depreciada XMLHttpRequest API. Estes features não são usados aqui para que você foque em entender Promises.")}}

+ +
function imgLoad(url) {
+  return new Promise(function(resolve, reject) {
+    var request = new XMLHttpRequest();
+    request.open('GET', url);
+    request.responseType = 'blob';
+
+    request.onload = function() {
+      if (request.status == 200) {
+        resolve(request.response);
+      } else {
+        reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
+      }
+    };
+
+    request.onerror = function() {
+      reject(Error('There was a network error.'));
+    };
+
+    request.send();
+  });
+}
+ +

Retornamos uma nova promise usando o Promise() constructor, o qual tem uma função callback como argumento com os parâmetros resolve ereject. Em algum lugar na função, precisamos definir o que acontece para que a promessa ser resolvida com sucesso ou ser rejeitada — neste caso, retornar um status 200 OK ou não — e então chamar resolve em caso de sucesso, ou reject em caso de falha. O resto do conteúdo desta função é XHR padrão, então, não vamos nos preocupar com isso agora.

+ +

Quando chamamos a função imgLoad(), chamamos com a url para a imagem que queremos carregar, como seria de se esperar, mas o resto do código é um pouco diferente:

+ +
var body = document.querySelector('body');
+var myImage = new Image();
+
+imgLoad('myLittleVader.jpg').then(function(response) {
+  var imageURL = window.URL.createObjectURL(response);
+  myImage.src = imageURL;
+  body.appendChild(myImage);
+}, function(Error) {
+  console.log(Error);
+});
+ +

No fim da chamada da função, encadeamos o método then() da promisse, o qual contém duas funções — a primeira é executada quando a promisse é resolvida com sucesso, e a segunda é chamada quando a promise é rejeitada. Caso seja resolvida, exibimos a imagem dentro de myImage e a acrescentamos ao corpo (cujo argument é o request.response contido dentro do método resolve da promise); no caso de rejeição, nos retornamos um erro ao console.

+ +

Tudo isto acontece assincronamente.

+ +
+

Nota: Você também pode encadear chamadas de promises, por exemplo:
+ myPromise().then(success, failure).then(success).catch(failure);

+
+ +
+

Nota: Você pode encontrar muito mais informações sobre promises lendo o excelente JavaScript Promises: there and back again de Jake Archibald.

+
+ +

Demonstração de Service workers

+ +

Para demonstrar apenas o básico de registro e instalação de um service worker, criamos uma simples demonstração chamada sw-test, que é uma simples galeria de imagens de Star Wars Lego. Usa uma função ativada por promise para ler dados de imagem a partir de um objeto JSON e carrega as imagens usando Ajax, antes de exibir as imagens em uma linha ao longo da página. Mantivemos as coisas estáticas e simples por enquanto. Também registra, instala e ativa um service worker, e quando mais especificações são suportadas pelos navegadores, armazena em cache todos os arquivos necessários para que funcione offline!

+ +


+
+
+ Você pode ver o código-fonte no GitHub, e ver um exemplo vivo. A parte que mencionaremos aqui é a promise (veja app.js linhas 22-47), que é uma versão modificada do que você leu a respeito acima, em Promises test demo. É diferente das seguintes formas:

+ +
    +
  1. No original, passamos somente uma URL para uma image que queríamos carregar. Nesta versão, passamos um fragmento de um JSON contendo todos os dados de uma única imagem (veja como se parecem em image-list.js). Isto porque todos os dados para cada resolução de promise precisam ser transmitidos com a promise, pois é assíncrona. Se você passou apenas a url, e depois tentou acessar os outros itens no JSON separadamente, quando o laço de repetição for() estivesse sendo iterado posteriormente, não funcionaria, pois a promise não se resolveria ao mesmo tempo que as iterações estão sendo feitas (isso é um processo síncrono).
  2. +
  3. Na verdade, resolvemos a promise como uma matriz, pois queremos tornar o blob da imagem carregada disponível para a função de resolução mais adiante no código, além do nome da imagem, créditos e texto alternativo (veja app.js linhas 31-34). Promises resolverão somente com um único argumento, então, se você quiser resolver múltiplos valores, precisará usar uma matriz/objeto..
  4. +
  5. Para acessar os valores da promise resolvida, acessamos esta função como esperado (veja app.js linhas 60-64). Pode parecer um pouco estranho no começo, mas é assim que as promises funcionam.
  6. +
+ +

Inserir service workers

+ +

Agora vamos aos service workers!

+ +

Registrando seu worker

+ +

O primeiro bloco de código do nosso arquivo do app JavaScript — app.js — é conforme segue. Este é nosso entry point para usar service workers.

+ +
if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.register('/sw-test/sw.js', {scope: '/sw-test/'})
+  .then(function(reg) {
+    // registration worked
+    console.log('Registration succeeded. Scope is ' + reg.scope);
+  }).catch(function(error) {
+    // registration failed
+    console.log('Registration failed with ' + error);
+  });
+}
+ +
    +
  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:

+ + + +

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 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 support")}} 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:

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(cache) {
+      return cache.addAll([
+        '/sw-test/',
+        '/sw-test/index.html',
+        '/sw-test/style.css',
+        '/sw-test/app.js',
+        '/sw-test/image-list.js',
+        '/sw-test/star-wars-logo.jpg',
+        '/sw-test/gallery/',
+        '/sw-test/gallery/bountyHunters.jpg',
+        '/sw-test/gallery/myLittleVader.jpg',
+        '/sw-test/gallery/snowTroopers.jpg'
+      ]);
+    })
+  );
+});
+ +
    +
  1. Here we add an install event listener to the service worker (hence this), 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.

+ +
this.addEventListener('fetch', function(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:

+ +
this.addEventListener('fetch', function(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 reject and we would just come up against a network error when a match isn’t found.

+ +

Fortunately service workers’ promise-based structure makes it trivial to provide further options towards success. We could do this:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).then(function(response) {
+      return response || fetch(event.request);
+    })
+  );
+});
+ +

If the resources isn't in the cache, it is 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:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).then(function(resp) {
+      return resp || fetch(event.request).then(function(response) {
+        return caches.open('v1').then(function(cache) {
+          cache.put(event.request, response.clone());
+          return response;
+        });
+      });
+    })
+  );
+});
+ +

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:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).then(function(resp) {
+      return resp || fetch(event.request).then(function(response) {
+        caches.open('v1').then(function(cache) {
+          cache.put(event.request, response.clone());
+        });
+        return response;
+      });
+    }).catch(function() {
+      return caches.match('/sw-test/gallery/myLittleVader.jpg');
+    })
+  );
+});
+ +

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):

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v2').then(function(cache) {
+      return cache.addAll([
+        '/sw-test/',
+        '/sw-test/index.html',
+        '/sw-test/style.css',
+        '/sw-test/app.js',
+        '/sw-test/image-list.js',
+
+        …
+
+        // include other new resources for the new version...
+      ]);
+    })
+  );
+});
+ +

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.

+ +
this.addEventListener('activate', function(event) {
+  var cacheWhitelist = ['v2'];
+
+  event.waitUntil(
+    caches.keys().then(function(keyList) {
+      return Promise.all(keyList.map(function(key) {
+        if (cacheWhitelist.indexOf(key) === -1) {
+          return caches.delete(key);
+        }
+      }));
+    })
+  );
+});
+ +

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:

+ + + +
+

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

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("33.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(40.0)}}{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}{{CompatNo}}{{ CompatVersionUnknown() }}{{CompatNo}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

+ +

See also

+ + diff --git a/files/pt-br/web/api/serviceworkercontainer/index.html b/files/pt-br/web/api/serviceworkercontainer/index.html new file mode 100644 index 0000000000..45a4406e9d --- /dev/null +++ b/files/pt-br/web/api/serviceworkercontainer/index.html @@ -0,0 +1,175 @@ +--- +title: ServiceWorkerContainer +slug: Web/API/ServiceWorkerContainer +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - Service worker API + - ServiceWorkerContainer + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerContainer +--- +

{{SeeCompatTable}}{{APIRef("Service Workers API")}}

+ +

ServiceWorkerContainer é a interface de ServiceWorker API 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.

+ +

Most importantly, it exposes the {{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} method used to register service workers, and the {{domxref("ServiceWorkerContainer.controller")}} property used to determine whether or not the current page is actively controlled.

+ +

Properties

+ +
+
{{domxref("ServiceWorkerContainer.controller")}} {{readonlyinline}}
+
Returns a {{domxref("ServiceWorker")}} object if its state is activated (the same object returned by {{domxref("ServiceWorkerRegistration.active")}}). This property returns null during a force-refresh request (Shift + refresh) or if there is no active worker.
+
+ +
+
{{domxref("ServiceWorkerContainer.ready")}} {{readonlyinline}}
+
Provides a way of delaying code execution until a service worker is active. It returns a {{jsxref("Promise")}} that will never reject, and which waits indefinitely until the {{domxref("ServiceWorkerRegistration")}} associated with the current page has an {{domxref("ServiceWorkerRegistration.active")}} worker. Once that condition is met, it resolves with the {{domxref("ServiceWorkerRegistration")}}.
+
+ +

Event handlers

+ +
+
{{domxref("ServiceWorkerContainer.oncontrollerchange")}}
+
Fired whenever a {{Event("controllerchange")}} event occurs — when the document's associated {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active","active")}} worker.
+
{{domxref("ServiceWorkerContainer.onerror")}}
+
Fired whenever an {{Event("error")}} event occurs in the associated service workers.
+
{{domxref("ServiceWorkerContainer.onmessage")}}
+
Fired whenever a {{Event("message")}} event occurs — when incoming messages are received to the {{domxref("ServiceWorkerContainer")}} object (e.g. via a {{domxref("MessagePort.postMessage()")}} call.)
+
+ +

Methods

+ +
+
{{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} 
+
Creates or updates a {{domxref("ServiceWorkerRegistration")}} for the given scriptURL.
+
{{domxref("ServiceWorkerContainer.getRegistration()")}}
+
Gets a {{domxref("ServiceWorkerRegistration")}} object whose scope matches the provided document URL.  If the method can't return a {{domxref("ServiceWorkerRegistration")}}, it returns a Promise
+
{{domxref("ServiceWorkerContainer.getRegistrations()")}}
+
Returns all {{domxref("ServiceWorkerRegistration")}} objects associated with a ServiceWorkerContainer in an array.  If the method can't return {{domxref("ServiceWorkerRegistration")}} objects, it returns a Promise
+
+ +

Examples

+ +

The example below first checks to see if the browser supports service workers. If supported, the code registers the service worker and determines if the page is actively controlled by the service worker. If it isn't, it prompts the user to reload the page so the service worker can take control. The code also reports any registration failures.

+ +
if ('serviceWorker' in navigator) {
+  // Register a service worker hosted at the root of the
+  // site using the default scope.
+  navigator.serviceWorker.register('/sw.js').then(function(registration) {
+    console.log('Service worker registration succeeded:', registration);
+
+    // At this point, you can optionally do something
+    // with registration. See https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
+  }).catch(function(error) {
+    console.log('Service worker registration failed:', error);
+  });
+
+  // Independent of the registration, let's also display
+  // information about whether the current page is controlled
+  // by an existing service worker, and when that
+  // controller changes.
+
+  // First, do a one-off check if there's currently a
+  // service worker in control.
+  if (navigator.serviceWorker.controller) {
+    console.log('This page is currently controlled by:', navigator.serviceWorker.controller);
+  }
+
+  // Then, register a handler to detect when a new or
+  // updated service worker takes control.
+  navigation.serviceWorker.oncontrollerchange = function() {
+    console.log('This page is now controlled by:', navigator.serviceWorker.controller);
+  };
+} else {
+  console.log('Service workers are not supported.');
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-container', 'ServiceWorkerContainer')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatOpera(27)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(40)}}{{CompatChrome(40)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatOperaMobile(27)}}{{CompatNo}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

+ +

See also

+ + diff --git a/files/pt-br/web/api/serviceworkercontainer/register/index.html b/files/pt-br/web/api/serviceworkercontainer/register/index.html new file mode 100644 index 0000000000..cb27ddc843 --- /dev/null +++ b/files/pt-br/web/api/serviceworkercontainer/register/index.html @@ -0,0 +1,140 @@ +--- +title: ServiceWorkerContainer.register() +slug: Web/API/ServiceWorkerContainer/register +translation_of: Web/API/ServiceWorkerContainer/register +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

O método register()da interface {{domxref("ServiceWorkerContainer")}} cria ou atualiza um {{domxref("ServiceWorkerRegistration")}} passado em scriptURL.

+ +

Em caso de sucesso, um registro de service worker vincula o URL do script fornecido ao escopo, que é usado posteriormente para a navegação correspondente. Você pode chamar esse método incondicionalmente da página controlada. Ou seja, você não precisa primeiro verificar se há um registro ativo.

+ +

Há uma frequente confusão em relação ao significado e uso do escopo. Uma vez que um service worker não pode ter um escopo mais amplo do que sua própria localização, use apenas a opção `scope` quando precisar de um escopo mais limitado do que o padrão.

+ +

Síntaxe

+ +
ServiceWorkerContainer.register(scriptURL, options)
+  .then(function(ServiceWorkerRegistration) { ... });
+ +

Parâmetros

+ +
+
scriptURL
+
A URL do script service worker.
+
options {{optional_inline}}
+
Um objeto contendo as opções do registro. Atualmente as opções disponíveis são: +
    +
  • scope: Uma {{domxref("USVString")}} representando uma URL que define o registro do escopo de um service worker's ; ou seja, o alcance das URLs que o service worker pode controlar. É geralmente uma URL relativa. O valor padrão é o URL que você obtém se você resolvesse './' usando a localização da página web como  base.  Não é, como customa-se acreditar, relativo à localização do service worker. Veja as seções de Exemplos para mais informações sobre como isso funciona.
  • +
+
+
+ +

Valor retornado

+ +

Um {{domxref("Promise")}} que resolve com um objeto {{domxref("ServiceWorkerRegistration")}}.

+ +

Exemplos

+ +

Os exemplos descritos escrito aqui deve ser tomado em conjunto para obter um melhor entendimento de como escopos do service workers são aplicados a uma página. 

+ +

O exemplo a seguir usa o valor padrão descope (ao omití-lo). O service worker neste caso irá controlarexample.com/index.html bem como páginas abaixo, como example.com/product/description.html.

+ +
if ('serviceWorker' in navigator) {
+  // Registra um service worker hospeadado na raiz do
+  // site usando o escopo padrão
+  navigator.serviceWorker.register('/sw.js').then(function(registration) {
+    console.log('Service worker  registrado com sucesso:', registration);
+  }).catch(function(error) {
+    console.log('Falha ao Registrar o Service Worker:', error);
+  });
+} else {
+  console.log('Service workers não suportado!');
+}
+ +

O código a seguir,  se incluído em uma página na raiz de um site, seria aplicado  exatamente às mesmas páginas, como no exemplo acima. Lembre-se de que o escopo, quando incluído, usa a localização da página como base. Alternativamente, se esse código foi incluído em uma página example.com/product/description.html,  o escopo de'./' significa que o escopo que o service worker seria aplicado somente  aos recursos deexample.com/product.  Se precisassemos de registrar um service worker em example.com/product/description.html aplicado a todoo example.com, deixaríamos o escopo acima.

+ +
if ('serviceWorker' in navigator) {
+  // Registre um service worker hospeado na raiz do
+  // site usando um escopo mais restritivo.
+  navigator.serviceWorker.register('/sw.js', {scope: './'}).then(function(registration) {
+    console.log('Service worker registrado com sucesso:', registration);
+  }).catch(function(error) {
+    console.log('Service worker falhou ao registrar:', error);
+  });
+} else {
+  console.log('Service workers não é suportado pelo navegador!.');
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Service Workers', '#service-worker-container', 'ServiceWorkerContainer')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Compatibilidade com Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatOpera(27)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(40)}}{{CompatChrome(40)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatOperaMobile(27)}}{{CompatNo}}
+
+ +

[1] Os Service workers (e Push) foram desativados no Firefox 45 e 52 Extended Support Releases (ESR.)

diff --git a/files/pt-br/web/api/serviceworkerglobalscope/clients/index.html b/files/pt-br/web/api/serviceworkerglobalscope/clients/index.html new file mode 100644 index 0000000000..6792b3b96c --- /dev/null +++ b/files/pt-br/web/api/serviceworkerglobalscope/clients/index.html @@ -0,0 +1,63 @@ +--- +title: ServiceWorkerGlobalScope.clients +slug: Web/API/ServiceWorkerGlobalScope/clients +tags: + - API + - Clients + - Service Worker + - Service Workers + - ServiceWorker + - ServiceWorkerGlobalScope + - ServiceWorkers +translation_of: Web/API/ServiceWorkerGlobalScope/clients +--- +

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

+ +

A propriedade somente-leitura clients da interface {{domxref("ServiceWorkerGlobalScope")}} retorna os objetos dos Clients associatos ao service worker.

+ +

Sintaxe

+ +
swClients = self.clients
+
+ +

Valor

+ +

O objeto {{domxref("Clients")}} associado ao service worker específico.

+ +

Especificações

+ +
 
+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-global-scope-clients', 'ServiceWorkerRegistration.clients')}}{{Spec2('Service Workers')}}Initial definition.
+  
+ +

Compatibilidade

+ +
+ + +

{{Compat("api.ServiceWorkerGlobalScope.clients")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/serviceworkerglobalscope/index.html b/files/pt-br/web/api/serviceworkerglobalscope/index.html new file mode 100644 index 0000000000..3f4115cbab --- /dev/null +++ b/files/pt-br/web/api/serviceworkerglobalscope/index.html @@ -0,0 +1,152 @@ +--- +title: ServiceWorkerGlobalScope +slug: Web/API/ServiceWorkerGlobalScope +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - ServiceWorkerGlobalScope + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerGlobalScope +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

The ServiceWorkerGlobalScope interface of the ServiceWorker API represents the global execution context of a service worker.

+ +

Developers should keep in mind that the ServiceWorker state is not persisted across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state.

+ +

Once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. An active service worker is automatically restarted to respond to events, such as {{domxref("ServiceWorkerGlobalScope.onfetch")}} or {{domxref("ServiceWorkerGlobalScope.onmessage")}}.

+ +

Additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the {{domxref("GlobalFetch.fetch", "fetch()")}} method, can be used.

+ +

This interface inherits from the {{domxref("WorkerGlobalScope")}} interface, and its parent {{domxref("EventTarget")}}, and therefore implements properties from {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, and {{domxref("WindowEventHandlers")}}.

+ +

{{InheritanceDiagram(700, 85, 20)}}

+ +

Properties

+ +
+
{{domxref("ServiceWorkerGlobalScope.clients")}} {{readonlyinline}}
+
Contains the {{domxref("Clients")}} object associated with the service worker.
+
{{domxref("ServiceWorkerGlobalScope.registration")}} {{readonlyinline}}
+
Contains the {{domxref("ServiceWorkerRegistration")}} object that represents the service worker's registration.
+
{{domxref("ServiceWorkerGlobalScope.caches")}} {{readonlyinline}}
+
Contains the {{domxref("CacheStorage")}} object associated with the service worker.
+
+ +

Events

+ +
+
activate
+
Occurs when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active")}} worker.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onactivate")}} property.
+
fetch
+
Occurs when a {{domxref("GlobalFetch.fetch", "fetch()")}} is called.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onfetch")}} property.
+
install
+
Occurs when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.installing")}} worker.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.oninstall")}} property.
+
message
+
Occurs when incoming messages are received. Controlled pages can use the {{domxref("MessagePort.postMessage()")}} method to send messages to service workers. The service worker can optionally send a response back via the {{domxref("MessagePort")}} exposed in event.data.port, corresponding to the controlled page.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onmessage")}} property.
+
notificationclick
+
Occurs when a user clicks on a displayed notification.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onnotificationclick")}} property.
+
notificationclose
+
Occurs — when a user closes a displayed notification.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onnotificationclose")}} property.
+
push
+
Occurs when a server push notification is received.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onpush")}} property.
+
pushsubscriptionchange
+
Occurs when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time).
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}} property.
+
sync
+
Triggered when a call to {{domxref("SyncManager.register")}} is made from a service worker client page. The attempt to sync is made either immediately if the network is available or as soon as the network becomes available. 
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onsync")}} property.
+
+ +

Methods

+ +
+
{{domxref("ServiceWorkerGlobalScope.skipWaiting()")}}
+
Allows the current service worker registration to progress from waiting to active state while service worker clients are using it.
+
+ +

ServiceWorkerGlobalScope implements {{domxref("WorkerGlobalScope")}} — which implements {{domxref("WindowOrWorkerGlobalScope")}}. Therefore it also has the following property available to it:

+ +
+
{{domxref("GlobalFetch.fetch()")}}
+
Starts the process of fetching a resource. This returns a promise that resolves to the {{domxref("Response")}} object representing the response to your request. This algorithm is the entry point for the fetch handling handed to the service worker context.
+
+ +

Examples

+ +

This code snippet is from the service worker prefetch sample (see prefetch example live.) The {{domxref("ServiceWorkerGlobalScope.onfetch")}} event handler listens for the fetch event. When fired, the code returns a promise that resolves to the first matching request in the {{domxref("Cache")}} object. If no match is found, the code fetches a response from the network.

+ +

The code also handles exceptions thrown from the {{domxref("GlobalFetch.fetch", "fetch()")}} operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set.

+ +
self.addEventListener('fetch', function(event) {
+  console.log('Handling fetch event for', event.request.url);
+
+  event.respondWith(
+    caches.match(event.request).then(function(response) {
+      if (response) {
+        console.log('Found response in cache:', response);
+
+        return response;
+      }
+      console.log('No response found in cache. About to fetch from network...');
+
+      return fetch(event.request).then(function(response) {
+        console.log('Response from network is:', response);
+
+        return response;
+      }, function(error) {
+        console.error('Fetching failed:', error);
+
+        throw error;
+      });
+    })
+  );
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#serviceworkerglobalscope-interface', 'ServiceWorkerGlobalScope')}}{{Spec2('Service Workers')}}Initial definition
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/sharedworker/index.html b/files/pt-br/web/api/sharedworker/index.html new file mode 100644 index 0000000000..6aa6257435 --- /dev/null +++ b/files/pt-br/web/api/sharedworker/index.html @@ -0,0 +1,188 @@ +--- +title: SharedWorker +slug: Web/API/SharedWorker +tags: + - API + - Interface + - NeedsTranslation + - Reference + - SharedWorker + - TopicStub + - Web Workers + - Workers +translation_of: Web/API/SharedWorker +--- +
{{APIRef("Web Workers API")}}
+ +

The SharedWorker interface represents a specific kind of worker that can be accessed from several browsing contexts, such as several windows, iframes or even workers. They implement an interface different than dedicated workers and have a different global scope, {{domxref("SharedWorkerGlobalScope")}}.

+ +
+

Note: If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host and port).

+
+ +
+

Note: In Firefox, shared workers cannot be shared between private (i.e. browsing in a private window) and non-private documents (see {{bug(1177621)}}.)

+
+ +

Constructors

+ +
+
{{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}
+
Creates a shared web worker that executes the script at the specified URL.
+
+ +

Properties

+ +

Inherits properties from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
Is an {{domxref("EventListener")}} that is called whenever an {{domxref("ErrorEvent")}} of type error bubbles through the worker.
+
{{domxref("SharedWorker.port")}} {{readonlyInline}}
+
Returns a {{domxref("MessagePort")}} object used to communicate and control the shared worker.
+
+ +
+
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("EventTarget")}}, and implements methods from {{domxref("AbstractWorker")}}.

+ +

Example

+ +

In our Basic shared worker example (run shared worker), we have two HTML pages, each of which uses some JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows.

+ +

The following code snippet shows creation of a SharedWorker object using the {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} constructor. Both scripts contain this:

+ +
var myWorker = new SharedWorker('worker.js');
+
+ +

Both scripts then access the worker through a {{domxref("MessagePort")}} object created using the {{domxref("SharedWorker.port")}} property. If the onmessage event is attached using addEventListener, the port is manually started using its start() method:

+ +
myWorker.port.start();
+ +

When the port is started, both scripts post messages to the worker and handle messages sent from it using port.postMessage() and port.onmessage, respectively:

+ +
first.onchange = function() {
+  myWorker.port.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+second.onchange = function() {
+  myWorker.port.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+myWorker.port.onmessage = function(e) {
+  result1.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

Inside the worker we use the {{domxref("SharedWorkerGlobalScope.onconnect")}} handler to connect to the same port discussed above. The ports associated with that worker are accessible in the {{event("connect")}} event's ports property — we then use {{domxref("MessagePort")}} start() method to start the port, and the onmessage handler to deal with messages sent from the main threads.

+ +
onconnect = function(e) {
+  var port = e.ports[0];
+
+  port.addEventListener('message', function(e) {
+    var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
+    port.postMessage(workerResult);
+  });
+
+  port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#sharedworker", "SharedWorker")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Support{{CompatChrome(4)}}{{CompatGeckoDesktop(29.0)}}{{CompatNo}}{{CompatOpera(10.60)}}5
+ {{CompatNo}} 6.1
Constructor name option{{CompatVersionUnknown}}{{CompatGeckoDesktop(55)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("33.0")}}{{CompatNo}}11.55.1
+ {{CompatNo}} 7.1
Constructor name option{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(55)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/sharedworker/port/index.html b/files/pt-br/web/api/sharedworker/port/index.html new file mode 100644 index 0000000000..248878949c --- /dev/null +++ b/files/pt-br/web/api/sharedworker/port/index.html @@ -0,0 +1,111 @@ +--- +title: SharedWorker.port +slug: Web/API/SharedWorker/port +translation_of: Web/API/SharedWorker/port +--- +
{{APIRef("Web Workers API")}}
+ +

A propriedade port do {{domxref ("SharedWorker")}} retorna um objeto {{domxref ("MessagePort")}} usado para comunicar e controlar o shared worker.

+ +

 

+ +

Sintaxe

+ +
myWorker.port;
+ +

Valor

+ +

Um objeto {{domxref("MessagePort")}}.

+ +

Exemplo

+ +

O snippet de código a seguir mostra a criação de um objeto SharedWorker usando o construtor {{domxref ("SharedWorker.SharedWorker", "SharedWorker ()")}} . Vários scripts podem acessar o worker através de um objeto do tipo {{domxref ("MessagePort")}} , usando a propriedade SharedWorker.port  — A porta é iniciada usando o método start() .

+ +
var myWorker = new SharedWorker('worker.js');
+myWorker.port.start();
+ +

Veja um exemplo completo Basic shared worker example (run shared worker.)

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-sharedworker-port", "AbstractWorker.onerror")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#dom-sharedworker-port", "AbstractWorker.onerror")}}{{Spec2('Web Workers')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Support{{CompatChrome(4)}}{{CompatGeckoDesktop(29.0)}}{{CompatNo}}{{CompatOpera(10.60)}}5
+ {{CompatNo}} 6.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("33.0")}}2.1{{CompatNo}}11.55.1
+ {{CompatNo}} 7.1
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/speechgrammar/index.html b/files/pt-br/web/api/speechgrammar/index.html new file mode 100644 index 0000000000..c1a3aac1cf --- /dev/null +++ b/files/pt-br/web/api/speechgrammar/index.html @@ -0,0 +1,79 @@ +--- +title: SpeechGrammar +slug: Web/API/SpeechGrammar +tags: + - API + - Experimental + - Fala + - Interface + - Referencia + - SpeechGrammar + - Web Speech API + - reconhecimento +translation_of: Web/API/SpeechGrammar +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

A interface SpeechGrammar da Web Speech API representa um conjunto de palavras ou padrões de palavras, os quais, nós queremos que o serviço de reconhecimento reconheça.

+ +

A gramática é definida usando JSpeech Grammar Format (JSGF.) Outros formatos podem ser suportados no futuro.

+ +

Construtor

+ +
+
{{domxref("SpeechGrammar.SpeechGrammar()")}}
+
Cria um novo objeto SpeechGrammar.
+
+ +

Propriedades

+ +
+
{{domxref("SpeechGrammar.src")}}
+
Define e retorna a string contendo a gramática contida na instância do objeto SpeechGrammar.
+
{{domxref("SpeechGrammar.weight")}} {{optional_inline}}
+
Define e retorna o peso do objeto SpeechGrammar.
+
+ +

Exemplos

+ +
var grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;'
+var recognition = new SpeechRecognition();
+var speechRecognitionList = new SpeechGrammarList();
+speechRecognitionList.addFromString(grammar, 1);
+recognition.grammars = speechRecognitionList;
+
+
+console.log(speechRecognitionList[0].src); // deveria retornar o mesmo conteúdo da variável grammar
+console.log(speechRecognitionList[0].weight); // deveria retornar 1 - o mesmo peso definido na linha 4.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#speechreco-speechgrammar', 'SpeechGrammar')}}{{Spec2('Web Speech API')}} 
+ +

Compatibilidade com os navegadores

+ +
+ + +

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

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/speechsynthesis/index.html b/files/pt-br/web/api/speechsynthesis/index.html new file mode 100644 index 0000000000..889e129516 --- /dev/null +++ b/files/pt-br/web/api/speechsynthesis/index.html @@ -0,0 +1,194 @@ +--- +title: SpeechSynthesis +slug: Web/API/SpeechSynthesis +tags: + - API + - Elocução + - Experimental + - Fala + - Interface + - Referencia + - SpeechSynthesis + - Web Speech API + - sintetização +translation_of: Web/API/SpeechSynthesis +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

A interface SpeechSynthesis da Web Speech API é a interface controladora para o serviço de fala; este pode ser usado para obter informações sobre as vozes sintetizadas disponíveis no dispositivo, reproduzir e pausar uma elocução, além de outros comandos.

+ +

Propriedades

+ +

SpeechSynthesis também herda propriedades da sua interface pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesis.paused")}} {{readonlyinline}}
+
Um {{domxref("Boolean")}} que retorna true se o objeto SpeechSynthesis está em estado de pausa.
+
{{domxref("SpeechSynthesis.pending")}} {{readonlyinline}}
+
Um {{domxref("Boolean")}} que retorna true se a fila de elocuções contém falas que ainda não foram reproduzidas.
+
{{domxref("SpeechSynthesis.speaking")}} {{readonlyinline}}
+
Um {{domxref("Boolean")}} que retorna true se uma elocução está sendo reproduzida atualmente — mesmo que SpeechSynthesis esteja em estado de pausa.
+
+ +

Tratamento de eventos

+ +
+
{{domxref("SpeechSynthesis.onvoiceschanged")}}
+
Disparado quando a lista de objetos {{domxref("SpeechSynthesisVoice")}} que pode ser retornada pelo método {{domxref("SpeechSynthesis.getVoices()")}} mudou.
+
+ +

Métodos

+ +

SpeechSynthesis também herda métodos da sua interface pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesis.cancel()")}}
+
Remove todas as elocuções da fila para reprodução.
+
{{domxref("SpeechSynthesis.getVoices()")}}
+
Retorna uma lista de objetos {{domxref("SpeechSynthesisVoice")}} representando todas as vozes disponíveis no dispositivo atuall
+
{{domxref("SpeechSynthesis.pause()")}}
+
Deixa o objeto SpeechSynthesis em estado de pausa.
+
{{domxref("SpeechSynthesis.resume()")}}
+
Retira o estado de pausa do objeto SpeechSynthesis: retoma a reprodução se ele estiver pausado.
+
{{domxref("SpeechSynthesis.speak()")}}
+
Adiciona uma {{domxref("SpeechSynthesisUtterance", "utterance")}} à fila de reprodução; ela será reproduzida assim que todas as elocuções enfileiradas anteriormente tenham sido reproduzidas.
+
+ +

Exemplos

+ +

Na nossa demonstração básica Speech synthesiser demo, nós primeiro pegamos uma referência para o controlador SpeechSynthesis usando window.speechSynthesis. Após definir algumas variáveis necessárias, nós obtemos uma lista de vozes disponíveis usando o método {{domxref("SpeechSynthesis.getVoices()")}} usando-as para popular um menu de seleção de forma que o usuário possa escolher a voz que desejar.

+ +

Dentro do tratamento inputForm.onsubmit, nós impedimos a submissão do formulário com preventDefault(),  instanciamos uma {{domxref("SpeechSynthesisUtterance")}} contendo o texto presente no {{htmlelement("input")}}, atribuímos a voz da elocução para a voz selecionada no elemento {{htmlelement("select")}}, e iniciamos a reprodução da elocução através do método {{domxref("SpeechSynthesis.speak()")}}.

+ +
var synth = window.speechSynthesis;
+
+var inputForm = document.querySelector('form');
+var inputTxt = document.querySelector('.txt');
+var voiceSelect = document.querySelector('select');
+
+var pitch = document.querySelector('#pitch');
+var pitchValue = document.querySelector('.pitch-value');
+var rate = document.querySelector('#rate');
+var rateValue = document.querySelector('.rate-value');
+
+var voices = [];
+
+function populateVoiceList() {
+  voices = synth.getVoices();
+
+  for(i = 0; i < voices.length ; i++) {
+    var option = document.createElement('option');
+    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
+
+    if(voices[i].default) {
+      option.textContent += ' -- DEFAULT';
+    }
+
+    option.setAttribute('data-lang', voices[i].lang);
+    option.setAttribute('data-name', voices[i].name);
+    voiceSelect.appendChild(option);
+  }
+}
+
+populateVoiceList();
+if (speechSynthesis.onvoiceschanged !== undefined) {
+  speechSynthesis.onvoiceschanged = populateVoiceList;
+}
+
+inputForm.onsubmit = function(event) {
+  event.preventDefault();
+
+  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
+  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
+  for(i = 0; i < voices.length ; i++) {
+    if(voices[i].name === selectedOption) {
+      utterThis.voice = voices[i];
+    }
+  }
+  utterThis.pitch = pitch.value;
+  utterThis.rate = rate.value;
+  synth.speak(utterThis);
+
+  inputTxt.blur();
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentários
{{SpecName('Web Speech API', '#tts-section', 'SpeechSynthesis')}}{{Spec2('Web Speech API')}} 
+ +

Compatibilidade de Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(33)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(49)}}{{CompatNo}}{{CompatUnknown}}7
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}2.0{{CompatNo}}{{CompatNo}}7.1
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/speechsynthesisutterance/index.html b/files/pt-br/web/api/speechsynthesisutterance/index.html new file mode 100644 index 0000000000..96c51a0c87 --- /dev/null +++ b/files/pt-br/web/api/speechsynthesisutterance/index.html @@ -0,0 +1,177 @@ +--- +title: SpeechSynthesisUtterance +slug: Web/API/SpeechSynthesisUtterance +tags: + - API + - Experimental + - Interface + - NeedsTranslation + - Reference + - SpeechSynthesisUtterance + - TopicStub + - Web Speech API + - speech + - synthesis +translation_of: Web/API/SpeechSynthesisUtterance +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

The SpeechSynthesisUtterance interface of the Web Speech API represents a speech request. It contains the content the speech service should read and information about how to read it (e.g. language, pitch and volume.)

+ +

Constructor

+ +
+
{{domxref("SpeechSynthesisUtterance.SpeechSynthesisUtterance()")}}
+
Returns a new SpeechSynthesisUtterance object instance.
+
+ +

Properties

+ +

SpeechSynthesisUtterance also inherits properties from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesisUtterance.lang")}}
+
Gets and sets the language of the utterance.
+
{{domxref("SpeechSynthesisUtterance.pitch")}}
+
Gets and sets the pitch at which the utterance will be spoken at.
+
{{domxref("SpeechSynthesisUtterance.rate")}}
+
Gets and sets the speed at which the utterance will be spoken at.
+
{{domxref("SpeechSynthesisUtterance.text")}}
+
Gets and sets the text that will be synthesised when the utterance is spoken.
+
{{domxref("SpeechSynthesisUtterance.voice")}}
+
Gets and sets the voice that will be used to speak the utterance.
+
{{domxref("SpeechSynthesisUtterance.volume")}}
+
Gets and sets the volume that the utterance will be spoken at.
+
+ +

Event handlers

+ +
+
{{domxref("SpeechSynthesisUtterance.onboundary")}}
+
Fired when the spoken utterance reaches a word or sentence boundary.
+
{{domxref("SpeechSynthesisUtterance.onend")}}
+
Fired when the utterance has finished being spoken.
+
{{domxref("SpeechSynthesisUtterance.onerror")}}
+
Fired when an error occurs that prevents the utterance from being succesfully spoken.
+
{{domxref("SpeechSynthesisUtterance.onmark")}}
+
Fired when the spoken utterance reaches a named SSML "mark" tag.
+
{{domxref("SpeechSynthesisUtterance.onpause")}}
+
Fired when the utterance is paused part way through.
+
{{domxref("SpeechSynthesisUtterance.onresume")}}
+
Fired when a paused utterance is resumed.
+
{{domxref("SpeechSynthesisUtterance.onstart")}}
+
Fired when the utterance has begun to be spoken.
+
+ +

Examples

+ +

In our basic Speech synthesiser demo, we first grab a reference to the SpeechSynthesis controller using window.speechSynthesis. After defining some necessary variables, we retrieve a list of the voices available using {{domxref("SpeechSynthesis.getVoices()")}} and populate a select menu with them so the user can choose what voice they want.

+ +

Inside the inputForm.onsubmit handler, we stop the form submitting with preventDefault(),  use the {{domxref("SpeechSynthesisUtterance.SpeechSynthesisUtterance()", "constructor")}} to create a new utterance instance containing the text from the text {{htmlelement("input")}}, set the utterance's {{domxref("SpeechSynthesisUtterance.voice","voice")}} to the voice selected in the {{htmlelement("select")}} element, and start the utterance speaking via the {{domxref("SpeechSynthesis.speak()")}} method.

+ +
var synth = window.speechSynthesis;
+
+var inputForm = document.querySelector('form');
+var inputTxt = document.querySelector('input');
+var voiceSelect = document.querySelector('select');
+
+var voices = synth.getVoices();
+
+for(i = 0; i < voices.length ; i++) {
+  var option = document.createElement('option');
+  option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
+  option.setAttribute('data-lang', voices[i].lang);
+  option.setAttribute('data-name', voices[i].name);
+  voiceSelect.appendChild(option);
+}
+
+inputForm.onsubmit = function(event) {
+  event.preventDefault();
+
+  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
+  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
+  for(i = 0; i < voices.length ; i++) {
+    if(voices[i].name === selectedOption) {
+      utterThis.voice = voices[i];
+    }
+  }
+  synth.speak(utterThis);
+  inputTxt.blur();
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#utterance-attributes', 'SpeechSynthesisUtterance')}}{{Spec2('Web Speech API')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(33)}}{{CompatGeckoDesktop(49)}}{{CompatNo}}{{CompatUnknown}}7
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}2.0{{CompatNo}}{{CompatNo}}7.1
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/speechsynthesisutterance/voice/index.html b/files/pt-br/web/api/speechsynthesisutterance/voice/index.html new file mode 100644 index 0000000000..22f884d58b --- /dev/null +++ b/files/pt-br/web/api/speechsynthesisutterance/voice/index.html @@ -0,0 +1,130 @@ +--- +title: SpeechSynthesisUtterance.voice +slug: Web/API/SpeechSynthesisUtterance/voice +tags: + - API + - Experimental + - Fala + - SpeechSynthesisUtterance + - Voz + - Web Speech API +translation_of: Web/API/SpeechSynthesisUtterance/voice +--- +
{{APIRef("Web Speech API")}}{{SeeCompatTable}}
+ +

A propriedade voice  da interface {{domxref("SpeechSynthesisUtterance")}} retorna e configura a voz que será usada para a fala.

+ +

Essa propriedade deve ser configurada para um dos objetos {{domxref("SpeechSynthesisVoice")}} retornado por {{domxref("SpeechSynthesis.getVoices()")}}. Se não for configurada no momento da fala, a voz usada será a determinada como default na propriedade {{domxref("SpeechSynthesisUtterance.lang","lang")}}.

+ +

Sintaxe

+ +
var myVoice = speechSynthesisUtteranceInstance.voice;
+speechSynthesisUtteranceInstance.voice = speechSynthesisVoiceInstance;
+
+ +

Valor

+ +

Um objeto {{domxref("SpeechSynthesisVoice")}}.

+ +

Examplo

+ +
var synth = window.speechSynthesis;
+
+var inputForm = document.querySelector('form');
+var inputTxt = document.querySelector('input');
+var voiceSelect = document.querySelector('select');
+
+var voices = synth.getVoices();
+
+  ...
+
+inputForm.onsubmit = function(event) {
+  event.preventDefault();
+
+  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
+  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
+  for(i = 0; i < voices.length ; i++) {
+    if(voices[i].name === selectedOption) {
+      utterThis.voice = voices[i];
+    }
+  }
+  synth.speak(utterThis);
+  inputTxt.blur();
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Speech API', '#dfn-utterancevoice', 'voice')}}{{Spec2('Web Speech API')}} 
+ +

Compatiblidade dos navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(33)}}{{CompatGeckoDesktop(49)}}{{CompatNo}}{{CompatUnknown}}7
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}2.0{{CompatNo}}{{CompatNo}}7.1
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/storage/clear/index.html b/files/pt-br/web/api/storage/clear/index.html new file mode 100644 index 0000000000..7542b3873a --- /dev/null +++ b/files/pt-br/web/api/storage/clear/index.html @@ -0,0 +1,131 @@ +--- +title: Storage.clear() +slug: Web/API/Storage/clear +tags: + - API + - Armazenamento + - Armazenamento web + - Referencia + - metodo +translation_of: Web/API/Storage/clear +--- +

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

+ +

O método clear() da interface {{domxref("Storage")}}, quando realizado uma chamada, todas as chaves do armazenamento são esvaziadas.

+ +

Syntaxe

+ +
storage.clear();
+ +

Parametros

+ +

Nenhum parametro..

+ +

Retorno

+ +

Nenhum retorno.

+ +

 

+ +

Exemplo

+ +

 

+ +

A função abaixo cria três itens e armazenam localmente, depois remove todos utilizando a função clear().

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+
+  localStorage.clear();
+}
+ +
+

Nota: Para visualizar um exemplo real, veja nossa seção Demonstração de Web Storage.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Storage', '#dom-storage-clear', 'clear()')}}{{Spec2('Web Storage')}} 
+ +

Compatibilidade de navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

Todos os navegadores possuem diferentes capacidades tanto para o localSotrage quanto para sessionSotrage. Você pode verificar uma lista detalhada de capacidades de diversos navegadores.

+ +
+

Nota: a versão iOS 5.1, Safari Mobile utiliza a pasta cache para armazenar os dados do localStorage, onde possivelmente podem perder os dados quando ocorrer pouco espaço no SO.

+
+ +

Veja também

+ +

Utilizando a API Web Storage

diff --git a/files/pt-br/web/api/storage/getitem/index.html b/files/pt-br/web/api/storage/getitem/index.html new file mode 100644 index 0000000000..46c49c6e0c --- /dev/null +++ b/files/pt-br/web/api/storage/getitem/index.html @@ -0,0 +1,79 @@ +--- +title: localStorage.getItem() +slug: Web/API/Storage/getItem +translation_of: Web/API/Storage/getItem +--- +

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

+ +

Passar o nome da chave para o método getItem() da interface {{domxref("Storage")}} retornará o seu valor.

+ +

Sintaxe

+ +
var aValue = localStorage.getItem(keyName);
+
+ +

Parâmetros

+ +
+
keyName
+
Um {{domxref("DOMString")}} contendo o nome da chave cujo valor você quer obter.
+
+ +

Retorno

+ +

Um {{domxref("DOMString")}} contendo o valor da chave. Se a chave não existe, é retornado null.

+ +

Exemplo

+ +

A função seguinte recupera três itens armazenados no local storage e usa-os para definir estilos customizados em uma página.

+ +
function setStyles() {
+  var currentColor = localStorage.getItem('bgcolor');
+  var currentFont = localStorage.getItem('font');
+  var currentImage = localStorage.getItem('image');
+
+  document.getElementById('bgcolor').value = currentColor;
+  document.getElementById('font').value = currentFont;
+  document.getElementById('image').value = currentImage;
+
+  htmlElem.style.backgroundColor = '#' + currentColor;
+  pElem.style.fontFamily = currentFont;
+  imgElem.setAttribute('src', currentImage);
+}
+ +
+

Nota: Para ver essa funcionalidade aplicada a um exemplo real, veja nossa Web Storage Demo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('Web Storage', '#dom-storage-getitem', 'getItem()')}}{{Spec2('Web Storage')}}
+ +

Compatibilidade

+ +
{{Compat("api.Storage.getItem")}}
+ +
+ +

Os níveis de compatibilidade podem variar em todos os navegadores, tanto para o localStorage quanto para o sessionStorage. Aqui temos estatísticas detalhadas dos níveis de compatibilidade para vários navegadores.

+ +
+

Nota: A partir da versão 5.1 do iOS, o Safari Mobile armazena os dados do localStorage na pasta do cache, sujeito a ser apagado em caso de espaço insificiente.

+
+ +

Veja também

+ +

Usando a API Web Storage

diff --git a/files/pt-br/web/api/storage/index.html b/files/pt-br/web/api/storage/index.html new file mode 100644 index 0000000000..e500e88cfa --- /dev/null +++ b/files/pt-br/web/api/storage/index.html @@ -0,0 +1,119 @@ +--- +title: Storage +slug: Web/API/Storage +tags: + - API + - Interface + - NeedsTranslation + - Reference + - Storage + - TopicStub + - Web Storage + - data +translation_of: Web/API/Storage +--- +

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

+ +

A interface de Armazenamento da Web Storage API fornece acesso ao armazenamento de sessão ou armazenamento local para um domínio específico, permitindo que você, por exemplo, adicione, modifique ou exclua itens de dados armazenados.

+ +

Se você quiser manipular o armazenamento de sessão para um domínio, você chama o método {{domxref ("Window.sessionStorage")}}; Se você quiser manipular o armazenamento local para um domínio, você chama {{domxref ("Window.localStorage")}}.

+ +

Propriedades

+ +
+
{{domxref("Storage.length")}} {{readonlyInline}}
+
Retorna um número inteiro que representa o número de itens de dados armazenados no objeto Storage.
+
+ +

Métodos

+ +
+
{{domxref("Storage.key()")}}
+
Quando passado um número n, este método retornará o nome da n-ésima chave no armazenamento..
+
+ +
+
{{domxref("Storage.getItem()")}}
+
Quando passado um nome de chave, retornará o valor dessa chave.
+
{{domxref("Storage.setItem()")}}
+
Quando passado um nome de chave e valor, irá adicionar essa chave para o armazenamento, ou atualizar o valor dessa chave, se já existir.
+
{{domxref("Storage.removeItem()")}}
+
Quando passado um nome de chave, irá remover essa chave do armazenamento.
+
{{domxref("Storage.clear()")}}
+
Quando chamado, irá esvaziar todas as chaves fora do armazenamento.
+
+ +

Exemplos

+ +

Aqui acessamos um objeto Storage chamando localStorage. Primeiro testamos se o armazenamento local contém itens de dados usando! localStorage.getItem ('bgcolor'). Se isso acontecer, executaremos uma função chamada setStyles () que agarra os itens de dados usando {{domxref("localStorage.getItem()")}} E usa esses valores para atualizar estilos de página. Se não, executamos outra função, populateStorage (), que usa {{domxref("localStorage.setItem()")}} Para definir os valores do item, em seguida, executa setStyles ().

+ +
if(!localStorage.getItem('bgcolor')) {
+  populateStorage();
+} else {
+  setStyles();
+}
+
+function populateStorage() {
+  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
+  localStorage.setItem('font', document.getElementById('font').value);
+  localStorage.setItem('image', document.getElementById('image').value);
+
+  setStyles();
+}
+
+function setStyles() {
+  var currentColor = localStorage.getItem('bgcolor');
+  var currentFont = localStorage.getItem('font');
+  var currentImage = localStorage.getItem('image');
+
+  document.getElementById('bgcolor').value = currentColor;
+  document.getElementById('font').value = currentFont;
+  document.getElementById('image').value = currentImage;
+
+  htmlElem.style.backgroundColor = '#' + currentColor;
+  pElem.style.fontFamily = currentFont;
+  imgElem.setAttribute('src', currentImage);
+}
+ +
+

Nota: Para ver isso funcionando como um exemplo completo de trabalho, consulte nossa Demonstração de armazenamento na Web.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Web Storage', '#the-storage-interface', 'Storage')}}{{Spec2('Web Storage')}} 
+ +

Compatibilidade com navegadores

+ +

 

+ + + +

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

+ +

 

+ +
 
+ +

[1] Desde o iOS 5.1, o Safari Mobile armazena os dados localStorage na pasta de cache, que está sujeita a limpeza ocasional a pedido do sistema operacional, normalmente se o espaço for curto.

+ +

Todos os navegadores têm diferentes níveis de capacidade para o localStorage e sessionStorage. Aqui está um resumo detalhado de todas as capacidades de armazenamento para vários navegadores.

+ +

Veja também

+ +

Using the Web Storage API

diff --git a/files/pt-br/web/api/storage/key/index.html b/files/pt-br/web/api/storage/key/index.html new file mode 100644 index 0000000000..9ed50459ad --- /dev/null +++ b/files/pt-br/web/api/storage/key/index.html @@ -0,0 +1,72 @@ +--- +title: Storage.key() +slug: Web/API/Storage/key +translation_of: Web/API/Storage/key +--- +
{{APIRef("Web Storage API")}}
+ +

O método key() da interface {{domxref("Storage")}}, quando passado um número n, retorna o nome da n-ésima chave no dado objeto Storage. A ordem das chaves é definida pelo user-agent, então não deve-se confiar nela.

+ +

Syntax

+ +
var aKeyName = storage.key(index);
+ +

Parâmetros

+ +
+
index
+
Um inteiro representando o número da chave que deseja obter. Esse é um índice que começa em zero.
+
+ +

Retorno

+ +

Uma {{domxref("DOMString")}} contendo o nome da chave. Se o index não existir, retornará null.

+ +

Exemplos

+ +

A função a seguir itera sobre as chaves do armazenamento local:

+ +
function forEachKey(callback) {
+  for (var i = 0; i < localStorage.length; i++) {
+    callback(localStorage.key(i));
+  }
+}
+ +

A função a seguir itera sobre as chaves do armazenamento local e obtém o valor de cada chave:

+ +
for(var i =0; i < localStorage.length; i++){
+  console.log(localStorage.getItem(localStorage.key(i)));
+}
+ +
+

Nota: Pra ver um exemplo real, consulte nossa Demonstração de armazenamento na Web.

+
+ +

Especificações

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

Compatibilidade com navegadores

+ + + +

{{Compat("api.Storage.key")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/storage/length/index.html b/files/pt-br/web/api/storage/length/index.html new file mode 100644 index 0000000000..fad990d9a8 --- /dev/null +++ b/files/pt-br/web/api/storage/length/index.html @@ -0,0 +1,130 @@ +--- +title: Storage.length +slug: Web/API/Storage/length +tags: + - API + - Armazenamento + - Armazenamento web + - Propriedade + - Referencia + - Somente Leitura + - Web Storage +translation_of: Web/API/Storage/length +--- +

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

+ +

A propriedade length, que é somente leitura, da interface {{domxref("Storage")}} retorna um inteiro que representa o número de itens armazenados no objeto Storage.

+ +

Sintaxe

+ +
var aLength = storage.length;
+ +

Retorno

+ +

Um inteiro

+ +

Exemplo

+ +

A função a seguir adiciona três itens ('bgcolor', 'font' e 'image') ao local storage do domínio atual, em seguida retorna o número de itens no storage:

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'yellow');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'cats.png');
+
+  localStorage.length; // should return 3
+}
+ +
+

Nota: Para um exemplo do mundo real, veja nosso Web Storage Demo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Storage', '#dom-storage-length', 'length')}}{{Spec2('Web Storage')}} 
+ +

Compatibilidade com browsers

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage4{{CompatVersionUnknown}}3.5810.504
sessionStorage5{{CompatUnknown}}2810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{CompatVersionUnknown}}{{ CompatUnknown }}811iOS 3.2
+
+ +

Cada browser tem uma capacidade variada para localStorage e sessionStorage. Aqui existe um tabela detalhada sobre a capacidade de armazenamento de cada browser.

+ +
+

Nota: desde o iOS 5.1, o Safari Mobile armazena os dados do localStorage no folder de cache, que está sujeito a uma limpeza ocasional baseada em regras do SO, tipicamente, quando o espaço está se esgotando.

+
+ +

Veja também

+ +

Usando a API Web Storage

diff --git a/files/pt-br/web/api/storage/removeitem/index.html b/files/pt-br/web/api/storage/removeitem/index.html new file mode 100644 index 0000000000..851f926173 --- /dev/null +++ b/files/pt-br/web/api/storage/removeitem/index.html @@ -0,0 +1,124 @@ +--- +title: Storage.removeItem() +slug: Web/API/Storage/removeItem +translation_of: Web/API/Storage/removeItem +--- +

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

+ +

O método removeItem() da interface {{domxref("Storage")}}, quando passado um nome de chave, irá remover essa chave do armazenamento.

+ +

Syntax

+ +
storage.removeItem(keyName);
+ +

Parâmetros

+ +
+
keyName
+
A {{domxref("DOMString")}} contendo o nome da chave que você deseja remover.
+
+ +

Retorno

+ +

Nenhum valor de retorno.

+ +

Exemplo

+ +

A função a seguir cria três itens de dados no armazenamento local, em seguida, remove o item "image".

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+
+  localStorage.removeItem('image');
+}
+ +
+

Nota: Para ver o uso em um exemplo prático veja nosso Web Storage Demo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('Web Storage', '#dom-storage-removeitem', 'removeItem()')}}{{Spec2('Web Storage')}} 
+ +

Compatibilidade

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ 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.

+ +
+

Note: 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.

+
+ +

Veja também

+ +

Usando a API Web Storage

diff --git a/files/pt-br/web/api/storage/setitem/index.html b/files/pt-br/web/api/storage/setitem/index.html new file mode 100644 index 0000000000..90a964fbc8 --- /dev/null +++ b/files/pt-br/web/api/storage/setitem/index.html @@ -0,0 +1,131 @@ +--- +title: Storage.setItem() +slug: Web/API/Storage/setItem +tags: + - Referencia +translation_of: Web/API/Storage/setItem +--- +

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

+ +

O método setItem() da interface {{domxref("Storage")}}, quando passado 'chave' e 'valor', irá adicionar esta chave ao storage, ou atualizar o valor caso a chave já exista.

+ +

Syntax

+ +
storage.setItem(keyName, keyValue);
+ +

Parâmetros

+ +
+
keyName
+
Um {{domxref("DOMString")}} contendo o nome da chave que você deseja criar ou alterar.
+
keyValue
+
Um {{domxref("DOMString")}} contendo o valor da chave que você está criando ou atualizando.
+
+ +

Retornos

+ +

Sem retorno.

+ +

Exceções

+ +

setItem() poderá lançar uma exceção caso o storage esteja cheio. Particularmente, no Safari Mobile (desde o iOS 5) sempre irá lançar quando o usuário entrar em modo privado (Safari define a quota para 0 bytes no modo privado ao contrário de outros navegadores que permitem o armazenamento em modo privado, usando recipientes de dados separados).
+ Assim os desenvolvedores devem certificar-se de sempre tratar as possíveis exceções do setItem().

+ +

Exemplo

+ +

A função abaixo irá criar três dados dentro do local storage.

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+}
+ +
+

Nota: Para ver ele sendo usado em um exemplo real, consulte nosso Web Storage Demo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Storage', '#dom-storage-setitem', 'setItem()')}}{{Spec2('Web Storage')}} 
+ + + +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

Todos os navegadores têm diferentes níveis de capacidade para tanto localStorage e sessionStorage. Aqui você encontra uma detalhada capacidade detalhada para vários browsers.

+ +
+

Nota: desde a versão iOS 5.1, Mobile Safari os dados na pasta 'cache' estão sujeito a limpezas ocasionais devido ao pouco espaço disponível.

+
+ +

Veja também

+ +

Usando a Web Storage API

diff --git a/files/pt-br/web/api/storagemanager/index.html b/files/pt-br/web/api/storagemanager/index.html new file mode 100644 index 0000000000..30be398f06 --- /dev/null +++ b/files/pt-br/web/api/storagemanager/index.html @@ -0,0 +1,53 @@ +--- +title: StorageManager +slug: Web/API/StorageManager +tags: + - API + - Interface + - Persistence + - Quotas + - Reference + - Secure context + - Storage + - Storage API + - StorageManager + - Usage +translation_of: Web/API/StorageManager +--- +

{{securecontext_header}}{{SeeCompatTable}}{{APIRef("Storage")}}

+ +

StorageManager é uma inteface da Storage API que fornece uma interface para controlar as permissões de gravações e estima o espaço disponível. Você pode obter a referência desta interface usando {{domxref("navigator.storage")}} ou {{domxref("WorkerNavigator.storage")}}.

+ +

Métodos

+ +
+
{{domxref("StorageManager.estimate()")}} {{securecontext_inline}}
+
Retorna um objeto {{domxref("StorageEstimate")}} contendo números de uso e cota para sua origem.
+
{{domxref("StorageManager.persist()")}} {{securecontext_inline}}
+
Retorna uma {{jsxref('Promise')}} que resolve como true se o agente de usuário for capaz de gravar o armazenamento do seu site.
+
{{domxref("StorageManager.persisted()")}} {{securecontext_inline}}
+
Retorna uma {{jsxref('Promise')}} que resolve como true se alguma gravação já foi concedida para o armazenamento do seu site.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Storage','#storagemanager','StorageManger')}}{{Spec2('Storage')}}Definição inicial.
+ +

Compatibilidade entre navegadores

+ + + +

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

diff --git a/files/pt-br/web/api/streams_api/concepts/index.html b/files/pt-br/web/api/streams_api/concepts/index.html new file mode 100644 index 0000000000..575d59cf67 --- /dev/null +++ b/files/pt-br/web/api/streams_api/concepts/index.html @@ -0,0 +1,121 @@ +--- +title: Conceitos da API Stream +slug: Web/API/Streams_API/Concepts +tags: + - API + - Streams + - conceitos +translation_of: Web/API/Streams_API/Concepts +--- +
{{apiref("Streams")}}
+ +

Streams API adiciona conjunto muito útil de ferramentas à plataforma web, provendo objetos que permitem ao JavaScript acessar via programação dados de stream recebidos pela rede e processá-los conforme desejado pelo desenvolvedor. Alguns conceitos e terminologias associadas a streams podem ser novos pra você - este artigo explicará tudo o que você precisa saber.

+ +

Readable streams

+ +

Um readable stream pode ser representado em JavaScript por um objeto {{domxref("ReadableStream")}} que flui de uma underlying source - é um recurso em algum lugar na rede ou outro lugar no domínio do qual deseja obter dados..

+ +

Há dois tipos de fontes subjacentes:

+ + + +

O dado é lido sequencialmente em pequenos blocos de informação chamado chunks. Um chunk por ser um simples byte, ou, pode ser algo maior como um typed array de um certo tamanho.
+ Um simples stream pode conter chunks de diferentes tamanhos e tipos.
+

+ +

Os chunks alocados em um stream são ditos enqueued (enfileirados) — isto significa que eles estão aguardando em uma fila prontos para serem lidos. Uma internal queue rastreia os chunks que ainda não foram lidos (veja filas internas e estratégias de enfileiramento na sessão abaixo).

+ +

Os chunks dentro de um stream são lidos por um reader — este processa o dado de um chunk por vez, permitindo fazer qualquer tipo de operação que desejar .O reader com mais outro código de processamento junto é chamado consumer.

+ +

Há também uma construção que você usará chamada controller — cada reader tem um controller associado que lhe permite controlar o stream (por exemplo, cancelá-lo se desejar).

+ +

Apenas um reader pode ler um stream por vez; quando um reader é criado e inicia a leitura de um stream (um active reader), dizemos que ele está atrelado a ele. Se você deseja outro reader para iniciar a leitura de seu stream, você precisa tipicamente cancelar o primeiro reader antes de fazer qualquer coisa (embora você possa usar um stream tee, veja Teeing na sessão abaixo)

+ +

Observe que há dois tipos diferentes de readable streams. Assim como um readable stream convencional há um tipo chamado byte stream - este é uma versão extendida de um stream convencional para leitura de underlying byte sources (de outra forma conhecido como BYOB, ou "bring your own buffer"). Estes permitem que streams sejam lidos diretamente em um buffer fornecido pelo desenvolvedor, minimizando a cópia necessária. Tal underlying stream (e por extensão, reader e controller) seu código dependerá em primeiro lugar de como o stream foi criado (veja o {{domxref("ReadableStream.ReadableStream()")}} construtor de página).

+ +
+

Importante: Bytes streams não estão implementados ainda em algum lugar, e foram levantadas questões sobre se os detalhes de especificação estão em condições para serem implementados. Isto pode mudar com o tempo.

+
+ +

Você pode fazer uso dos stream readers já implementados via mecanismos como {{domxref("Response.body")}} como uma requisição, ou com seus próprios streams usando o {{domxref("ReadableStream.ReadableStream()")}} como construtor.

+ +

Teeing

+ +

Embora um único reader possa ler um stream por vez, é possível dividir um stream em duas cópias idênticas, que podem então serem lidas por dois readers distintos. Isto é chamado teeing. 

+ +

Em JavaScript, isto pode ser alcançado pelo método {{domxref("ReadableStream.tee()")}} — ele retorna um array contendo duas cópias idêniticas o readable stream original, o qual pode então ser lido independentemente por dois readers separados.

+ +

Você deve fazê-lo por exemplo em um ServiceWorker se deseja pegar a resposta de um servidor e disponibilizar via stream no navegador, mas, também disponibilizá-lo via cache do ServiceWorker. Uma vez que o corpo da resposta não pode ser consumido mais que uma vez, e um stream não pode ser lido por mais de um reader por vez, você precisaria de duas cópias para fazer isto.

+ +

+ +

Writable streams

+ +

Um writable stream é o destino o qual você pode escrever dados, representado em JavaScript pelo objeto {{domxref("WritableStream")}}. Ele serve como uma camada de abstração sobre um underlying sink — um I/O de baixo-nivel que sincroniza quais dados brutos são escritos.

+ +

O dado é escrito para o stream via um writer, um chunk por vez. Um chunk pode ter uma infinidade de formas, assim como os chunk em um reader. Você pode usar qualquer código que desejar para produzir chunks prontos para escrever, mais o código associado ao producer.

+ +

Quando um writer é criado e inicia a escrita para um stream (um active writer), dizemos estar locked (atrelado) a este. Apenas um writer opde escrever em um writable stream por vez. Se deseja outro writer iniciar a escrita em seu stream, você deve tipicamente abortá-lo antes de anexar outro write à ele.

+ +

Uma internal queue mantém os chunks que foram escritos por um stream mas não foram ainda processados por underlying sink.

+ +

Há uma construção que você usará chamada controller — cada writer tem um controller associado que permite a você controlar o stream (por exemplo, abortá-lo se desejado).

+ +

+ +

Você pode fazer uso de writable streams usando o construtor 

+ +

You can make use of writable streams using the {{domxref("WritableStream.WritableStream()")}}. Estes atualmente possuem uma disponibilidade limitada nos navegadores.

+ +

Pipe chains

+ +

A API de Streams torna possível encadear streams (ou pelo menos irá fazer quando os navegadores implementarem a funcionalidade relevante para tal) usando uma estrutura chamada pipe chain. Há dois métodos disponíveis na especificação para facilitá-lo:

+ + + +

Para iniciar um pipe chain é chamado o original source, e no final é chamado ultimate sink.

+ +

+ +
+

Nota: Esta funcionalidade não está totalmente pensada ainda, embora disponível em muitos navegadores. Até certo ponto espero que a especificação dos writers pode contribuir para algo como uma clase TransformStream para criar facilmente transform stream.

+
+ +

Backpressure

+ +

Um importante conceito sobre streams é backpressure — é um processo pelo qual um stream simples ou uma pipe chain ajusta a velocidade de leitura/escrita. Quando um stream mais tarde na conrrente continua ocupado e não está ainda pronto para aceitar mais chunks, ele envia um sinal de volta através da corrente informar mais tarde o transform stream (ou a fonte original) para diminuir a velocidade de entrega conforme apropriado tal que você não precise terminar com um gargalo em algum lugar.

+ +

Para usar backpressure em um ReadableStream, podemos perguntar ao controller pelo tamanho do chunk desejado pelo consumer consultando o atributo {{domxref("ReadableStreamDefaultController.desiredSize")}} no controller. Se estiver muito baixo, nosso ReadableStream pode informar sua underlying source de dados e o backpressure junto a cadeira de stream.

+ +

Se mais tarde o consumer novamente deseja receber dados, podemos usar o método pull no stream para informar nossa underlying source para alimentar nosso stream com dados.

+ +

Internal queues and queuing strategies

+ +

Como mencionado antes, os chunks de um stream que não foram ainda processados e finalizados são mantidos por uma internal queue (fila interna).

+ + + +

Filas internas trabalham com uma queuing strategy, o qual dita informar a backpressure baseado na internal queue state.

+ +

Em geral, a estratégia compara o tamanho dos chunks na fila com o valor chamado no high water mark, o qual é o total do maior valor de chunk que a fila pode gerenciar de modo realista.

+ +

O cálculo realizado é

+ +
high water mark - total size of chunks in queue = desired size
+ +

O desired size é o tamanho de chunks que um stream ainda pode aceitar para manter o fluxo do stream menor que o high water mark. Após o cálculo ser efetuado, a geração de chunks terá sua velocidade reduzida ou aumentada conforme apropriado para manter o fluxo do stream o mais rápido possível enquanto mantém o tamanho desejado acima de zero. Se o valor cair para zero (ou menor no caso de writable streams), significa que os chunks estão sendo gerados mais rápido que o stream pode lidar, o qual resulta em problemas.

+ +
+

Nota: O que ocorre no caso em que valor desejado for zero ou negativo não foi definido na especificação até o momento. Paciência é uma virtude. 

+
+ +

Como um exemplo, vamos pegar um chunk de tamanho 1, e uma high water mark de 3. Isto significa que até 3 chunks podem ser enfileirados antes que a high water mark seja alcançada e o  backpressure aplicado.

diff --git a/files/pt-br/web/api/streams_api/index.html b/files/pt-br/web/api/streams_api/index.html new file mode 100644 index 0000000000..c382b3e7f8 --- /dev/null +++ b/files/pt-br/web/api/streams_api/index.html @@ -0,0 +1,157 @@ +--- +title: Streams API +slug: Web/API/Streams_API +tags: + - API + - Experimental + - Landing + - NeedsTranslation + - Reference + - Streams + - TopicStub +translation_of: Web/API/Streams_API +--- +
{{SeeCompatTable}}{{APIRef("Streams")}}
+ +
A API Streams permite que o JavaScript acesse programaticamente fluxos de dados recebidos pela rede e os processe conforme desejado pelo desenvolvedor.
+ +

+ +

Conceitos e Uso

+ + + +

O streaming envolve a divisão de um recurso que você deseja receber pela rede em pequenos blocos e, em seguida, processa esses blocos aos poucos. Isso é algo que os navegadores fazem de qualquer maneira ao receber recursos para serem exibidos em páginas da web — o buffer de vídeos e mais está gradualmente disponível para reprodução, e às vezes você verá imagens sendo exibidas gradualmente conforme mais é carregado.

+ +

Mas isto nunca esteve disponível para JavaScript antes. Anteriormente, se quiséssemos processar um recurso de algum tipo (seja ele um vídeo, ou um arquivo de texto, etc.), Teríamos que baixar o arquivo inteiro, espera até que seja desserializado em um formato adequado, então processa todo o lote após ser totalmente recebido.

+ +

Com o Streams disponível para JavaScript, tudo isso muda - agora você pode começar a processar dados brutos com JavaScript bit a bit assim que estiverem disponíveis no lado do cliente, sem a necessidade de gerar um buffer, string ou blob.

+ +

+ + + +

Também há mais vantagens - você pode detectar quando os fluxos começam ou terminam, encadeia os fluxos juntos, trata os erros e cancela os fluxos quando necessário e reage à velocidade em que o fluxo está sendo lido.

+ +

O uso básico de Streams gira em torno de tornar as respostas disponíveis como streams. Por exemplo, a resposta {{domxref("Body")}} retornada com sucesso de uma fetch request pode ser exposta como um {{domxref("ReadableStream")}}, e você pode lê-lo usando um leitor criado com {{domxref("ReadableStream.getReader()")}}, cancela-lo com {{domxref("ReadableStream.cancel()")}}, etc.

+ + + +

Usos mais complicados envolvem a criação de seu próprio fluxo usando o contrutor {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}}, por exemplo para processar dados dentro de um service worker.

+ +

Você também pode gravar dados em streams usando {{domxref("WritableStream")}}.

+ +
+

Note: Você pode encontrar muito mais detalhes sobre a teoria e prática de streams em nossos artigos — Streams API concepts, Using readable streams, e Using writable streams.

+
+ +

Stream interfaces

+ +

Readable streams

+ +
+
{{domxref("ReadableStream")}}
+
Represents a readable stream of data. It can be used to handle response streams of the Fetch API, or developer-defined streams (e.g. a custom {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} constructor).
+
{{domxref("ReadableStreamDefaultReader")}}
+
Represents a default reader that can be used to read stream data supplied from a network (e.g. a fetch request).
+
{{domxref("ReadableStreamDefaultController")}}
+
Represents a controller allowing control of a {{domxref("ReadableStream")}}'s state and internal queue. Default controllers are for streams that are not byte streams.
+
+ +

Writable streams

+ +
+
{{domxref("WritableStream")}}
+
Provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.
+
{{domxref("WritableStreamDefaultWriter")}}
+
Represents a default writable stream writer that can be used to write chunks of data to a writable stream.
+
{{domxref("WritableStreamDefaultController")}}
+
Represents a controller allowing control of a {{domxref("WritableStream")}}'s state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.
+
+ + + +
+
{{domxref("ByteLengthQueuingStrategy")}}
+
Provides a built-in byte length queuing strategy that can be used when constructing streams.
+
{{domxref("CountQueuingStrategy")}}
+
Provides a built-in chunk counting queuing strategy that can be used when constructing streams.
+
+ +

Extensions to other APIs

+ +
+
{{domxref("Request")}}
+
When a new Request object is constructed, you can pass it a {{domxref("ReadableStream")}} in the body property of its RequestInit dictionary.  This Request could then be passed to a {{domxref("WindowOrWorkerGlobalScope.fetch()")}} to commence fetching the stream.
+
{{domxref("Body")}}
+
The response {{domxref("Body")}} returned by a successful fetch request is exposed by default as a {{domxref("ReadableStream")}}, and can have a reader attached to it, etc.
+
+ + + +
+

Important: these are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented. This may change over time.

+
+ +
+
{{domxref("ReadableStreamBYOBReader")}}
+
Represents a BYOB ("bring your own buffer") reader that can be used to read stream data supplied by the developer (e.g. a custom {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} constructor).
+
{{domxref("ReadableByteStreamController")}}
+
Represents a controller allowing control of a {{domxref("ReadableStream")}}'s state and internal queue. Byte stream controllers are for byte streams.
+
{{domxref("ReadableStreamBYOBRequest")}}
+
Represents a pull into request in a {{domxref("ReadableByteStreamController")}}.
+
+ +

Examples

+ +

We have created a directory of examples to go along with the Streams API documentation — see mdn/dom-examples/streams. The examples are as follows:

+ + + +

Examples from other developers:

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Streams')}}{{Spec2('Streams')}}Initial definition.
+ +

Browser compatibility

+ + + +

WritableStream

+ +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/subtlecrypto/derivekey/index.html b/files/pt-br/web/api/subtlecrypto/derivekey/index.html new file mode 100644 index 0000000000..16f39fb7e1 --- /dev/null +++ b/files/pt-br/web/api/subtlecrypto/derivekey/index.html @@ -0,0 +1,270 @@ +--- +title: SubtleCrypto.deriveKey() +slug: Web/API/SubtleCrypto/deriveKey +tags: + - API + - Criptografía + - Crypto + - Referencia + - SubtleCrypto + - Web + - metodo +translation_of: Web/API/SubtleCrypto/deriveKey +--- +

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

+ +

O método SubtleCrypto.deriveKey() retorna como {{jsxref("Promise")}} de um recentemente gerado {{domxref("CryptoKey")}} derivada de uma master key e um algoritmo específico dados como parâmetro.

+ +

Sintaxe

+ +
var result = crypto.subtle.deriveKey(algorithm, masterKey, derivedKeyAlgorithm, extractable, keyUsages);
+
+ +

Parâmetros

+ + + +

Valor de retorno

+ + + +

Exceções

+ +

A promise é rejeitada quando uma das seguintes exceções é encontrada:

+ + + +

Exemplo

+ +

Aqui está um exemplo de como usar deriveKey() para criar uma Secure Remote Password (também nomeado de Proof of Secret) da password de um usuário.

+ +
// salt deve ser Uint8Array ou ArrayBuffer
+var saltBuffer = Unibabel.hexToBuffer('e85c53e7f119d41fd7895cdc9d7bb9dd');
+
+// não use métodos naïve para conversão de texto, senão caracteres
+// internacionais não terão a sequência correta de byte. Use o TextEncoder quando
+// possível ou então use polyfills relevantes
+var passphraseKey = Unibabel.utf8ToBuffer("I hëart årt and £$¢!");
+
+// Você deve primeiramente importar sua passphrase Uint8array em uma CryptoKey
+window.crypto.subtle.importKey(
+  'raw',
+  passphraseKey,
+  {name: 'PBKDF2'},
+  false,
+  ['deriveBits', 'deriveKey']
+).then(function(key) {
+
+  return window.crypto.subtle.deriveKey(
+    { "name": 'PBKDF2',
+      "salt": saltBuffer,
+      // não seja muito ambicioso, ou pelo menos tenha em mente
+      // que celulares com baixo poder de processamento vão acessar o seu app
+      "iterations": 100,
+      "hash": 'SHA-256'
+    },
+    key,
+
+    // Nota: para essa demo nós não vamos precisar de uma cipher suite,
+    // mas a API exige que a mesma seja especificada.
+
+    // Para AES o comprimento requerido é de 128 ou 256 bits (não bytes)
+    { "name": 'AES-CBC', "length": 256 },
+
+    // Independente da resposta a key é extraível (menos seguro) ou não extraível (mais seguro),
+    // quando falso, a key pode ser entregue apenas como um objeto crypto web, não inspecionado
+    true,
+
+    // esse objeto crypto web será permitido para apenas essas funções:
+    [ "encrypt", "decrypt" ]
+  )
+}).then(function (webKey) {
+
+  return crypto.subtle.exportKey("raw", webKey);
+
+}).then(function (buffer) {
+
+    var proofOfSecret = Unibabel.bufferToHex(buffer);
+    // esta proof-of-secret / password remota-segura
+    // pode agora ser enviada no lugar da password do usuário
+});
+ +

Nota: Por conta de não haver ferramentas nativas que convertam entre Uint8Array, Unicode, hex, e base64, você provavelmente vai querer utilizar algo como o Unibabel ou Buffer para converter entre eles.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-SubtleCrypto-method-deriveKey', 'SubtleCrypto.deriveKey()') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatSafari(11) }}
PBKDF2{{ CompatChrome(42) }}{{CompatUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatSafari(11) }}
HKDF-CTR{{ CompatChrome(42) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}
DH{{ CompatNo() }}{{CompatUnknown}}{{ CompatGeckoDesktop(35) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidEdgeChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}37{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
PBKDF2{{CompatVersionUnknown}}{{CompatUnknown}}42{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
HKDF-CTR{{CompatVersionUnknown}}{{CompatUnknown}}42{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
DH{{ CompatNo() }}{{CompatUnknown}}{{ CompatNo() }}{{ CompatGeckoMobile(35) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

+ +

"Master key" = "Chave mestre"

+ +

"Proof-of-secret" = "Prova de segredo ou Atestado de sigilo"

+ +

"Password" = "Palavra passe ou Senha"

diff --git a/files/pt-br/web/api/subtlecrypto/generatekey/index.html b/files/pt-br/web/api/subtlecrypto/generatekey/index.html new file mode 100644 index 0000000000..0b2c8a8bb0 --- /dev/null +++ b/files/pt-br/web/api/subtlecrypto/generatekey/index.html @@ -0,0 +1,197 @@ +--- +title: SubtleCrypto.generateKey() +slug: Web/API/SubtleCrypto/GenerateKey +tags: + - API + - Referencia + - SubtleCrypto + - Web Crypto API + - metodo +translation_of: Web/API/SubtleCrypto/generateKey +--- +

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

+ +

O método SubtleCrypto.generateKey() retorna como {{jsxref("Promise")}} de uma recentemente gerada {{domxref("CryptoKey")}}, para algoritmos simétricos, ou uma {{domxref("CryptoKeyPair")}}, contendo duas keys recentemente geradas, para algoritmos assimétricos, que combina com o algoritmo, o uso e a extractividade são dados como parâmetro.

+ +

Sintaxe

+ +
var result = crypto.subtle.generateKey(algo, extractable, keyUsages);
+
+ +

Parâmetros

+ + + +

Valor de retorno

+ + + +

Exceções

+ +

A {{jsxref("Promise")}} é rejeitada quando a seguinte exceção é encontrada:

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusCommentário
{{ SpecName('Web Crypto API', '#dfn-SubtleCrypto-method-generateKey', 'SubtleCrypto.generateKey()') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeEdgeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}13{{ CompatNo }}
ECDSA{{CompatVersionUnknown}}{{CompatUnknown}}{{ CompatGeckoDesktop(36) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }}
DH{{ CompatNo() }}{{CompatUnknown}}{{ CompatGeckoDesktop(35) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}37{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
ECDSA{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile(36) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
DH{{ CompatNo() }}{{CompatVersionUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile(35) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/subtlecrypto/importkey/index.html b/files/pt-br/web/api/subtlecrypto/importkey/index.html new file mode 100644 index 0000000000..15c4102162 --- /dev/null +++ b/files/pt-br/web/api/subtlecrypto/importkey/index.html @@ -0,0 +1,169 @@ +--- +title: SubtleCrypto.importKey() +slug: Web/API/SubtleCrypto/importKey +tags: + - API + - Criptografía + - Referencia + - SubtleCrypto + - Web Crypto API + - metodo +translation_of: Web/API/SubtleCrypto/importKey +--- +

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

+ +

O método SubtleCrypto.importKey() retorna como {{jsxref("Promise")}} de uma {{domxref("CryptoKey")}} de uma informção dada como parâmetro.

+ +

Sintaxe

+ +
var result = crypto.subtle.importKey(format, keyData, algo, extractable, usages);
+
+ +

Parâmetros

+ + + +

Valor de retorno

+ + + +

Exceções

+ +

A promise é rejeitada quando umas das seguintes exceções é encontrada:

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-SubtleCrypto-method-importKey', 'SubtleCrypto.importKey()') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
ECDH{{ CompatUnknown() }}{{CompatUnknown}}{{ CompatGeckoDesktop(41) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}37{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
ECDH{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatUnknown}}{{ CompatGeckoDesktop(41) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

+ +

 

diff --git a/files/pt-br/web/api/subtlecrypto/index.html b/files/pt-br/web/api/subtlecrypto/index.html new file mode 100644 index 0000000000..a949d1cfa5 --- /dev/null +++ b/files/pt-br/web/api/subtlecrypto/index.html @@ -0,0 +1,83 @@ +--- +title: SubtleCrypto +slug: Web/API/SubtleCrypto +tags: + - API + - Interface + - NeedsTranslation + - Referencia + - TopicStub + - Web Crypto API +translation_of: Web/API/SubtleCrypto +--- +

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

+ +

A interface SubtleCrypto representa um conjunto de criptografias primitivas. E está disponível via propriedades {{domxref("Crypto.subtle")}} disponíveis em uma janela de contexto (via {{domxref("Window.crypto")}}).

+ +
+

Por especificação: "Desenvolvedores fazendo uso da interface SubtleCrypto devem estar cientes das preocupações associadas com o design e a implementação de vários algoritmos providos. Os algoritmos brutos são providos em ordem para permitir aos desenvolvedores uma felixibilidade máxima na implementação de uma variedade de protocolos e aplicações, cada um deve representar a composição e os parâmetros de segurança em uma maneira única que necessita do uso de algoritmos brutos."

+
+ +

Propriedades

+ +

Esta interface não herda e nem implementa nenhuma propriedade.

+ +

Métodos

+ +

Esta interface não herda nenhum método

+ +
+
{{domxref("SubtleCrypto.encrypt()")}}
+
Retorna uma {{jsxref("Promise")}} da informação criptografada correspondente com o texto, algoritmo e chave key dados como parâmetros.
+
{{domxref("SubtleCrypto.decrypt()")}}
+
Retorna uma {{jsxref("Promise")}} da informação correspondente ao texto encriptografado, algoritmo e key dados como parâmetros.
+
{{domxref("SubtleCrypto.sign()")}}
+
Retorna uma {{jsxref("Promise")}} de uma assinatura correspondente ao texto, algoritmo e key dados como parâmetros.
+
{{domxref("SubtleCrypto.verify()")}}
+
Retorna uma {{jsxref("Promise")}} de um valor {{jsxref("Boolean")}} indicando se a assinatura dada como parâmetro combina com o texto, algoritmo e key também dados como parâmetros.
+
{{domxref("SubtleCrypto.digest()")}}
+
Retorna uma {{jsxref("Promise")}} de um resumo gerado a partir do algoritmo e texto dados como parâmetros.
+
{{domxref("SubtleCrypto.generateKey()")}}
+
Retorna uma {{jsxref("Promise")}} de uma recentemente gerada {{domxref("CryptoKey")}}, para algoritmos simétricos, ou uma {{domxref("CryptoKeyPair")}}, contendo duas novas keys simétricas, para algoritmos assimétricos, que combina com o algoritmo, os usos e a extrabilidade dados como parâmetros.
+
{{domxref("SubtleCrypto.deriveKey()")}}
+
Retorna uma {{jsxref("Promise")}} de uma recentemente gerada {{domxref("CryptoKey")}} derivada de uma master key e um algoritmo específico dados como parâmetros.
+
{{domxref("SubtleCrypto.deriveBits()")}}
+
Retorna uma {{jsxref("Promise")}} de um buffer recentemente gerado de bits pseudo-randômicos derivados de uma master key e um algoritmo específico dados como parâmetros.
+
{{domxref("SubtleCrypto.importKey()")}}
+
Retorna uma {{jsxref("Promise")}} de uma {{domxref("CryptoKey")}} correspondente ao formato, o algoritmo, a informação da key bruta, o uso e a extrabilidade dados como parâmetros.
+
{{domxref("SubtleCrypto.exportKey()")}}
+
Retorna uma {{jsxref("Promise")}} deu uma buffer contendo a key no formato requisitado.
+
{{domxref("SubtleCrypto.wrapKey()")}}
+
Retorna uma {{jsxref("Promise")}} de uma key envolvida simetricamente para uso (transferência, armazenamento) em ambientes não seguros. O buffer envolvido retornado será no formato dado nos parâmetros, e contém a key envolvida com a key envolvendo e o algoritmo dado.
+
{{domxref("SubtleCrypto.unwrapKey()")}}
+
Retorna uma {{jsxref("Promise")}} de uma {{domxref("CryptoKey")}} correspondente à key envolvida dada como parâmetro.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#subtlecrypto-interface', 'SubtleCrypto') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/svgaelement/index.html b/files/pt-br/web/api/svgaelement/index.html new file mode 100644 index 0000000000..687b067178 --- /dev/null +++ b/files/pt-br/web/api/svgaelement/index.html @@ -0,0 +1,74 @@ +--- +title: SVGAElement +slug: Web/API/SVGAElement +tags: + - Imagem vetorial + - Vetores +translation_of: Web/API/SVGAElement +--- +
{{APIRef("SVG")}}
+ +
SVGAElement interface fornece acesso as propriedades do elemento {{SVGElement("a")}}, bem como metodos para manipula-los.
+ +

Propriedades

+ +

Esta interface também herda propriedades de sua interface pai,{{domxref("SVGGraphicsElement")}}, e implementa propriedades de {{domxref("SVGURIReference")}} e de {{domxref("HTMLHyperlinkElementUtils")}}.

+ +
+
{{domxref("SVGAElement.target")}} {{readonlyInline}}
+
It corresponds to the {{SVGAttr("target")}} attribute of the given element.
+
+ +

Metodos

+ +

Esta interface não tem metodos próprios, porém herda metodos da interface {{domxref("SVGGraphicsElement")}}.

+ +

Exemplos

+ +

No exemplo abaixo, o {{SVGAttr("target")}} atributo do elemento {{SVGElement("a")}} recebe o valor _blank e quando o link for clicado, ele notifica se a condição é verdadeira ou falsa.

+ +
var linkRef = document.querySelector("a");
+linkRef.target = "_self";
+
+linkRef.onclick = function(){
+  if (linkRef.target === "_blank") {
+    console.log("BLANK!");
+    linkRef.target = "_self";
+  } else {
+    console.log("SORRY! not _blank");
+  }
+} 
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("SVG2", "linking.html#InterfaceSVGAElement")}}{{Spec2("SVG2")}}Replaced inheritance from {{domxref("SVGElement")}} by {{domxref("SVGGraphicsElement")}} and removed the interface implementations of {{domxref("SVGTests")}}, {{domxref("SVGLangSpace")}}, {{domxref("SVGExternalResourcesRequired")}}, {{domxref("SVGStylable")}}, and {{domxref("SVGTransformable")}} by {{domxref("HTMLHyperlinkElementUtils")}}
{{SpecName("SVG1.1", "linking.html#InterfaceSVGAElement")}}{{Spec2("SVG1.1")}}Definição inicial
+ +

Compatibilidade com o Navegador

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/svgaelement/svgalement.target/index.html b/files/pt-br/web/api/svgaelement/svgalement.target/index.html new file mode 100644 index 0000000000..ebd533b068 --- /dev/null +++ b/files/pt-br/web/api/svgaelement/svgalement.target/index.html @@ -0,0 +1,105 @@ +--- +title: SVGAElement.target +slug: Web/API/SVGAElement/SVGAlement.target +tags: + - Imagem vetorial + - Vetores +translation_of: Web/API/SVGAElement/target +--- +

{{APIRef("SVGAElement")}}

+ +

SVGAElement.target propriedade somente ler de {{domxref("SVGAElement")}} retorna um objeto {{domxref("SVGAnimatedString")}} que especifica a porção de um alvo sendo ele "window", "frame" ou "pane" no qual um documento será aberto quando o link for acionado.

+ +

Esta propriedade é usada quando existem dois ou mais possiveis alvos(destinos) para o documento, por exemplo, quando o documento pai é um arquivo .html ou .xhtml com varias telas (multi-frame).

+ +

Sintaxe

+ +
myLink.target = 'value';
+ +

Valor

+ +

Um {{domxref("SVGAnimatedString")}} indica o destino final do recurso que abre o documento assim que o link é acionado.

+ +

Valores para {{domxref("target")}} você pode ver aqui.

+ +

Exemplo

+ +

O código é foi retirado de "SVGAElement example code"

+ +
...
+var linkRef = document.querySelector('a');
+linkRef.target ='_blank';
+...
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('SVG1.1', 'text.html#InterfaceSVGAElement', 'target')}}{{Spec2('SVG1.1')}} 
+ +

Compatibilidade com o navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}9.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/svganimatetransformelement/index.html b/files/pt-br/web/api/svganimatetransformelement/index.html new file mode 100644 index 0000000000..2dddfa5f0b --- /dev/null +++ b/files/pt-br/web/api/svganimatetransformelement/index.html @@ -0,0 +1,48 @@ +--- +title: SVGAnimateTransformElement +slug: Web/API/SVGAnimateTransformElement +translation_of: Web/API/SVGAnimateTransformElement +--- +
{{APIRef("SVG")}}
+ +

A interface SVGAnimateTransformElement corresponde ao elemento {{SVGElement("animateTransform")}}.

+ +

{{InheritanceDiagram(600, 140)}}

+ +

Propriedades

+ +

Essa interface não possui propriedades próprias mas as herda do seu pai,       {{domxref("SVGAnimationElement")}}.

+ +

Métodos

+ +

Essa interface não possui métodos próprios mas os herda do seu pai, {{domxref("SVGAnimationElement")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("SVG Animations 2", "#InterfaceSVGAnimateTransformElement", "SVGAnimateTransformElement")}}{{Spec2("SVG Animations 2")}}No change
{{SpecName("SVG1.1", "animate.html#InterfaceSVGAnimateTransformElement", "SVGAnimateTransformElement")}}{{Spec2("SVG1.1")}}Initial definition
+ +

Compatibilidade

+ + + + + +

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

diff --git a/files/pt-br/web/api/url/createobjecturl/index.html b/files/pt-br/web/api/url/createobjecturl/index.html new file mode 100644 index 0000000000..430b49c457 --- /dev/null +++ b/files/pt-br/web/api/url/createobjecturl/index.html @@ -0,0 +1,42 @@ +--- +title: URL.createObjectURL() +slug: Web/API/URL/createObjectURl +translation_of: Web/API/URL/createObjectURL +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}}

+ +

Resumo

+ +

Cria um novo objeto URL, cujo tempo de vida está ligado ao {{domxref("document")}} na janela na qual este objeto foi criado. O novo objeto URL representa o objeto {{domxref("File")}} ou o objeto {{domxref("Blob")}} passado como argumento.

+ +

Sintaxe

+ +
objetoURL = window.URL.createObjectURL(blob);
+
+ + + +

Exemplo

+ +

Veja Using object URLs to display images.

+ +

Notas

+ +

Cada vez que a função createObjectURL() é chamada, um novo objeto URL é criado, mesmo se você já tiver criado um objeto URL para esse mesmo arquivo. Cada objeto URL criado precisa ser liberado por meio de uma chamada a {{domxref("window.URL.revokeObjectURL()")}} quando este não for mais necessário. Os navegadores liberarão os objetos URL criados automaticamente quando o documento for descarregado; no entanto, para um desempenho e um gerenciamento de memória ótimos, se houver algum momento em que você puder liberar estes recursos explicitamente, você deveria fazê-lo.

+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.URL.createObjectURL")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/url/index.html b/files/pt-br/web/api/url/index.html new file mode 100644 index 0000000000..6e24c8efe7 --- /dev/null +++ b/files/pt-br/web/api/url/index.html @@ -0,0 +1,113 @@ +--- +title: URL +slug: Web/API/URL +translation_of: Web/API/URL +--- +
{{ApiRef("URL API")}} {{SeeCompatTable}}
+ +

The URL interface represent an object providing static methods used for creating object URLs.

+ +

When using a user agent where no constructor has been implemented yet, it is possible to access such an object using the non-standard {{domxref("Window.URL")}} properties (prefixed with Webkit- and Blink-based browser as Window.webkitURL).

+ +

Properties

+ +

Implements properties defined in {{domxref("URLUtils")}}.

+ +
+
{{domxref("URLUtils.href")}}
+
Is a {{domxref("DOMString")}} containing the whole URL.
+
{{domxref("URLUtils.protocol")}}
+
Is a {{domxref("DOMString")}} containing the protocol scheme of the URL, including the final ':'.
+
{{domxref("URLUtils.host")}}
+
Is a {{domxref("DOMString")}} containing the host, that is the hostname, a ':', and the port of the URL.
+
{{domxref("URLUtils.hostname")}}
+
Is a {{domxref("DOMString")}} containing the domain of the URL.
+
{{domxref("URLUtils.port")}}
+
Is a {{domxref("DOMString")}} containing the port number of the URL.
+
{{domxref("URLUtils.pathname")}}
+
Is a {{domxref("DOMString")}} containing an initial '/' followed by the path of the URL.
+
{{domxref("URLUtils.search")}}
+
Is a {{domxref("DOMString")}} containing a '?' followed by the parameters of the URL.
+
{{domxref("URLUtils.hash")}}
+
Is a {{domxref("DOMString")}} containing a '#' followed by the fragment identifier of the URL.
+
{{domxref("URLUtils.username")}}
+
Is a {{domxref("DOMString")}} containing the username specified before the domain name.
+
{{domxref("URLUtils.password")}}
+
Is a {{domxref("DOMString")}} containing the password specified before the domain name.
+
{{domxref("URLUtils.origin")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the origin of the URL, that is its scheme, its domain and its port.
+
+ +
+
{{domxref("URLUtils.searchParams")}}
+
Returns a {{domxref("URLSearchParams")}} object allowing to access the GET query arguments contained in the URL.
+
+ +

Constructor

+ +
+
{{domxref("URL.URL", "URL()")}}
+
Creates and return a URL object composed from the given parameters.
+
+ +

Methods

+ +

The URL interface implements methods defined in {{domxref("URLUtils")}}.

+ +
+
{{domxref("URLUtils.toString()")}}
+
Returns a {{domxref("DOMString")}} containing the whole URL. It is a synonym for {{domxref("URLUtils.href")}}, though it can't be used to modify the value.
+
+ +

Static methods

+ +
+
{{ domxref("URL.createObjectURL()") }}
+
Returns a {{domxref("DOMString")}} containing a unique blob URL, that is a URL with blob: as its scheme, followed by an opaque string uniquely identifying the object in the browser.
+
{{ domxref("URL.revokeObjectURL()") }}
+
Revokes an object URL previously created using {{ domxref("URL.createObjectURL()") }}.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API', '#creating-revoking', 'URL')}}{{Spec2('File API')}}Added the static methods URL.createObjectURL() and URL.revokeObjectURL().
{{SpecName('URL', '#api', 'Node')}}{{Spec2('URL')}}Initial definition (implements URLUtils).
+ +

Browser compatibility

+ +

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

+ +

[1] From Gecko 2 (Firefox 4) to Gecko 18 included, Gecko supported this interface with the non-standard nsIDOMMozURLProperty internal type. As the only to access such an object was through {{domxref("window.URL")}}, in practice, this didn't make any difference.

+ +

Chrome Code - Scope Availability

+ +

To use from chrome code, JSM and Bootstrap scope, you have to import it like this:

+ +
Cu.importGlobalProperties(['URL']);
+
+ +

URL is available in Worker scopes.

+ +

See also

+ + diff --git a/files/pt-br/web/api/url/revokeobjecturl/index.html b/files/pt-br/web/api/url/revokeobjecturl/index.html new file mode 100644 index 0000000000..1a6c34027d --- /dev/null +++ b/files/pt-br/web/api/url/revokeobjecturl/index.html @@ -0,0 +1,107 @@ +--- +title: URL.revokeObjectURL() +slug: Web/API/URL/revokeObjectURL +translation_of: Web/API/URL/revokeObjectURL +--- +

{{ApiRef("URL")}}{{SeeCompatTable}}

+ +

Resumo

+ +

O método estático URL.revokeObjectURL() libera um objeto URL que foi criado préviamente chamando {{domxref("URL.createObjectURL()") }}.  Utilize este método quando terminar de usar um objeto URL, para informar o navegador que não é mais necessário manter a referência para o arquivo.

+ +

{{AvailableInWorkers}}

+ +

Sintaxe

+ +
window.URL.revokeObjectURL(objectURL);
+
+ +
+
objectURL
+
é um {{domxref("DOMString")}} representando o objeto URL que foi criado chamando {{domxref("URL.createObjectURL()") }}.
+
+ + + +

Exemplo

+ +

Veja Using object URLs to display images.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('File API', '#dfn-revokeObjectURL', 'URL')}}{{Spec2('File API')}}Initial definition
+ +

Compatibilidade de Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support8.0[1]{{CompatGeckoDesktop(2.0)}}10.015.06.0[1]
+ 7.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}[1]{{CompatGeckoMobile(14.0)}}{{CompatVersionUnknown}}15.06.0[1]
+ 7.0
+
+ +

[1] Implementado com prefixo de URL como webkitURL.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/url/searchparams/index.html b/files/pt-br/web/api/url/searchparams/index.html new file mode 100644 index 0000000000..a711b85fa2 --- /dev/null +++ b/files/pt-br/web/api/url/searchparams/index.html @@ -0,0 +1,45 @@ +--- +title: URL.searchParams +slug: Web/API/URL/searchParams +translation_of: Web/API/URL/searchParams +--- +

{{APIRef("")}}

+ +

A propriedade searchParams da interface {{domxref("URL")}} retorna um objeto {{domxref("URLSearchParams")}} permitindo acesso aos parâmetros enviados via GET que uma URL possui.

+ +

Sintaxe

+ +
var urlSearchParams = URL.searchParams;
+ +

Valor

+ +

Um objeto {{domxref("URLSearchParams")}}.

+ +

Exemplo

+ +

Se a URL da sua página é https://example.com/?name=Jonathan&age=18 você pode parsear os parametros 'name' e 'age' usando:

+ +
let params = (new URL(document.location)).searchParams;
+let name = params.get("name"); // é a string "Jonathan"
+let age = parseInt(params.get("age")); // é o número 18
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-searchparams', 'searchParams')}}{{Spec2('URL')}}Definição inicial.
+ +

Browser compatibility

+ +

{{Compat("api.URL.searchParams")}}

diff --git a/files/pt-br/web/api/urlsearchparams/get/index.html b/files/pt-br/web/api/urlsearchparams/get/index.html new file mode 100644 index 0000000000..7a89676a9a --- /dev/null +++ b/files/pt-br/web/api/urlsearchparams/get/index.html @@ -0,0 +1,109 @@ +--- +title: URLSearchParams.get() +slug: Web/API/URLSearchParams/get +translation_of: Web/API/URLSearchParams/get +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}} 

+ +

O métod get()  da interface {{domxref("URLSearchParams")}},  retorna o primeiro valor associado ao parametro de busca fornecido.

+ +

Syntax

+ +
URLSearchParams.get(name)
+ +

Parâmetros

+ +
+
name
+
O nome do parâmetro à ser retornado.
+
+ +

Retorno

+ +

Um {{domxref("USVString")}} se o parâmetro de pesquisa for encontrado; Caso contrário, null.

+ +

Exemplo

+ +

Se a URL da sua página é https://example.com/?name=Jonathan&age=18 você pode obter o parâmetro 'name' e 'age'  usando:

+ +
let params = new URLSearchParams(document.location.search.substring(1));
+let name = params.get("name"); // retorna a string "Jonathan"
+let age = parseInt(params.get("age"), 10); // retorna o número 18
+
+ +

Buscar um  parâmetro que não esteja presente na string de pesquisa, retornará  null:

+ +
let address = params.get("address"); // null
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('URL', '#dom-urlsearchparams-get', "get()")}}{{Spec2('URL')}}Definição inicial.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
diff --git a/files/pt-br/web/api/urlsearchparams/index.html b/files/pt-br/web/api/urlsearchparams/index.html new file mode 100644 index 0000000000..00080b0ae5 --- /dev/null +++ b/files/pt-br/web/api/urlsearchparams/index.html @@ -0,0 +1,177 @@ +--- +title: URLSearchParams +slug: Web/API/URLSearchParams +tags: + - API + - API de URL + - Experimental + - Interface + - Referencia +translation_of: Web/API/URLSearchParams +--- +

{{ApiRef("URL API")}}

+ +

A interface URLSearchParams define métodos de utilização para trabalhar com query string de uma URL.

+ +

Uma implementação do objeto URLSearchParams pode diretamente ser usado em uma estrutura {{jsxref("Statements/for...of", "for...of")}}, em vez de {{domxref('URLSearchParams.entries()', 'entries()')}}: for (var p of mySearchParams) é equivalente de for (var p of mySearchParams.entries()).

+ +

Construtor

+ +
+
{{domxref("URLSearchParams.URLSearchParams", 'URLSearchParams()')}}
+
Construtor retorna um objeto URLSearchParams.
+
+ +

Propriedades

+ +

Esta interface não herda nenhuma propriedade.

+ +

Métodos

+ +

Esta interface não herda nenhum método.

+ +
+
{{domxref("URLSearchParams.append()")}}
+
Acrescenta um par de chave/valor específica com um novo parâmetro de busca.
+
{{domxref("URLSearchParams.delete()")}}
+
Exclui o parâmetro de busca informado, e seu valor associado, da lista de parâmetros de busca.
+
{{domxref("URLSearchParams.entries()")}}
+
Retorna um {{jsxref("Iteration_protocols","iterator")}} permitindo obter por todos os pares de chave/valor contidos neste objeto.
+
{{domxref("URLSearchParams.get()")}}
+
Retorna o primeiro valor associado ao parâmetro de busca informado.
+
{{domxref("URLSearchParams.getAll()")}}
+
Retorna todos os valores associados com o parâmetro de busca encontrado.
+
{{domxref("URLSearchParams.has()")}}
+
Retorna um {{jsxref("Boolean")}} indicando se cada um dos parâmetros de busca existe.
+
{{domxref("URLSearchParams.keys()")}}
+
Retorna um {{jsxref("Iteration_protocols", "iterator")}} permitindo obter todas as chaves dos pares de chave/valor contido neste objeto.
+
{{domxref("URLSearchParams.set()")}}
+
Define o valor associado ao parâmetro de busca com o valor informado. Se tiver mutios valores, exclua os outros.
+
{{domxref("URLSearchParams.toString()")}}
+
Retorna uma string contendo uma query string adequada pra usar numa URL.
+
{{domxref("URLSearchParams.values()")}}
+
Retorna um {{jsxref("Iteration_protocols", "iterator")}} permitindo obter todos os valores dos pares de chave/valor contido neste objeto.
+
+ +

Exemplo

+ +
var stringParams = "q=URLUtils.searchParams&topic=api"
+var paramsBusca = new URLSearchParams(stringParams);
+
+//Iterar os parâmetros de busca.
+for (let p of paramsBusca) {
+  console.log(p);
+}
+
+paramsBusca.has("topic") === true; // true
+paramsBusca.get("topic") === "api"; // true
+paramsBusca.getAll("topic"); // ["api"]
+paramsBusca.get("foo") === null; // true
+paramsBusca.append("topic", "webdev");
+paramsBusca.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
+paramsBusca.set("topic", "More webdev");
+paramsBusca.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
+paramsBusca.delete("topic");
+paramsBusca.toString(); // "q=URLUtils.searchParams"
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName('URL', '#urlsearchparams', "URLSearchParams")}}{{Spec2('URL')}}Initial definition.
+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatChrome(49)}}{{CompatGeckoDesktop("29.0")}}{{CompatNo}}36{{CompatNo}}
entries(), keys(), values(), e suporte de for...of{{CompatChrome(49)}}{{CompatGeckoDesktop("44.0")}}{{CompatNo}}36{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Suporte básico{{CompatNo}}{{CompatChrome(49)}}{{CompatGeckoMobile("29.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(49)}}
entries(), keys(), values(), e suporte de for...of{{CompatNo}}{{CompatChrome(49)}}{{CompatGeckoMobile("44.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(49)}}
+
+ +

Veja também

+ + + +
+
diff --git a/files/pt-br/web/api/urlsearchparams/values/index.html b/files/pt-br/web/api/urlsearchparams/values/index.html new file mode 100644 index 0000000000..0bb1b06ff3 --- /dev/null +++ b/files/pt-br/web/api/urlsearchparams/values/index.html @@ -0,0 +1,112 @@ +--- +title: URLSearchParams.values() +slug: Web/API/URLSearchParams/values +translation_of: Web/API/URLSearchParams/values +--- +

{{APIRef("URL API")}}

+ +

O método URLSearchParams.values()retorna um {{jsxref("Iteration_protocols",'iterator')}} que permite passar por todos os valores do objeto. Os valores são objetos {{domxref("USVString")}}.

+ +
+

Nota: Esse método está disponível no Web Workers.

+
+ +

Sintaxe

+ +
searchParams.values();
+ +

Valor de retorno

+ +

Retorna um  {{jsxref("Iteration_protocols","iterator")}}.

+ +

Exemplo

+ +
// Cria um objeto URLSearchParams
+var searchParams = new URLSearchParams("key1=value1&key2=value2");
+
+// Mostra os pares de chave/valor
+for(var value of searchParams.values()) {
+  console.log(value);
+}
+ +

O resultado é:

+ +
value1
+value2
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#urlsearchparams','values() (as iterator<>)')}}{{Spec2('URL')}}Definição inicial.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop(44)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(44)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/validitystate/index.html b/files/pt-br/web/api/validitystate/index.html new file mode 100644 index 0000000000..e5bba7b7fb --- /dev/null +++ b/files/pt-br/web/api/validitystate/index.html @@ -0,0 +1,85 @@ +--- +title: ValidityState +slug: Web/API/ValidityState +tags: + - API + - Forms + - HTML DOM + - HTML5 + - Interface + - Validation +translation_of: Web/API/ValidityState +--- +
{{APIRef("HTML DOM")}} {{gecko_minversion_header("2.0")}}
+ +

A interface ValidityState representa os estados de validação que um elemento 
+ pode conter de acordo com as propriedades de validação abaixo. Juntas, elas podem explicar porque um elemento é inválido (caso seja) ao ser validado.

+ +

Propriedades

+ +

Para cada uma das propriedades Booleanas abaixo, caso retorne true, isso indica a razão específica porque a validação falhou, exceto no caso da propriedade valid, que retorna true no caso do elemento ser completamente válido e false caso contrário.

+ +
+
{{domxref("ValidityState.badInput")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o usuário inseriu um valor que o navegador é incapaz de converter.
+
{{domxref("ValidityState.customError")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o elemento possui uma mensagem de validação definida por setCustomValidity() para um valor não vázio.
+
{{domxref("ValidityState.patternMismatch")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor não combina com o padrão ({{htmlattrxref("pattern", "input")}}) especificado.
+
{{domxref("ValidityState.rangeOverflow")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor é maior do que o máximo especificado pelo atributo {{htmlattrxref("max", "input")}}.
+
{{domxref("ValidityState.rangeUnderflow")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor é menor do que o mínimo especificado pelo atributo {{htmlattrxref("min", "input")}}.
+
{{domxref("ValidityState.stepMismatch")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor não segue a regra definida pelo atributo {{htmlattrxref("step", "input")}}.
+
{{domxref("ValidityState.tooLong")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor ultrapassa o especificado pelo atributo maxlength para {{domxref("HTMLInputElement")}} ou {{domxref("HTMLTextAreaElement")}}. OBS: Isso nunca será true em navegadores como o Firefox, pois a inserção de valores não é permitida ao alcançar o valor definido em maxlength.
+
{{domxref("ValidityState.tooShort")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor não corresponde ao especificado no atributo minlength para {{domxref("HTMLInputElement")}} ou {{domxref("HTMLTextAreaElement")}}.
+
{{domxref("ValidityState.typeMismatch")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor não corresponde ao tipo de entrada definida. (Um exemplo é quando {{htmlattrxref("type", "input")}} é email ou url).
+
{{domxref("ValidityState.valid")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o elemento é completamente válido.
+
{{domxref("ValidityState.valueMissing")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando que o elemento tem o atributo {{htmlattrxref("required", "input")}}, mas não tem {{htmlattrxref("value", "input")}}.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('HTML WHATWG', 'forms.html#the-constraint-validation-api', 'ValidityState') }}{{Spec2('HTML WHATWG')}}Live Standard
{{ SpecName('HTML5.1', '#the-constraint-validation-api', 'ValidityState') }}{{Spec2('HTML5.1')}}No change from the previous snapshot {{SpecName('HTML5 W3C')}}.
{{ SpecName('HTML5 W3C', 'forms.html#the-constraint-validation-api', 'ValidityState') }}{{Spec2('HTML5 W3C')}}First snapshot of  {{SpecName('HTML WHATWG')}} containing this interface.
+ +

Compatibilidade com navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/web_animations_api/index.html b/files/pt-br/web/api/web_animations_api/index.html new file mode 100644 index 0000000000..c18d6fec70 --- /dev/null +++ b/files/pt-br/web/api/web_animations_api/index.html @@ -0,0 +1,86 @@ +--- +title: Web Animations API +slug: Web/API/Web_Animations_API +tags: + - API + - Animation + - Landing + - NeedsTranslation + - Reference + - TopicStub + - Web Animations +translation_of: Web/API/Web_Animations_API +--- +

{{DefaultAPISidebar("Web Animations")}}

+ +

The Web Animations API allows for synchronizing and timing changes to the presentation of a Web page, i.e. animation of DOM elements. It does so by combining two models: the Timing Model and the Animation Model.

+ +

Concepts and usage

+ +

The Web Animations API provides a common language for browsers and developers to describe animations on DOM elements. To get more information on the concepts behind the API and how to use it, read Using the Web Animations API.

+ +

Web Animations interfaces

+ +
+
{{domxref("Animation")}}
+
Provides playback controls and a timeline for an animation node or source. Can take an object created with the {{domxref("KeyframeEffect.KeyframeEffect", "KeyframeEffect()")}} constructor.
+
{{domxref("KeyframeEffect")}}
+
Describes sets of animatable properties and values, called keyframes and their timing options. These can then be played using the {{domxref("Animation.Animation", "Animation()")}} constructor.
+
{{domxref("AnimationTimeline")}}
+
Represents the timeline of animation. This interface exists to define timeline features (inherited by {{domxref("DocumentTimeline")}} and future timeline objects) and is not itself accessed by developers.
+
{{domxref("AnimationEvent")}}
+
Actually part of CSS Animations.
+
{{domxref("DocumentTimeline")}}
+
Represents animation timelines, including the default document timeline (accessed using the {{domxref("Document.timeline")}} property).
+
{{domxref("EffectTiming")}}
+
{{domxref("Element.animate()")}}, {{domxref("KeyframeEffectReadOnly.KeyframeEffectReadOnly()")}}, and {{domxref("KeyframeEffect.KeyframeEffect()")}} all accept an optional dictionary object of timing properties.
+
+ +

Extensions to other interfaces

+ +

The Web Animations API adds some new features to {{domxref("document")}} and {{domxref("element")}}.

+ +

Extensions to the Document interface

+ +
+
{{domxref("document.timeline")}}
+
The DocumentTimeline object representing the default document timeline.
+
{{domxref("document.getAnimations()")}}
+
Returns an Array of {{domxref("Animation")}} objects currently in effect on elements in the document.
+
+

Extensions to the Element interface

+
+
{{domxref("Element.animate()")}}
+
A shortcut method for creating and playing an animation on an element. It returns the created {{domxref("Animation")}} object instance.
+
{{domxref("Element.getAnimations()")}}
+
Returns an Array of {{domxref("Animation")}} objects currently affecting an element or which are scheduled to do so in future.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations')}}{{Spec2('Web Animations')}}Initial definition
+ +

See also

+ + diff --git a/files/pt-br/web/api/web_animations_api/usando_a_web_animations_api/index.html b/files/pt-br/web/api/web_animations_api/usando_a_web_animations_api/index.html new file mode 100644 index 0000000000..2743f68d65 --- /dev/null +++ b/files/pt-br/web/api/web_animations_api/usando_a_web_animations_api/index.html @@ -0,0 +1,358 @@ +--- +title: Usando a Web Animations API +slug: Web/API/Web_Animations_API/Usando_a_Web_Animations_API +tags: + - Alice + - Animação + - CSS + - Guía + - Iniciante + - JavaScript + - Timing + - Tutorial + - animar + - duration + - keyframes + - pausar + - pause + - play + - quadro-chave + - reverse + - web animations api +translation_of: Web/API/Web_Animations_API/Using_the_Web_Animations_API +--- +

{{DefaultAPISidebar("Web Animations")}}

+ +

A Web Animations API nos possibilita criar animações e controlar sua reprodução pelo JavaScript. Esse artigo vai te demonstrar esses conceitos com demonstrações e tutoriais com o temática de Alice no País das Maravilhas.

+ +

Conhecendo a Web Animations API

+ +

A Web Animations API abre a engine de animação do browser para os desenvolvedores manipularem via JavaScript. Esta API foi construída para se basear nas implementações das Animações CSS e Transições CSS, e deixam a porta aberta para futuros efeitos de animação. É um dos métodos mais performáticos para se animar na Web, permitindo que o browser faça internamente suas próprias otimizações, sem precisar depender de hacks, coerções ou {{domxref("Window.requestAnimationFrame()")}}.

+ +

Com a Web Animations API, podemos transferir as animações interativas das folhas de estilo para o JavaScript, separando comportamento de apresentação. Não vamos precisar mais depender de técnicas muito dependentes do DOM como propriedades do CSS e escopo de classes para controlar a direção da reprodução. E diferente de CSS puro e declarativo, JavaScript também te possibilita definir dinâmicamente valores: de propriedades à duração. Para criar bibilotecas de animação à criar animações interativas, a Web Animations API pode ser a ferramenta perfeita para o trabalho. Vamos ver o que ela pode fazer!

+ +

Suporte de Navegadores

+ +

O suporte básico para as funcionalidades da Web Animations API discutidas neste artigo estão disponíveis no Firefox 48+, Chrome 36+ e Safari 13.1+. Também existe um polyfill prático que verifica o suporte e adiciona as funcionalidades onde for necessário.

+ +

Escrevendo Animações CSS com a Web Animations API

+ +

Uma das maneiras mais familiares de abordar a Web Animations API é começar com algo que boa parte dos desenvolvedores web já utilizaram antes: Animações CSS. Animações CSS tem uma sintaxe familiar que funciona bem para nossa demonstração.

+ +

A versão CSS

+ +

Aqui temos uma animação escrita com CSS mostrando Alice caindo no buraco de coelho que leva ao País das Maravilhas (veja o código completo no Codepen):

+ +

Alice Tumbling down the rabbit's hole.

+ +

Perceba que o fundo se mexe, a Alice gira e sua cor muda em sincronia com o giro. Nós vamos focar somente na Alice para este tutorial. Segue a versão simplificada do CSS que controla a animação da Alice:

+ +
#alice {
+  animation: aliceTumbling infinite 3s linear;
+}
+
+@keyframes aliceTumbling {
+  0% {
+    color: #000;
+    transform: rotate(0) translate3D(-50%, -50%, 0);
+  }
+  30% {
+    color: #431236;
+  }
+  100% {
+    color: #000;
+    transform: rotate(360deg) translate3D(-50%, -50%, 0);
+  }
+}
+ +

Isso muda a cor da Alice e a rotação do `transform` por 3 segundos em um ritmo constante (linear) e se repete infinitamente. No bloco do @keyframes podemos ver que em 30% de cada repetição (por volta dos 900ms), a cor da Alice muda de preto para um vinho, e volta para o preto no final do loop.

+ +

Mudando para o JavaScript

+ +

Agora vamos tentar criar a mesma animação usando a Web Animations API.

+ +

Representando keyframes

+ +

A primeira coisa que precisamos fazer é criar um Objeto Keyframe correspondente ao nosso bloco @keyframes do CSS:

+ +
var aliceTumbling = [
+  { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
+  { color: '#431236', offset: 0.3},
+  { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
+];
+ +

Aqui estávamos utilizando uma array contendo múltiplos objetos. Cada objeto representa uma chave do CSS original. Contudo, diferente do CSS, a Web Animations API não precisa informar explicitamente as porcentagens temporais para cada chave, o JS automaticamente divide a animação em partes iguais baseado no número de chaves que você forneceu. Isso significa que um objeto Keyframe com três chaves vai reproduzir a chave do meio em 50% do tempo de cada loop, exceto se for definido o contrário.

+ +

Quando queremos explicitamente definir um timing diferente para essas outras chaves, podemos especificar um offset diretamente no objeto, separado do resto da declaração por uma vírgula. No exemplo acima, para definir que a cor da Alice muda em 30% do tempo (e não 50%), nós definiremos como offset: 0.3.

+ +

Atualmente, devem ser definidos pelo menos dois keyframes (representando o início e fim de estado das sequências de animação). Se a sua lista de keyframes somente tem uma entrada, {{domxref("Element.animate()")}} pode disparar uma exceção NotSupportedErro em alguns browsers até eles serem atualizados.

+ +

Então recapitulando: as chaves são espaçadas igualmente por padrão, exceto se você definir um offset para uma chave. Útil, não?

+ +

Representando propriedades temporais

+ +

Nós precisamos criar também um objeto de propriedades temporais (um objeto {{domxref("AnimationEffectTimingProperties")}}) correspondente aos valores da animação da Alice:

+ +
var aliceTiming = {
+  duration: 3000,
+  iterations: Infinity
+}
+ +

Você pode notar algumas diferenças aqui comparando com os valores equivalentes representados no CSS:

+ + + +
+

Existem algumas pequenas diferenças de terminologia entre o CSS Animations e o Web Animations. Por exemplo, Web Animations não usa a string "infinite", e sim a keyword JavaScript Infinity. E no lugar de timing-function, usamos easing. Não estamos citando um valor de easing aqui pois, diferente das Animações CSS onde o valor padrão do animation-timing-function é ease, na Web Animations API o padrão é linear — o que nós já queremos para a animação da Alice.

+
+ +

Juntando as peças

+ +

Agora vamos juntar o que já fizemos com o método {{domxref("Element.animate()")}}:

+ +
document.getElementById("alice").animate(
+  aliceTumbling,
+  aliceTiming
+)
+ +

E pronto: a animação começa a tocar (veja a versão final no Codepen).

+ +

O método animate() pode ser chamado em qualquer elemento do DOM que pode ser animado com CSS. E pode ser escrito de algumas maneiras. Ao invés de criar objetos para os keyframes e propriedades temporais, podemos passar seus valores diretamentes, tipo:

+ +
document.getElementById("alice").animate(
+  [
+    { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
+    { color: '#431236', offset: 0.3},
+    { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
+  ], {
+    duration: 3000,
+    iterations: Infinity
+  }
+);
+ +

E se nós precisarmos somente especificar a duração da animação e não suas iterações (por padrão, a animação roda uma ), podemos passar só os milisegundos após o array:

+ +
document.getElementById("alice").animate(
+  [
+    { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
+    { color: '#431236', offset: 0.3},
+    { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
+  ], 3000);
+ +

Controlando a reprodução com play(), pause(), reverse() e updatePlaybackRate()

+ +

Por mais que possamos escrever Animações CSS utilizando a Web Animations API, a API realmente mostra seu potencial quando precisamos manipular a reprodução da animação. A Web Animations API fornece vários métodos úteis para controlar a reprodução. Vamos dar uma olhada em como pausar e tocar animações no jogo da Alice Crescendo/Encolhendo (confira o código completo no Codepen):

+ +

Playing the growing and shrinking game with Alice.

+ +

Nesse jogo, Alice tem uma animação que a encolhe ou aumenta seu tamanho, que controlamos por uma garrafa e um cupcake. Cada um tem sua própria animação.

+ +

Pausando e tocando animações

+ +

Vamos falar sobre a animação da Alice depois, mas por enquanto, vamos dissecar esta animação do cupcake.

+ +
var nommingCake = document.getElementById('eat-me_sprite').animate(
+[
+  { transform: 'translateY(0)' },
+  { transform: 'translateY(-80%)' }
+], {
+  fill: 'forwards',
+  easing: 'steps(4, end)',
+  duration: aliceChange.effect.timing.duration / 2
+});
+ +

O método {{domxref("Element.animate()")}} vai rodar imediatamente depois de ser chamado. Para evitar que o bolinho se coma sozinho antes da interação do usuário, chamamos o {{domxref("Animation.pause()")}} imediatamente depois de criar a animação:

+ +
nommingCake.pause();
+ +

Agora nós podemos usar o método {{domxref("Animation.play()")}} para rodar assim que for o momento:

+ +
nommingCake.play();
+ +

Especificamente, nós queremos linka-lo à animação da Alice, para ela crescer assim que o cupcake é mordido. Podemos fazer isso com a seguinte função:

+ +
var growAlice = function() {
+
+  // Play Alice's animation.
+  aliceChange.play();
+
+  // Play the cake's animation.
+  nommingCake.play();
+
+}
+ +

Quando o usuário clicar ou pressionar seu dedo no bolinho em uma tela de toque, podemos chamar a função growAlice para fazer todas as animações tocarem:

+ +
cake.addEventListener("mousedown", growAlice, false);
+cake.addEventListener("touchstart", growAlice, false);
+ +

Outros métodos úteis

+ + + +

Vamos dar uma olhada primeiro no método playbackRate — um valor negativo vai fazer a animação tocar ao contrário. Quando Alice bebe da garrafa, ela encolhe. Isso porque a garrafa muda o playbackRate da animação de 1 para -1:

+ +
var shrinkAlice = function() {
+  aliceChange.playbackRate = -1;
+  aliceChange.play();
+}
+
+bottle.addEventListener("mousedown", shrinkAlice, false);
+bottle.addEventListener("touchstart", shrinkAlice, false);
+ +

Em Alice Através do Espelho, Alice viaja para um mundo onde ela deve correr para se manter no lugar — e correr com o dobro de velocidade para avançar! No exemplo da Corrida da Rainha Vermelha, Alice e a Rainha Vermelha estão correndo para se manter no lugar (veja o código completo no Codepen):

+ +

Alice and the Red Queen race to get to the next square in this game.

+ +

Já que crianças pequenas se cansam facilmente, diferente de peças de xadrez autônomas, Alice está constantemente desacelerando. Nós podemos fazer isso definindo uma queda no playbackRate da animação dela. Usamos o updatePlaybackRate() no lugar de definir manualmente o playbackRate, já que isso produz uma atualização mais suave:

+ +
setInterval( function() {
+
+  // Make sure the playback rate never falls below .4
+  if (redQueen_alice.playbackRate > .4) {
+    redQueen_alice.updatePlaybackRate(redQueen_alice.playbackRate * .9);
+  }
+
+}, 3000);
+ +

Mas impulsioná-las clicando ou tocando na tela aumenta a velocidade delas por multiplicar o playbackRate:

+ +
var goFaster = function() {
+  redQueen_alice.updatePlaybackRate(redQueen_alice.playbackRate * 1.1);
+}
+
+document.addEventListener("click", goFaster);
+document.addEventListener("touchstart", goFaster);
+ +

Os elementos do fundo também tem playbackRates que também são afetados pelo clique ou toque na tela. O que acontece quando você faz Alice e a Rainha Vermelha correrem com o dobro da velocidade? O que acontece quando você as deixa desacelerar?

+ +

Extraindo informação das animações

+ +

Imagine outras maneiras de utilizar o playbackRate, como melhorar a acessibilidade para usuários com disfunções vestibulares permitindo que eles desacelerem as animações do site todo. Isso é impossível de fazer via CSS sem recalcular todas as regras, mas com a Web Animations API, podemos utilizar o método {{domxref("document.getAnimations()")}} para iterar todas animações de uma página e dividir pela metade seu playbackRate, como por exemplo:

+ +
document.getAnimations().forEach(
+  function (animation) {
+    animation.updatePlaybackRate(animation.playbackRate * .5);
+  }
+);
+ +

Com a Web Animations API, você só precisa mudar uma simples propriedade!

+ +

Outra coisa que é difícil de fazer somente com Animações CSS é criar dependências de valores fornecidos por outras animações. Por exemplo, no logo Aumentando e Encolhendo Alice, você pode ter notado algo estranho sobre a duração do bolinho:

+ +
duration: aliceChange.effect.getComputedTiming().duration / 2
+ +

Para entender o que está acontecendo, vamos dar uma olhada na animação da Alice:

+ +
var aliceChange = document.getElementById('alice').animate(
+  [
+    { transform: 'translate(-50%, -50%) scale(.5)' },
+    { transform: 'translate(-50%, -50%) scale(2)' }
+  ], {
+    duration: 8000,
+    easing: 'ease-in-out',
+    fill: 'both'
+  });
+ +

A animação da Alice a fazia ir de metade de seu tamanho para o dobro em 8 segundos. Então nós a pausamos:

+ +
aliceChange.pause();
+ +

Se pausassemos no início da animação, ela começaria com metade de seu tamanho original, como se já tivesse bebido a garrafa toda! Então nós precisamos definir o estado inicial da animação no meio. Podemos fazer isso definindo o {{domxref("Animation.currentTime")}} para 4 segundos, como no exemplo abaixo:

+ +
aliceChange.currentTime = 4000;
+ +

Mas enquanto trabalhamos nessa animação, vamos mudar bastante a duração da Alice. Não seria melhor definir essa currentTime dinamicamente? Assim não precisariamos fazer duas atualizações de uma vez só. Podemos fazer isso referenciando a propriedade {{domxref("Animation.effect")}}, que retorna um objeto que contém todos os detalhes sobre o(s) efeito(s) ativos na Alice:

+ +
aliceChange.currentTime = aliceChange.effect.getComputedTiming().duration / 2;
+ +

O effect nos permite acessar os keyframes e propriedades temporais da animação — aliceChange.effect.getComputedTiming() aponta para o objeto timing da Alice (cujo tipo é {{domxref("ComputedEffectTiming")}}) — que contem o {{domxref("ComputedEffectTiming.duration")}} dela. Podemos dividir sua duração pela metade para definir a metade da animação para a linha do tempo da animação da Alice, assim ela começaria com o tamanho normal. Então nós podemos reverter e tocar a animação dela em qualquer direção para encolher ou aumentar seu tamanho!

+ +

E nós podemos fazer a mesma coisa quando definimos as durações da garrafa e do bolinho:

+ +
var drinking = document.getElementById('liquid').animate(
+[
+  { height: '100%' },
+  { height: '0' }
+], {
+  fill: 'forwards',
+  duration: aliceChange.effect.getComputedTiming().duration / 2
+});
+drinking.pause();
+ +

Agora todas as três animações estão ligadas por apenas um duration, que pode ser modificado facilmente em um só lugar do código.

+ +

Nós também podemos utilizar a Web Animations API para descobrir o quanto da linha do tempo já foi percorrido. O jogo acaba quando o seu bolinho acaba ou você esvazia a garrafa. A vinheta que é apresentada aos jogadores depende do quão longe a Alice estava em sua animação, seja ficando grande demais pra caber na portinha ou pequena demais pra não conseguir mais alcançar a chave para abrir a porta. Podemos descobrir se ela está nesses extremos pegando o currentTime da sua animação e dividir pelo activeDuration:

+ +
var endGame = function() {
+
+  // get Alice's timeline's playhead location
+  var alicePlayhead = aliceChange.currentTime;
+  var aliceTimeline = aliceChange.effect.getComputedTiming().activeDuration;
+
+  // stops Alice's and other animations
+  stopPlayingAlice();
+
+  // depending on which third it falls into
+  var aliceHeight = alicePlayhead / aliceTimeline;
+
+  if (aliceHeight <= .333){
+    // Alice got smaller!
+    ...
+
+  } else if (aliceHeight >= .666) {
+    // Alice got bigger!
+    ...
+
+  } else {
+    // Alice didn't change significantly
+    ...
+
+  }
+}
+
+ +
+

Nota: getAnimations() e effect não estão disponíveis em todos os browsers no momento em que este artigo foi escrito, mas o polyfill possibilita utilizá-los agora.

+
+ +

Callbacks e promises

+ +

Animações e Transições CSS tem seus event listeners próprios, que também são possíveis com a Web Animations API:

+ + + +

Aqui nós definimos os callbacks para o bolinho, a garrafa e para Alice para disparar a função endGame:

+ +
// When the cake or bottle runs out...
+nommingCake.onfinish = endGame;
+drinking.onfinish = endGame;
+
+// ...or Alice reaches the end of her animation
+aliceChange.onfinish = endGame;
+
+
+ +

Ainda melhor, a Web Animations API também fornece uma promise finished que será resolvida quando a animação é completada, e rejeitada se for cancelada.

+ +

Conclusão

+ +

Essas são as funcionalidades básicas da Web Animations API, a maioria delas já estão sendo suportadas pelas últimas versões do Chrome, Firefox e Safari. Agora você está pronto pra "cair na toca do coelho" de animar utilizando o browser e pronto pra escrever e experimentar com sua própria animação! Se você está utilizando a API e deseja compartilha, tente usar a hashtag #WAAPI. Nós estaremos de olho e vamos escrever mais tutoriais para cobrir funcionalidades futuras assim que o suporte aumentar!

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/web_crypto_api/index.html b/files/pt-br/web/api/web_crypto_api/index.html new file mode 100644 index 0000000000..3058112978 --- /dev/null +++ b/files/pt-br/web/api/web_crypto_api/index.html @@ -0,0 +1,132 @@ +--- +title: Web Crypto API +slug: Web/API/Web_Crypto_API +tags: + - API + - API de criptografia Web + - Overview + - Referencia + - Visão Geral + - Web Crypto API +translation_of: Web/API/Web_Crypto_API +--- +

{{DefaultAPISidebar("Web Crypto API")}}{{SeeCompatTable}}{{draft}}

+ +

A Web Crypto API é uma interface que permite um script utilizar criptografias primitivas para criar sistemas usando criptografia.

+ +

Uma característica fundamental desta API é permitir a manipulação e o armazenamento de keys de criptografia privadas e secretas sem que o JavaScript tenha acesso aos bits internos das keys.

+ +

Essa interface permite que scripts acessem as seguintes primitivas:

+ + + +

A Web Crypto API não resolve todos os problemas de criptografia que um site Web ou aplicação pode encontrar:

+ + + +
+

Atenção!

+ + +
+ +

Interfaces

+ +

Alguns navegadores implementam uma interface chamada {{domxref("Crypto")}} sem que ela esteja bem definida ou seja substancialmente criptografado. Para evitar confusões, métodos e propriedades desta interface foram retiradas de navegadores que implementaram Web Crypto API, e todos os métodos Web Crypto API estão disponíveis em uma nova interface: {{domxref("SubtleCrypto")}}. A propriedade {{domxref("Crypto.subtle")}} dá acesso a um objeto que a implementa.

+ +

Casos de uso

+ +

A Web Crypto API pode ser utilizada:

+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Web Crypto API")}}{{Spec2("Web Crypto API")}}Definição inicial
+ +

 

+ +

 

+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(24)}}{{CompatUnknown}}
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Suporte básico{{CompatNo}}{{CompatChrome(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ +

 

diff --git a/files/pt-br/web/api/web_storage_api_pt_br/index.html b/files/pt-br/web/api/web_storage_api_pt_br/index.html new file mode 100644 index 0000000000..f4e16bd9e7 --- /dev/null +++ b/files/pt-br/web/api/web_storage_api_pt_br/index.html @@ -0,0 +1,139 @@ +--- +title: API de Armazenamento na Web +slug: Web/API/Web_Storage_API_pt_br +translation_of: Web/API/Web_Storage_API +--- +

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

+ +

A  API de armazenamento na web (Web Storage) fornece mecanismos para que os navegadores possam armazenar dados através de chave/valor de uma forma mais eficiente que os cookies.

+ +

Armazenamento na Web conceitos e formas de uso

+ +

A API de Web Storage fornece duas maneiras de armazenar dados:

+ + + +

Esses mecanismos estão disponíveis a partir das seguintes propriedades {{domxref("Window.sessionStorage")}} e {{domxref("Window.localStorage")}} (para um maior suporte, o objeto Window implementa os objetos  Window.LocalStorageWindow.SessionStorage) — ao invocar uma dessas propriedades, é criada uma instância do objeto {{domxref("Storage")}}, que fornece métodos para inserir, recuperar e remover os dados. Sempre será utilizado um objeto diferente para cada origem de sessionStorage e localStorage, dessa forma o controle de ambos é realizado de forma separada.

+ +
+

Nota: O acesso a API de Web storage a partir de IFrames de terceiros é negado se o usuário desabilitou cookies de terceiros (Firefox implementa esse comportamento a partir da versão 43 em diante).

+
+ +
+

Nota: Web Storage não é o mesmo que mozStorage (interface XPCOM da Mozilla para o SQLite) ou Session store API (uma forma de armazenamento XPCOM para uso de extensões).

+
+ +

Interfaces de Armazenamento na Web

+ +
+
{{domxref("Storage")}}
+
Permite que você insira, recupere e remova dados de um domínio no storage(session ou local).
+
{{domxref("Window")}}
+
A API de Web Storage estende o objeto {{domxref("Window")}} com duas novas propriedades — {{domxref("Window.sessionStorage")}} e {{domxref("Window.localStorage")}} —  fornecendo acesso à sessão do domínio atual e local para o objeto {{domxref("Storage")}} respectivamente.
+
{{domxref("StorageEvent")}}
+
+

Um evento de storage é chamado em um objeto window do documento quando ocorre uma mudança no storage.

+
+
+ +

Exemplos

+ +

Para desmonstrar o uso de web storage, nós criamos um exemplo simples, chamado Web Storage Demo. A página da demo landing page oferece funcionalidades que permitem alterar a cor, fonte e imagem que é exibida na página. Quando você escolhe uma opção diferente, a página será atualizada imediatamente. Além disso, sua escolha foi armazenada em localStorage,  para que quando você feche o navegador e abra novamente para acessar a página, suas escolhas sejam lembradas.

+ +

Nós também fornecemos um event output page —  para quando você abrir a página em outra aba,  as informações sejam atualizadas através da chamada de um {{event("StorageEvent")}}.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Storage')}}{{Spec2('Web Storage')}}
+ +

Compatibilidade com os Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

Todos os navegadores têm espaços de armazenamento diferentes tanto para localStorage quanto para sessionStorage. Veja um resumo detalhado da capacidade de armazenamento de vários navegadores.

+ +
+

Nota: Desde iOS 5.1, o Safari armazena dados móveis de LocalStorage na pasta cache, que está sujeito a limpeza pelo OS, além disso o espaço de armazenamento é curto.

+
+ + + +

Boa parte dos navegadores atuais suportam a opção de privacidade chamada modo de "Navegação privada ou anônima", que basicamente torna a sessão de navegação privada e não deixa rastros depois que o navegador é fechado. Este modo é incompatível com armazenamento na Web por razões óbvias. Os fabricantes de navegadores estão experimentando com diferentes cenários como lidar com essa incompatibilidade.

+ +

A maioria dos navegadores optaram por uma estratégia onde as APIs de armazenamento ainda estão disponíveis e, aparentemente, funcional, com a grande diferença de que todos os dados armazenados é apagado depois que o navegador é fechado. Para estes navegadores ainda existem diferentes interpretações sobre o que deve ser feito com os dados existentes armazenados (a partir de uma sessão de navegação regular). E quanto   a leitura dos dados se o navegador estiver no modo privado? Há alguns navegadores, principalmente Safari, que optaram por uma solução em que o armazenamento está disponível, mas está vazio e tem uma quota de 0 bytes atribuídos, tornando impossível o armazenamento de dados.

+ +

Os desenvolvedores devem estar cientes e considerar as diferentes formas de implementações ao desenvolverem sites dependendo das APIs Web Storage. Para mais informações, leia neste post escrito no blog do WHATWG que lida especificamente com este tópico.

+ +

Veja também

+ +

Usando a API Web Storage

diff --git a/files/pt-br/web/api/web_storage_api_pt_br/using_the_web_storage_api/index.html b/files/pt-br/web/api/web_storage_api_pt_br/using_the_web_storage_api/index.html new file mode 100644 index 0000000000..eb9807f0ef --- /dev/null +++ b/files/pt-br/web/api/web_storage_api_pt_br/using_the_web_storage_api/index.html @@ -0,0 +1,267 @@ +--- +title: Usando a API Web Storage +slug: Web/API/Web_Storage_API_pt_br/Using_the_Web_Storage_API +tags: + - API + - Guía + - Storage + - Web Storage API + - localStorage + - sessionStorage +translation_of: Web/API/Web_Storage_API/Using_the_Web_Storage_API +--- +
{{DefaultAPISidebar("Web Storage API")}}
+ +
+

A API Web Storage fornece mecanismos pelos quais os navegadores podem armazenar pares de chaves/valores de uma maneira muito mais segura e intuitiva do que usar cookies. Este artigo fornece um passo a passo sobre como usar essa tecnologia.

+
+ +

Conceitos básicos

+ +

Objetos Storage são simples conjuntos contendo pares de chave/valor, de forma parecida com objetos, porém eles permanecem intactos mesmo após a página ser recarregada. As chaves e valores são sempre strings (note que chaves cujo nome seja um número inteiro serão automaticamente convertidas par strings, assim como acontece nos objetos). Você pode acessar esses valores como você faria com um objeto ou usando os métodos {{domxref("Storage.getItem()")}} e {{domxref("Storage.setItem()")}}. As três linhas seguintes definem o valor de corDefinida de maneiras diferentes, mas com o mesmo resultado:

+ +
localStorage.corDefinida = '#a4509b';
+localStorage['corDefinida'] = '#a4509b';
+localStorage.setItem('corDefinida', '#a4509b');
+ +
+

Nota: Recomendamos que você utilize a API Web Storage (setItemgetItemremoveItemkeylength) para evitar as armadilhas associadas ao uso de objetos literais como mapas de chave-valor.

+
+ +

Os dois mecanismos presentes na Web Storage são os seguintes:

+ + + +

Esses mecanismos estão disponíveis através das propriedades {{domxref("Window.sessionStorage")}} e {{domxref("Window.localStorage")}} (de forma mais específica, em navegadores compatíveis, o objeto Window implementa os objetos WindowLocalStorageWindowSessionStorage, aos quais as propriedades localStorage and sessionStorage pertencem, respectivamente) — invocar uma dessas propriedades irá criar uma instância do objeto {{domxref("Storage")}}, através do qual itens de dados podem ser definidos, acessados e removidos. Cada origem recebe objetos Storage diferentes para sessionStorage and localStorage — eles operam e são controlados separadamente.

+ +

Por exemplo, chamar localStorage pela primeira vez em um documento retornará um objeto {{domxref("Storage")}}; chamar sessionStorage em um documento retornará um outro objeto {{domxref("Storage")}}. Ambos podem ser manipulados da mesma maneira, mas de forma isolada.

+ +

Detectando a disponibilidade do localStorage

+ +

Para poder usarmos o localStorage, devemos antes verificar se ele é compatível e está disponível na sessão atual de navegação.

+ +

Testando a disponibilidade

+ +

Navegadores compatíveis com localStorage terão uma propriedade no objeto window chamada localStorage. Contudo, por várias razões, apenas verificar se essa propriedade existe pode gerar erros. Se ela existir, ainda não haverá garantias de que o localStorage está de fato disponível para uso, já que vários navegadores fornecem opções que desativam o localStorage. Dessa forma, um navegador pode ser compatível com o localStorage, mas também pode não torná-lo disponível para os scripts usarem. One example of that is Safari, which in Private Browsing mode gives us an empty localStorage object with a quota of zero, effectively making it unusable. However, we might still get a legitimate QuotaExceededError, which only means that we've used up all available storage space, but storage is actually available. Our feature detect should take these scenarios into account.

+ +

Here is a function that detects whether localStorage is both supported and available:

+ +
function storageAvailable(type) {
+    try {
+        var storage = window[type],
+            x = '__storage_test__';
+        storage.setItem(x, x);
+        storage.removeItem(x);
+        return true;
+    }
+    catch(e) {
+        return e instanceof DOMException && (
+            // everything except Firefox
+            e.code === 22 ||
+            // Firefox
+            e.code === 1014 ||
+            // test name field too, because code might not be present
+            // everything except Firefox
+            e.name === 'QuotaExceededError' ||
+            // Firefox
+            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
+            // acknowledge QuotaExceededError only if there's something already stored
+            storage.length !== 0;
+    }
+}
+ +

And here is how you would use it:

+ +
if (storageAvailable('localStorage')) {
+  // Yippee! We can use localStorage awesomeness
+}
+else {
+  // Too bad, no localStorage for us
+}
+ +

You can test for sessionStorage instead by calling storageAvailable('sessionStorage').

+ +

See here for a brief history of feature-detecting localStorage.

+ +

Example

+ +

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 color, 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 and load it again, later on, your choices are remembered.

+ +

We have also 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 a {{domxref("StorageEvent")}} is fired.

+ +

+ +
+

Note: As well as viewing the example pages live using the above links, you can also check out the source code.

+
+ +

Testing whether your storage has been populated

+ +

To start with on main.js, we will test whether the storage object has already been populated (i.e., the page was previously accessed):

+ +
if(!localStorage.getItem('bgcolor')) {
+  populateStorage();
+} else {
+  setStyles();
+}
+ +

The {{domxref("Storage.getItem()")}} method is used to get a data item from storage; in this case, we are testing to see whether the bgcolor item exists; if not, we run populateStorage() to add the existing customization values to the storage. If there are already values there, we run setStyles() to update the page styling with the stored values.

+ +

Note: You could also use {{domxref("Storage.length")}} to test whether the storage object is empty or not.

+ +

Getting values from storage

+ +

As noted above, values can be retrieved from storage using {{domxref("Storage.getItem()")}}. This takes the key of the data item as an argument, and returns the data value. For example:

+ +
function setStyles() {
+  var currentColor = localStorage.getItem('bgcolor');
+  var currentFont = localStorage.getItem('font');
+  var currentImage = localStorage.getItem('image');
+
+  document.getElementById('bgcolor').value = currentColor;
+  document.getElementById('font').value = currentFont;
+  document.getElementById('image').value = currentImage;
+
+  htmlElem.style.backgroundColor = '#' + currentColor;
+  pElem.style.fontFamily = currentFont;
+  imgElem.setAttribute('src', currentImage);
+}
+ +

Here, the first three lines grab the values from local storage. Next, we set the values displayed in the form elements to those values, so that they keep in sync when you reload the page. Finally, we update the styles/decorative image on the page, so your customization options come up again on reload.

+ +

Setting values in storage

+ +

{{domxref("Storage.setItem()")}} is used both to create new data items, and (if the data item already exists) update existing values. This takes two arguments — the key of the data item to create/modify, and the value to store in it.

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
+  localStorage.setItem('font', document.getElementById('font').value);
+  localStorage.setItem('image', document.getElementById('image').value);
+
+  setStyles();
+}
+ +

The populateStorage() function sets three items in local storage — the background color, font, and image path. It then runs the setStyles() function to update the page styles, etc.

+ +

We've also included an onchange handler on each form element so that the data and styling are updated whenever a form value is changed:

+ +
bgcolorForm.onchange = populateStorage;
+fontForm.onchange = populateStorage;
+imageForm.onchange = populateStorage;
+ +

Responding to storage changes with the StorageEvent

+ +

The {{domxref("StorageEvent")}} is fired whenever a change is made to the {{domxref("Storage")}} object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects.

+ +

On the events page (see events.js) the only JavaScript is as follows:

+ +
window.addEventListener('storage', function(e) {
+  document.querySelector('.my-key').textContent = e.key;
+  document.querySelector('.my-old').textContent = e.oldValue;
+  document.querySelector('.my-new').textContent = e.newValue;
+  document.querySelector('.my-url').textContent = e.url;
+  document.querySelector('.my-storage').textContent = e.storageArea;
+});
+ +

Here we add an event listener to the window object that fires when the {{domxref("Storage")}} object associated with the current origin is changed. As you can see above, the event object associated with this event has a number of properties containing useful information — the key of the data that changed, the old value before the change, the new value after that change, the URL of the document that changed the storage, and the storage object itself.

+ +

Deleting data records

+ +

Web Storage also provides a couple of simple methods to remove data. We don't use these in our demo, but they are very simple to add to your project:

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#webstorage')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ 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.

+ +
+

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

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/web_workers_api/index.html b/files/pt-br/web/api/web_workers_api/index.html new file mode 100644 index 0000000000..538a92bd1f --- /dev/null +++ b/files/pt-br/web/api/web_workers_api/index.html @@ -0,0 +1,213 @@ +--- +title: Web Workers API +slug: Web/API/Web_Workers_API +translation_of: Web/API/Web_Workers_API +--- +

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

+ +

Web Workers são mecanismos que permitem que uma operação de um dado script seja executado em uma thread diferente da thread principal da aplicação Web. Permitindo que cálculos laboriosos sejam processados sem que ocorra bloqueio da thread principal (geralmente associado à interface).

+ +

 

+ +

Web Workers: conceitos e uso

+ +

Um "worker" é um objeto criado através da utilização do construtor (ex {{domxref("Worker.Worker", "Worker()")}}) que executa um dado arquivo Javascript —  o código contido em tal arquivo é executado no thread do worker; e tais workers são executados em um contexto diferente do principal {{domxref("window")}}. O contexto dos workers é representado pelo objeto {{domxref("DedicatedWorkerGlobalScope")}} no caso de workers dedicados (workers padrões são utilizados por um único script; workers compartilhados utilizam {{domxref("SharedWorkerGlobalScope")}}).

+ +

O thread do worker roda qualquer trecho de código, mas é importante ressaltar que esse trecho não poderá manipular o DOM, ou usar alguns métodos e propriedades do objeto {{domxref("window")}}. Mas, é permitido usar um grande número de itens fornecidos pelo objeto window, incluindo WebSockets, mecanismos de data storage tais como IndexedDB, Firefox OS-only Data Store API. Para mais detalhes veja Funções e classes disponíveis para os workers.

+ +

O thread principal e os threads dos workers comunicam-se entre si enviando dados através do sistema de mensagens — ambos os lados enviam mensagens usando o método postMessage(), e respondem as mensagens via o manipulador de eventos onmessage (a mensagem está contida no atributo data do evento {{event("Message")}}). É importante ressaltar que os dados são copiados, e não compartilhados.

+ +

Workers podem, por sua vez, gerar novos workers, desde que esses workers sejam hospedados na mesma origem que a página principal. Além disso, workers podem usar XMLHttpRequest para network I/O, com a exceção de que os atributos responseXMLchannel do XMLHttpRequest sempre retornam nulo.

+ +

Além dos workers dedicados, existem outros tipos de workers:

+ + + +

Interfaces Web Worker

+ +
+
{{domxref("AbstractWorker")}}
+
Propriedades Abstratas e métodos comuns a todos tipos de workers (i.e. {{domxref("Worker")}} ou {{domxref("SharedWorker")}}).
+
{{domxref("Worker")}}
+
Representa a worker thread em execução, permitindo que você passe mensagens para o código em execução.
+
{{domxref("SharedWorker")}}
+
Representa um tipo específico de worker que pode ser acessado a partir de vários contextos de navegação, sendo várias janelas, iframes ou mesmo workers.
+
{{domxref("WorkerGlobalScope")}}
+
Representa o escopo genérico de qualquer worker (fazendo o mesmo trabalho como {{domxref("Window")}} para conteúdo normal da web). Diferentes tipos de workers têm objetos de escopo que herdam desta interface e adicionam recursos mais específicos.
+
{{domxref("DedicatedWorkerGlobalScope")}}
+
Representa o escopo de um dedicated worker, herdado de {{domxref("WorkerGlobalScope")}} e adicionam recursos mais específicos.
+
{{domxref("SharedWorkerGlobalScope")}}
+
Representa o escopo de um shared worker, herdado de {{domxref("WorkerGlobalScope")}} e adicionam recursos mais específicos.
+
{{domxref("WorkerNavigator")}}
+
Representa a identidade e estado do user agent (o cliente):
+
+ +

Exemplos

+ +

Criamos algumas demonstrações simples para mostrar o uso básico:

+ + + +

Você pode descobrir mais informações sobre como essas demonstrações funcionam em Usando web workers.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#toc-workers')}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers')}}{{Spec2('Web Workers')}}Initial definition.
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop(1.9.1)}}10.010.64
Shared workers4{{CompatGeckoDesktop(29)}}{{CompatNo}}10.64
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 [1]
+ 23
{{CompatGeckoDesktop(21)}}11156 [2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome MobileFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44{{CompatGeckoDesktop(1.9.1)}}1.0.110.011.55.1
Shared workers{{CompatNo}}4291.4{{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][2] Como em webkitURL.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/webgl_api/index.html b/files/pt-br/web/api/webgl_api/index.html new file mode 100644 index 0000000000..97e1e97857 --- /dev/null +++ b/files/pt-br/web/api/webgl_api/index.html @@ -0,0 +1,278 @@ +--- +title: WebGL +slug: Web/API/WebGL_API +tags: + - WebGL +translation_of: Web/API/WebGL_API +--- +
{{WebGLSidebar}}
+ +
+

WebGL (Web Graphics Library) é uma API do JavaScript para renderizar gráficos 3D e 2D dentro de um navegador web compatível sem o uso de plug-ins. O WebGL faz isso introduzindo uma API que está de acordo com o OpenGL ES 2.0 e que pode ser usada em elementos do HTML5 {{HTMLElement("canvas")}}.

+
+ +

O suporte para WebGL está presente no Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+ e Internet Explorer 11+. No entanto, o dispositivo do usuário também deve ter um hardware que suporte esses recursos.

+ +

O elemento {{HTMLElement("canvas")}} é também usado pelo Canvas 2D para renderizar gráficos 2D em páginas web.

+ +

Referências

+ +

Interfaces padrão

+ +
+ +
+ +

Extensões

+ +
+ +
+ +

Eventos

+ + + +

Constantes e tipos

+ + + +

WebGL 2

+ +

O WebGL 2 é uma atualização importante para o WebGL, que é fornecida através da interface {{domxref ("WebGL2RenderingContext")}}. Baseia-se no OpenGL ES 3.0 e os novos recursos incluem:

+ + + +

Veja também os posts WebGL 2 lands in Firefox e webglsamples.org/WebGL2Samples para alguns exemplos de demonstração.

+ +

Guias e tutoriais

+ + + +

Tutoriais avançados

+ + + +

Recursos

+ + + +

Bibliotecas

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('WebGL')}}{{Spec2('WebGL')}}Definição inicial. Baseada em OpenGL ES 2.0
{{SpecName('WebGL2')}}{{Spec2('WebGL2')}}Criada com base no WebGL 1. Baseada em 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 em navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico9{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}11125.1
WebGL 256{{CompatNo}}{{CompatGeckoDesktop("51")}}{{CompatNo}}43{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico25{{CompatVersionUnknown}}4{{CompatNo}}128.1
WebGL 2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Notas sobre compatibilidade

+ +

Além do navegador, a própria GPU também precisa suportar o recurso. Por exemplo, o S3 Texture Compression (S3TC) só está disponível em tablets baseados em Tegra. A maioria dos navegadores disponibiliza o contexto WebGL usando o nome de contexto webgl, mas navegadores antigos também precisam do nome de contexto experimental-webgl. Além disso, o futuro WebGL 2 é totalmente retrocompatível e terá o nome de contexto webgl2.

+ +

Notas sobre o Gecko

+ +

Debugando e testando WebGL

+ +

Iniciando com o Gecko 10.0 {{geckoRelease("10.0")}}, há duas preferências disponíveis que permitem controlar as funcionalidades do WebGL, para efeitos de teste:

+ +
+
webgl.min_capability_mode
+
Uma propriedade booleana que, quando configurada para true, habilita um modo de capacidade mínima. Neste modo, o WebGL é configurado para suportar somente um conjunto básico de recursos e funcionalidades requeridos pela especificação WebGL. Isto garante que o código WebGL funcione em qualquer dispositivo ou navegador, independente de suas funcionalidades. Esta propriedade tem o valor false por padrão.
+
webgl.disable_extensions
+
Uma propriedade booleana que, quando configurada para true, desabilita todas as extensões WebGL. Esta propriedade tem o valor false por padrão.
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/webgl_api/tutorial/adicionando_conteudo_2d_a_um_contexto_webgl/index.html b/files/pt-br/web/api/webgl_api/tutorial/adicionando_conteudo_2d_a_um_contexto_webgl/index.html new file mode 100644 index 0000000000..7b4f6384f6 --- /dev/null +++ b/files/pt-br/web/api/webgl_api/tutorial/adicionando_conteudo_2d_a_um_contexto_webgl/index.html @@ -0,0 +1,226 @@ +--- +title: Adicionando conteúdo 2D a um contexto WebGL +slug: Web/API/WebGL_API/Tutorial/Adicionando_conteudo_2D_a_um_contexto_WebGL +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL")}}

+ +

Uma vez que você tenha  criado um contexto WebGL com sucesso, você pode iniciar a renderizar nele. O mais simples que podemos fazer é desenhar um objeto 2D não texturizado. Então vamos começar por aí, construindo o código necessário para se desenhar um quadrado.

+ +

Desenhando a cena

+ +

A coisa mais importante para se entender antes de começarmos é que, mesmo que estejamos só renderizando um objeto bidimensional nesse exemplo, nós ainda estamos desenhamos em um espaço 3d. Portanto, ainda precisamos estabelecer os shaders que irão criar a cor para a nossa cena simples, assim como desenhar o objeto. Eles irão estabelecer como o quadrado irá aparecer na tela.

+ +

Inicializando os shaders

+ +

Shaders são especificados ao usar a Linguagem de Shading OpenGL ES. Com o intuito de tornar mais fácil para manter e atualizar nosso conteúdo, nós podemos escrever nosso código que carrega os shaders para buscá-los no documento HTML, ao invés de termos de criar tudo em JavaScript. Vamos dar uma olhada na nossa rotina initShaders(), que cuida dessa tarefa:

+ +
function initShaders() {
+  var fragmentShader = getShader(gl, "shader-fs");
+  var vertexShader = getShader(gl, "shader-vs");
+
+  // Cria o progrma shader
+
+  shaderProgram = gl.createProgram();
+  gl.attachShader(shaderProgram, vertexShader);
+  gl.attachShader(shaderProgram, fragmentShader);
+  gl.linkProgram(shaderProgram);
+
+  // Se falhar ao criar o progrma shader, alerta
+
+  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
+    alert("Não foi possível inicializar o programa shader.");
+  }
+
+  gl.useProgram(shaderProgram);
+
+  vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
+  gl.enableVertexAttribArray(vertexPositionAttribute);
+}
+
+
+ +

Dois programas estão sendo inicializados por essa rotina; o primeiro, fragment shader, é carregado a partir do elemento HTML com o id "shader-fs". O segundo, vertex shader, é carregado pelo elemento HTML com o id "shader-vs". Nós vamos analisar a função getShader() no próximo tutorial; Essa rotina, na verdade, lida com a parte de puxar os programas shader da DOM.

+ +

Então nós criamos o programa shader chamando do objeto WebGL a função createProgram(), anexamos dois shaders nele e fazemos o link com o programa shader. Depois de fazer isso, o parametro LINK_STATUS do objeto g1 é checado para ter certeza de que o link foi criado com sucesso; Se sim, nós ativamos o novo programa shader.

+ +

Carregando os shaders da DOM

+ +

A rotina getShader() busca um programa shader com o nome específico do DOM, retornando o programa shader compilado para o requisitante, ou null se ele não pode ser carregado ou compilado.

+ +
function getShader(gl, id) {
+  var shaderScript, theSource, currentChild, shader;
+
+  shaderScript = document.getElementById(id);
+
+  if (!shaderScript) {
+    return null;
+  }
+
+  theSource = "";
+  currentChild = shaderScript.firstChild;
+
+  while(currentChild) {
+    if (currentChild.nodeType == currentChild.TEXT_NODE) {
+      theSource += currentChild.textContent;
+    }
+
+    currentChild = currentChild.nextSibling;
+  }
+
+ +

Uma vez que o elemento com o ID específico é encontrado, seu texto é lido na variável theSource.

+ +
  if (shaderScript.type == "x-shader/x-fragment") {
+    shader = gl.createShader(gl.FRAGMENT_SHADER);
+  } else if (shaderScript.type == "x-shader/x-vertex") {
+    shader = gl.createShader(gl.VERTEX_SHADER);
+  } else {
+     // Tipo de shader desconhecido
+     return null;
+  }
+ +

Uma vez que o código para o shader tenha sido lido, nós observamos o tipo MIME do objeto shader para determinar se é um sombreamento de vértice (MIME type "x-shader/x-vertex") ou um fragmento de shader (MIME type "x-shader/x-fragment"), em seguinda crie um tipo de shader apropriado para a partir do código fonte recuperado.

+ +
  gl.shaderSource(shader, theSource);
+
+  // Compile o programa shader
+  gl.compileShader(shader);
+
+  // Veja se ele compila com sucesso
+  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
+      alert("Um erro ocorreu ao compilar os shaders: " + gl.getShaderInfoLog(shader));
+      return null;
+  }
+
+  return shader;
+}
+
+ +

Finalmente, a fonte é passada para o shader e compilada. Se um erro ocorrer enquanto o shader estiver compilando, nós mostraremos um alerta e retornaremos null; Caso contrário, o shader recém compilado é retornado para o requisitante.

+ +

Os shaders

+ +

Agora, nós precisamos adicionar os programas shaders ao HTML para descrever nosso documento. Os detalhes sobre como os shaders trabalham estão além do escopo deste artigo, assim como a sintaxe da linguagem do shader.

+ +

Fragmentos shader

+ +

Cada pixel é um poligono chamado de fragmento (fragment) na linguagem GL. O trabalho do fragmento de shader é estabelecer a cor de cada pixel. Ness caso, nós estamos apenas definindo a cor branca para cada pixel.

+ +

g1_FragColor é um construtor de variável GL que é utilizado para a cor do fragmento. Altere seu valor para definir a cor do pixel, como mostrado abaixo.

+ +
<script id="shader-fs" type="x-shader/x-fragment">
+  void main(void) {
+    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
+  }
+</script>
+
+ +

Vértice do shader

+ +

A vértice (vertex) do shader define a posição e a forma de cada vértice.

+ +
<script id="shader-vs" type="x-shader/x-vertex">
+  attribute vec3 aVertexPosition;
+
+  uniform mat4 uMVMatrix;
+  uniform mat4 uPMatrix;
+
+  void main(void) {
+    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
+  }
+</script>
+
+ +

Criando um objeto

+ +

Before we can render our square, we need to create the buffer that contains its vertices. We'll do that using a function we call initBuffers(); as we explore more advanced WebGL concepts, this routine will be augmented to create more -- and more complex -- 3D objects.

+ +
var horizAspect = 480.0/640.0;
+
+function initBuffers() {
+  squareVerticesBuffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
+
+  var vertices = [
+    1.0,  1.0,  0.0,
+    -1.0, 1.0,  0.0,
+    1.0,  -1.0, 0.0,
+    -1.0, -1.0, 0.0
+  ];
+
+  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
+}
+
+ +

This routine is pretty simplistic given the basic nature of the scene in this example. It starts by calling the gl object's createBuffer() method to obtain a buffer into which we'll store the vertices. This is then bound to the context by calling the bindBuffer() method.

+ +

Once that's done, we create a JavaScript array containing the coordinates for each vertex of the square. This is then converted into an array of WebGL floats and passed into the gl object's bufferData() method to establish the vertices for the object.

+ +

Desenhando a cena

+ +

Once the shaders are established and the object constructed, we can actually render the scene. Since we're not animating anything in this example, our drawScene() function is very simple. It uses a few utility routines we'll cover shortly.

+ +
function drawScene() {
+  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+
+  perspectiveMatrix = makePerspective(45, 640.0/480.0, 0.1, 100.0);
+
+  loadIdentity();
+  mvTranslate([-0.0, 0.0, -6.0]);
+
+  gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
+  gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
+  setMatrixUniforms();
+  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+}
+
+ +

The first step is to clear the context to our background color; then we establish the camera's perspective. We set a field of view of 45°, with a width to height ratio of 640/480 (the dimensions of our canvas). We also specify that we only want objects between 0.1 and 100 units from the camera to be rendered.

+ +

Then we establish the position of the square by loading the identity position and translating away from the camera by 6 units. After that, we bind the square's vertex buffer to the context, configure it, and draw the object by calling the drawArrays() method.

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample2/index.html', 670, 510) }}

+ +

View the complete code | Open this demo on a new page

+ +

Operações úteis da Matrix

+ +

Matrix operations are complicated enough. Nobody really wants to write all the code needed to handle them on their own. Fortunately, there's Sylvester, a very handy library for handling vector and matrix operations from JavaScript.

+ +

The glUtils.js file used by this demo is used by a number of WebGL demos floating around on the Web. Nobody seems entirely clear on where it came from, but it does simplify the use of Sylvester even further by adding methods for building special types of matrices, as well as outputting HTML for displaying them.

+ +

In addition, this demo defines a few helpful routines to interface with these libraries for specific tasks. What exactly they do is beyond the scope of this demo, but there are plenty of good references on matrices available online; see the {{ anch("See also") }} section for a list of a few.

+ +
function loadIdentity() {
+  mvMatrix = Matrix.I(4);
+}
+
+function multMatrix(m) {
+  mvMatrix = mvMatrix.x(m);
+}
+
+function mvTranslate(v) {
+  multMatrix(Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4());
+}
+
+function setMatrixUniforms() {
+  var pUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
+  gl.uniformMatrix4fv(pUniform, false, new Float32Array(perspectiveMatrix.flatten()));
+
+  var mvUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
+  gl.uniformMatrix4fv(mvUniform, false, new Float32Array(mvMatrix.flatten()));
+}
+
+ +

Ver Também

+ + + +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL")}}

diff --git a/files/pt-br/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html b/files/pt-br/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html new file mode 100644 index 0000000000..4abbd5e304 --- /dev/null +++ b/files/pt-br/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html @@ -0,0 +1,71 @@ +--- +title: Começando com WebGL +slug: Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL +translation_of: Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{Next("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context")}}

+ +

WebGL permite que o contéudo web use uma API baseada em OpenGL ES 2.0 para realizar renderização 3D em um canvas HTML em browsers que o suportam sem o uso de plugins. Programas WebGL consistem em um código de controle escrito em JavaScript e códigos de efeitos especiais (shader code) que é executado na Unidade Gráfica de Processamento (GPU) de um computador. Elementos WebGL podem ser utilizados junto com outros elementos HTML e com outras partes da página ou do fundo.

+ +

Esse artigo vai introduzir o básico sobre o uso do WebGL. Acredita-se que você já possui entendimento da matemática que envolve os gráficos 3D, e que este artigo não tem a pretensão de tentar ensinar-lhe OpenGL em si.

+ +

Os exemplos de código deste tutorial também podem ser encontrados no Exemplos de WebGL no repositório do GitHub.

+ +

Preparando-se para renderizar em 3D

+ +

A primeira coisa que você precisa para para renderização do WebGL, é a inicialização do canvas. O fragmento HTML abaixo declara um canvas em que nosso exemplo será desenhado.

+ +
<body>
+  <canvas id="glCanvas" width="640" height="480"></canvas>
+</body>
+
+ +

Preparando o contexto WebGL

+ +

A função main() em nosso código JavaScript é chamada quando nosso script é carregado. O objetivo é configurar o contexto do WebGL e começar a renderizar o conteúdo.

+ +
main();
+
+//
+// começa aqui
+//
+function main() {
+  const canvas = document.querySelector("#glCanvas");
+  // Inicializa o contexto GL
+  const gl = canvas.getContext("webgl");
+
+  // Só continua se o WebGL estiver disponível e funcionando
+  if (!gl) {
+    alert("Incapaz de inicializar o WebGL.Seu navegador ou sua máquina não suporta.");
+    return;
+  }
+
+  // Define a cor para preto totalmente opaca (sem transparência)
+  gl.clearColor(0.0, 0.0, 0.0, 1.0);
+  // Limpa o buffer de cores com uma cor específica
+  gl.clear(gl.COLOR_BUFFER_BIT);
+}
+
+
+ +

A primeira coisa que nós fazemos aqui é obter a referência para o canvas, atribuindo-a para a variável chamada canvas.

+ +

Uma vez que nós temos o canvas, nós tentamos obter um WebGLRenderingContext para ele chamando o getContext e passando a string "webgl". Se o browser não suportar o webgl getContext vai retornar null nesse caso nós mostraremos uma mensagem para o usuário e sair.

+ +

Se o contexto for inicializado com sucesso, a variável gl é nossa referência para ele. Nesse caso, nós altermos a cor para preto, e o contexto para aquela cor (redesenhando o canvas com a cor de fundo).

+ +

Nesse ponto, você tem código suficiente para o contexto WebGL ser inicializado com sucesso, e você deve visualizar uma grande caixa preta vazia, pronta e esperando para receber conteúdo.

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample1/index.html', 670, 510) }}

+ +

Veja o código completo | Abra a demo em uma nova página

+ +

Veja também

+ + + +

{{Next("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context")}}

diff --git a/files/pt-br/web/api/webgl_api/tutorial/index.html b/files/pt-br/web/api/webgl_api/tutorial/index.html new file mode 100644 index 0000000000..4fa7ba76cf --- /dev/null +++ b/files/pt-br/web/api/webgl_api/tutorial/index.html @@ -0,0 +1,39 @@ +--- +title: WebGL tutorial +slug: Web/API/WebGL_API/Tutorial +tags: + - WebGL +translation_of: Web/API/WebGL_API/Tutorial +--- +
{{WebGLSidebar}}
+ +
+

WebGL enables web content to use an API based on OpenGL ES 2.0 to perform 3D rendering in an HTML {{HTMLElement("canvas")}} in browsers that support it without the use of plug-ins. WebGL programs consist of control code written in JavaScript and special effects code(shader code) that is executed on a computer's Graphics Processing Unit (GPU). WebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background.

+
+ +

This tutorial describes how to use the <canvas> element to draw WebGL graphics, starting with the basics. The examples provided should give you some clear ideas what you can do with WebGL and will provide code snippets that may get you started in building your own content.

+ +

Before you start

+ +

Using the <canvas> element is not very difficult, but you do need a basic understanding of HTML and JavaScript. The <canvas> element and WebGL are not supported in some older browsers, but are supported in recent versions of all major browsers. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly.

+ +

In this tutorial

+ +
+
Getting started with WebGL
+
How to set up a WebGL context.
+
Adding 2D content to a WebGL context
+
How to render simple flat shapes using WebGL.
+
Using shaders to apply color in WebGL
+
Demonstrates how to add color to shapes using shaders.
+
Animating objects with WebGL
+
Shows how to rotate and translate objects to create simple animations.
+
Creating 3D objects using WebGL
+
Shows how to create and animate a 3D object (in this case, a cube).
+
Using textures in WebGL
+
Demonstrates how to map textures onto the faces of an object.
+
Lighting in WebGL
+
How to simulate lighting effects in your WebGL context.
+
Animating textures in WebGL
+
Shows how to animate textures; in this case, by mapping an Ogg video onto the faces of a rotating cube.
+
diff --git a/files/pt-br/web/api/webrtc_api/index.html b/files/pt-br/web/api/webrtc_api/index.html new file mode 100644 index 0000000000..f4a91242e3 --- /dev/null +++ b/files/pt-br/web/api/webrtc_api/index.html @@ -0,0 +1,197 @@ +--- +title: WebRTC API +slug: Web/API/WebRTC_API +tags: + - API + - Audio + - Landing + - Media + - NeedsTranslation + - Networking + - TopicStub + - Video + - WebRTC + - WebRTC API + - streaming +translation_of: Web/API/WebRTC_API +--- +
{{APIRef("WebRTC")}}
+ +

WebRTC (Web Real-Time Communications) é uma tecnologia que permite aplicativos e sites da Web a capturarem e opcionalmente transmitirem mídia de áudio e/ou vídeo, assim como trocar informação arbitrária entre navegadores sem a necessidade de um intermediador. O conjunto de padrões que abrangem WebRTC possibilita o compartilhamento de informação e a realização de teleconferência peer-to-peer, dispensando a instalação de plug-ins ou quaisquer softwares de terceiros.

+ +

WebRTC consiste em diversas APIs e protocolos interrelacionados que trabalham juntos. A documentação que você encontrará aqui o ajudará a entender os fundamentos de WebRTC, como configurar e usar, tanto informação, quanto conexões de mídia e mais. 

+ +

WebRTC conceitos e uso

+ +

WebRTC serve à diversas propostas, e sobrepõe-se substancialmente com a API de Captura e Transmissão. Juntas, provém capacidades poderosas de multimídia para a Web, incluíndo suporte para conferência em áudio e vídeo, troca de arquivos, administração de identidade, e lidando com sistemas telefônicos legados enviando sinais {{Glossary("DTMF")}}.

+ +

Conexões entre dois peers são criadas usando—e representadas por—uma interface {{DOMxRef("RTCPeerConnection")}}. Uma vez que a conexão tenha sido estabilizada e iniciada, media streams ({{DOMxRef("MediaStream")}}s) (transmissões de mídia) e/ou data channels ({{DOMxRef("RTCDataChannel")}}s) (canais de dados) podem ser adicionados à conexão.

+ +

Dados de mídia podem consistir em qualquer número de tracks(faixas) de dados de mídia; tracks, que são representados por objetos baseados na interface {{DOMxRef("MediaStreamTrack")}} , que podem conter um número dentre tipos de dados de mídia, incluíndo áudio, vídeo e texto (como legendas ou até mesmo nomes de capítulos). A maioria das transmissões consiste de ao menos uma faixa de áudio e comumente também uma faixa de vídeo, e podem ser usadas para enviar e receber ambas as mídias ao vivo ou dados salvos de mídia (como um filme transmitido).

+ +

Você também pode usar a conexão entre dois peers para trocar dados arbitrários binários usando a interface {{DOMxRef("RTCDataChannel")}}. Isto pode ser usado para informação de back-channel (canal de volta), troca de metadata, pacotes de status de games, transferência de arquivos, ou até mesmo como um canal primário para transferir dados.

+ +

são necessários mais detalhes e links e tutoriais relevantes

+ +

WebRTC interfaces

+ +

Porque WebRTC provê interfaces que trabalham em conjunto para realizar uma variedade de tarefas, nós dividimos as interfaces na listagem abaixo por categoria. Por favor, atente-se a sidebar para uma listagem em ordem alfabética.

+ +

Conexão, configuração e gerenciamento

+ +

Estas interfaces são usadas para configurar, abrir e gerenciar conexões WebRTC.

+ +
+
{{domxref("RTCPeerConnection")}}
+
Representa a conexão WebRTC entre o computador local e um peer remoto. É usado para lidar com um streaming eficiente de dados entre os dois peers.
+
{{domxref("RTCDataChannel")}}
+
Representa um canal de dados bidirecional entre dois peers de uma conexão
+
{{domxref("RTCDataChannelEvent")}}
+
Represents events that occur while attaching a {{domxref("RTCDataChannel")}} to a {{domxref("RTCPeerConnection")}}. The only event sent with this interface is {{event("datachannel")}}.
+
{{domxref("RTCSessionDescription")}}
+
Represents the parameters of a session. Each RTCSessionDescription consists of a description type indicating which part of the offer/answer negotiation process it describes and of the SDP descriptor of the session.
+
{{domxref("RTCStatsReport")}}
+
Provides information detailing statistics for a connection or for an individual track on the connection; the report can be obtained by calling {{domxref("RTCPeerConnection.getStats()")}}.
+
{{domxref("RTCIceCandidate")}}
+
Represents a candidate internet connectivity establishment (ICE) server for establishing an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCIceTransport")}}
+
Represents information about an internet connectivity establishment (ICE) transport.
+
{{domxref("RTCPeerConnectionIceEvent")}}
+
Represents events that occurs in relation to ICE candidates with the target, usually an {{domxref("RTCPeerConnection")}}. Only one event is of this type: {{event("icecandidate")}}.
+
{{domxref("RTCRtpSender")}}
+
Manages the encoding and transmission of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCRtpReceiver")}}
+
Manages the reception and decoding of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCTrackEvent")}}
+
Indicates that a new incoming {{domxref("MediaStreamTrack")}} was created and an associated {{domxref("RTCRtpReceiver")}} object was added to the {{domxref("RTCPeerConnection")}} object.
+
+ +

Identity and security

+ +

The WebRTC API includes a number of interfaces to manage security and identity.

+ +
+
{{domxref("RTCIdentityProvider")}}
+
Enables a user agent is able to request that an identity assertion be generated or validated.
+
{{domxref("RTCIdentityAssertion")}}
+
Represents the identity of the a remote peer of the current connection. If no peer has yet been set and verified this interface returns null. Once set it can't be changed.
+
{{domxref("RTCIdentityProviderRegistrar")}}
+
Registers an  identity provider (idP).
+
{{domxref("RTCIdentityEvent")}}
+
Represents an identity assertion generated by an identity provider (idP). This is usually for an {{domxref("RTCPeerConnection")}}. The only event sent with this type is {{event("identityresult")}}.
+
{{domxref("RTCIdentityErrorEvent")}}
+
Represents an error associated with the identity provider (idP). This is usually for an {{domxref("RTCPeerConnection")}}. Two events are sent with this type: {{event("idpassertionerror")}} and {{event("idpvalidationerror")}}.
+
{{domxref("RTCCertificate")}}
+
Represents a certificate that an {{domxref("RTCPeerConnection")}} uses to authenticate.
+
+ +

Telephony

+ +

These interfaces are related to interactivity with public-switched telephone networks (PTSNs).

+ +
+
{{domxref("RTCDTMFSender")}}
+
Manages the encoding and transmission of dual-tone multi-frequency (DTMF) signaling for an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCDTMFToneChangeEvent")}}
+
Indicates an occurrence of a of dual-tone multi-frequency (DTMF). This event does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated).
+
+ +

Guides

+ +
+
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.
+
+ +

Tutorials

+ +
+
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.
+
+ +

Resources

+ +

Protocols

+ +

WebRTC-proper protocols

+ + + + + + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}The initial definition of the API of WebRTC.
{{SpecName('Media Capture')}}{{Spec2('Media Capture')}}The initial definition of the object conveying the stream of media content.
{{SpecName('Media Capture DOM Elements')}}{{Spec2('Media Capture DOM Elements')}}The initial definition on how to obtain stream of content from DOM Elements
+ +

In additions to these specifications defining the API needed to use WebRTC, there are several protocols, listed under resources.

+ + + + diff --git a/files/pt-br/web/api/webrtc_api/protocols/index.html b/files/pt-br/web/api/webrtc_api/protocols/index.html new file mode 100644 index 0000000000..973a160ca7 --- /dev/null +++ b/files/pt-br/web/api/webrtc_api/protocols/index.html @@ -0,0 +1,70 @@ +--- +title: Introdução aos protocolos WebRTC +slug: Web/API/WebRTC_API/Protocols +tags: + - API + - Audio + - Guía + - ICE + - Iniciante + - Media + - NAT + - Projeto + - SDP + - STUN + - TURN + - Video + - WebRTC + - WebRTC API +translation_of: Web/API/WebRTC_API/Protocols +--- +
{{WebRTCSidebar}}{{draft}}
+ +

Este artigo apresenta os protocolos sobre os quais a API WebRTC é construída.

+ +

ICE

+ +

Interactive Connectivity Establishment (ICE) é a estrutura que permite seu navegador web se conectar com outras pessoas. Existem muitas razões pelas quais uma conexão direta do Ponto A para o Ponto B simplesmente não funciona. Ele precisa ignorar firewalls que impediriam a abertura de conexões, fornecer um endereço exclusivo, como na maioria das situações, caso seu dispositivo não tiver um endereço IP público e retransmitir dados por meio de um servidor ou se seu roteador não permitir a conexão direta com seus pares . O ICE usa servidores STUN e / ou TURN para fazer isso, conforme descrito abaixo.

+ +

STUN

+ +

Session Traversal Utilities for NAT (STUN) (sigla dentro de uma sigla) é um protocolo para descobrir seu endereço público e determinar quaisquer restrições em seu roteador que poderiam impedir uma conexão direta com um par.

+ +

O cliente enviará uma solicitação a um servidor STUN na Internet que responderá com o endereço público do cliente e se o cliente está ou não acessível por meio do NAT do roteador.

+ +

An interaction between two users of a WebRTC application involving a STUN server.

+ +

NAT

+ +

Network Address Translation (NAT) é usado para dar ao seu dispositivo um endereço IP público. Um roteador terá um endereço IP público e cada dispositivo conectado ao roteador terá um endereço IP privado. As solicitações serão traduzidas do IP privado do dispositivo para o IP público do roteador com uma porta exclusiva. Dessa forma, você não precisa de um IP público exclusivo para cada dispositivo, mas ainda pode ser descoberto na Internet.

+ +

Alguns roteadores terão restrições sobre quem pode se conectar a dispositivos na rede. Isso pode significar que, embora tenhamos o endereço IP público encontrado pelo servidor STUN, ninguém pode criar uma conexão. Nesta situação, precisamos voltar para TURN.

+ +

TURN

+ +

Alguns roteadores que usam NAT empregam uma restrição chamada ‘Symmetric NAT’ (NAT simétrico). Isso significa que o roteador só aceitará conexões de pares aos quais você já se conectou.

+ +

Traversal Using Relays around NAT (TURN) destina-se a contornar a restrição de NAT simétrico abrindo uma conexão com um servidor TURN para que ele re-transmita toda informação. Você criaria uma conexão com um servidor TURN e avisaria a todos os pares (peers) para enviar pacotes para este servidor, que lhe encaminharia. Isso obviamente vem com alguma sobrecarga, então só é usado se não houver outras alternativas.

+ +

An interaction between two users of a WebRTC application involving STUN and TURN servers.

+ +

SDP

+ +

Session Description Protocol (SDP) é um padrão para descrever o conteúdo multimídia da conexão, como resolução, formatos, codecs, criptografia, etc., para que os dois pontos possam se entender uma vez que os dados estejam sendo transferidos. Em essência, são os metadados que descrevem o conteúdo e não o conteúdo da mídia em si.

+ +

Tecnicamente, então, SDP não é realmente um protocolo, mas um formato de dados usado para descrever a conexão que compartilha mídia entre dispositivos.

+ +

A documentação do SDP está bem fora do escopo desta documentação; no entanto, existem algumas coisas que vale a pena observar aqui.

+ +

Estrutura

+ +

O SDP consiste em uma ou mais linhas de texto UTF-8, cada uma começando com um tipo de um caractere, seguido por um sinal de igual ("="), seguido por um texto estruturado contendo um valor ou descrição, cujo formato depende do tipo. As linhas de texto que começam com uma determinada letra são geralmente chamadas de "letter-lines" ("linhas de letras"). Por exemplo, as linhas que fornecem descrições de mídia têm o tipo "m", portanto, essas linhas são chamadas de "linhas m".

+ +

Para mais informações

+ +

Para saber mais sobre o SDP, consulte os seguintes recursos úteis:

+ + diff --git a/files/pt-br/web/api/webrtc_api/simples_rtcdatachannel_amostra/index.html b/files/pt-br/web/api/webrtc_api/simples_rtcdatachannel_amostra/index.html new file mode 100644 index 0000000000..72ac37e56a --- /dev/null +++ b/files/pt-br/web/api/webrtc_api/simples_rtcdatachannel_amostra/index.html @@ -0,0 +1,272 @@ +--- +title: Uma simples amostra de RTCDataChannel +slug: Web/API/WebRTC_API/Simples_RTCDataChannel_amostra +translation_of: Web/API/WebRTC_API/Simple_RTCDataChannel_sample +--- +

{{WebRTCSidebar}}

+ +

A interface {{domxref("RTCDataChannel")}} é um recurso da WebRTC API que permite abrir um canal entre dois pares sobre os quais você pode enviar e receber dados arbitrários. A API é intencionalmente semelhante à WebSocket API, de modo que o mesmo modelo de programação pode ser usado para ambos.

+ +

Neste exemplo, abriremos um {{domxref("RTCDataChannel")}} para realizar a conexão entre dois elementos na mesma página. Embora seja obviamente um cenário artificial, é útil para demonstrar o fluxo de conexão entre dois pares. Vamos cobrir a mecânica necessária para conectar, transmitir e receber dados, mas vamos deixar para outro exemplo os detalhes sobre como localizar e se conectar a um computador remoto.

+ +

O HTML

+ +

Primeiro, vamos dar uma olhada rápida no HTML que é necessário. Não há nada incrivelmente complicado aqui. Primeiro, temos um par de botões para estabelecer e fechar a conexão:

+ +
<button id="connectButton" name="connectButton" class="buttonleft">
+  Conectar
+</button>
+<button id="disconnectButton" name="disconnectButton" class="buttonright" disabled>
+  Desconectar
+</button>
+ +

Depois, há uma caixa que contém o campo de input no qual o usuário pode digitar uma mensagem para transmitir, com um botão para enviar o texto digitado. Este {{HTMLElement("div")}} será o primeiro ponto (peer) no canal.

+ +
  <div class="messagebox">
+    <label for="message">Insira a mensagem:
+      <input type="text" name="message" id="message" placeholder="Texto da mensagem"
+              inputmode="latin" size=60 maxlength=120 disabled>
+    </label>
+    <button id="sendButton" name="sendButton" class="buttonright" disabled>
+      Enviar
+    </button>
+  </div>
+ +

Finalmente, há uma pequena caixa na qual vamos inserir as mensagens. Este bloco {{HTMLElement("div")}} será o segundo ponto do par (peer).

+ +
<div class="messagebox" id="receivebox">
+  <p>Mensagens recebidas:</p>
+</div>
+ +

O código JavaScript

+ +

Como você pode simplesmente ver o próprio código no GitHub, abaixo, analisaremos as partes do código que fazem o trabalho pesado.

+ +

A WebRTC API faz um intenso uso de {{jsxref("Promise")}}s. Que tornam muito fácil encadear as etapas do processo de conexão; Se você ainda não leu sobre esta funcionalidade do ECMAScript 2015, você deveria ler sobre eles. Da mesma forma, este exemplo usa arrow functions para simplificar a sintaxe.

+ +

Começando

+ +

Quando o script é executado, configuramos um {{event("load")}} ouvinte de eventos (event listener), De modo que, uma vez que a página esteja totalmente carregada, nossa função startup() seja chamada.

+ +
function startup() {
+  connectButton = document.getElementById('connectButton');
+  disconnectButton = document.getElementById('disconnectButton');
+  sendButton = document.getElementById('sendButton');
+  messageInputBox = document.getElementById('message');
+  receiveBox = document.getElementById('receivebox');
+
+  // Define os ouvintes de eventos para os elementos da interface do usuário
+
+  connectButton.addEventListener('click', connectPeers, false);
+  disconnectButton.addEventListener('click', disconnectPeers, false);
+  sendButton.addEventListener('click', sendMessage, false);
+}
+ +

Isso é bastante direto. Pegamos referências de todos os elementos da página que precisaremos acessar e, em seguida, configuramos {{domxref("EventListener", "event listeners")}} nos três botões.

+ +

Estabelecendo uma conexão

+ +

Quando o usuário clica no botão "Conectar", o método connectPeers() é chamado. Para que fique mais claro, iremos quebrar o código em mais partes, e analisar um pouco de cada vez.

+ +
+

Nota: Mesmo que ambas as extremidades da nossa conexão estejam na mesma página, vamos nos referir ao ponto que inicia a conexão como "local", e ao outro como sendo o "remoto".

+
+ +

Configurando o ponto local (local peer)

+ +
localConnection = new RTCPeerConnection();
+
+sendChannel = localConnection.createDataChannel("sendChannel");
+sendChannel.onopen = handleSendChannelStatusChange;
+sendChannel.onclose = handleSendChannelStatusChange;
+
+ +

O primeiro passo é criar o ponto "local" da conexão. Este é o ponto que enviará o pedido de conexão. O próximo passo é criar o {{domxref("RTCDataChannel")}} chamando {{domxref("RTCPeerConnection.createDataChannel()")}} e configurando ouvintes de eventos (event listeners) para monitorar o canal, e para que possamos saber quando ele for aberto e fechado (isto é, quando o canal está conectado ou desconectado dentro dessa conexão entre pares (peer connection)).

+ +

É importante ter em mente que cada extremidade do canal tem seu próprio objeto {{domxref("RTCDataChannel")}} .

+ +

Configurando o ponto remoto (remote peer)

+ +
remoteConnection = new RTCPeerConnection();
+remoteConnection.ondatachannel = receiveChannelCallback;
+ +

O ponto remoto está configurado de forma semelhante, exceto que não precisamos nós mesmos criar explicitamente um {{domxref("RTCDataChannel")}} , uma vez que vamos ser conectados através do canal estabelecido acima. Em vez disso, criamos um {{event("datachannel")}} manipulador de eventos (event handler); Isso será chamado quando o canal de dados (data channel) for aberto; Este manipulador (handler) receberá um objeto RTCDataChannel; você verá isso abaixo.

+ +

Configurando  ICE candidates

+ +

O próximo passo é configurar cada conexão com os ouvintes do ICE que serão chamados quando houver um novo candidato ICE para comunicar com o outro lado.

+ +
+

Nota: Em um cenário do mundo real em que os dois pares não estão sendo executados no mesmo contexto, o processo é um pouco mais complexo; Cada lado fornece, um de cada vez, um sugestão sobre como conectar (por exemplo, UDP, UDP com um relay, TCP, etc.) chamando {{domxref("RTCPeerConnection.addIceCandidate()")}}, e eles vão de um lado para outro até chegarem a um acordo. Mas aqui, acabamos de aceitar a primeira oferta de cada lado, uma vez que não existe uma rede real envolvida.

+
+ +
    localConnection.onicecandidate = e => !e.candidate
+        || remoteConnection.addIceCandidate(e.candidate)
+        .catch(handleAddCandidateError);
+
+    remoteConnection.onicecandidate = e => !e.candidate
+        || localConnection.addIceCandidate(e.candidate)
+        .catch(handleAddCandidateError);
+ +

Configuramos cada {{domxref("RTCPeerConnection")}} para ter um manipulador de eventos (event handler) para o evento {{event("icecandidate")}} .

+ +

Iniciando a tentativa de conexão

+ +

A última coisa que precisamos fazer para começar a conectar nossos pares é criar uma oferta de conexão.

+ +
    localConnection.createOffer()
+    .then(offer => localConnection.setLocalDescription(offer))
+    .then(() => remoteConnection.setRemoteDescription(localConnection.localDescription))
+    .then(() => remoteConnection.createAnswer())
+    .then(answer => remoteConnection.setLocalDescription(answer))
+    .then(() => localConnection.setRemoteDescription(remoteConnection.localDescription))
+    .catch(handleCreateDescriptionError);
+ +

Vamos passar por isto linha por linha e decifrar o que significa.

+ +
    +
  1. Primeiro chamamos {{domxref("RTCPeerConnection.createOffer()")}} método para criar um resumo {{Glossary("SDP")}} (Session Description Protocol) descrevendo a conexão que queremos fazer. Este método aceita, opcionalmente, um objeto com restrições a serem suportadas pela conexão para atender às suas necessidades, como no caso da conexão precisar suportar áudio, vídeo ou ambos. Em nosso exemplo simples, não temos restrições.
  2. +
  3. Se a oferta for criada com sucesso, passamos o resumo junto ao método de conexões locais {{domxref("RTCPeerConnection.setLocalDescription()")}} . Isso configura o ponto local da conexão.
  4. +
  5. O próximo passo é conectar o ponto local ao remoto comunicando ao ponto remoto sobre ele. Isso é feito chamando remoteConnection.{{domxref("RTCPeerConnection.setRemoteDescription()")}}. Agora o remoteConnection conhece a conexão que está sendo construída.
  6. +
  7. Isso significa que é hora do ponto remoto responder. Ele faz isso chamando o método {{domxref("RTCPeerConnection.createAnswer", "createAnswer()")}} . Isso gera um resumo de SDP que descreve a conexão que o ponto remoto está disposto e capaz de estabelecer. Essa configuração está em algum lugar na união das opções que ambos os pares podem suportar.
  8. +
  9. Uma vez que a resposta foi criada, ela é passada para o remoteConnection chamando {{domxref("RTCPeerConnection.setLocalDescription()")}}. Isso estabelece o ponto remoto da conexão (que, para o ponto remoto, é o ponto local. Isso pode parecer confuso, mas você irá se acostumar com isso.
  10. +
  11. Finalmente, a descrição local das conexões remotas está configurada para se referir ao ponto remoto, chamando localConnection's {{domxref("RTCPeerConnection.setRemoteDescription()")}}.
  12. +
  13. catch() chama uma rotina que lida com os erros que ocorrem.
  14. +
+ +
+

Nota: Mais uma vez, esse processo não é uma implementação do mundo real; No uso normal, há dois pedaços de código executados em duas máquinas, interagindo e negociando a conexão.

+
+ +

Manipulação da conexão de pares bem sucedida

+ +

Como cada lado da conexão peer-to-peer é conectado com sucesso, o evento correspondente {{domxref("RTCPeerConnection")}}'s {{event("icecandidate")}} é disparado. Esses manipuladores podem fazer o que for necessário, mas, neste exemplo, tudo o que precisamos fazer é atualizar a interface do usuário:

+ +
  function handleLocalAddCandidateSuccess() {
+    connectButton.disabled = true;
+  }
+
+  function handleRemoteAddCandidateSuccess() {
+    disconnectButton.disabled = false;
+  }
+ +

A única coisa que fazemos aqui é desativar o botão "Conectar" quando o ponto local estiver conectado e ativar o botão "Desconectar" quando o ponto remoto se conectar.

+ +

Conectando o canal de dados

+ +

Uma vez que o {{domxref("RTCPeerConnection")}} é aberto, o evento {{event("datachannel")}} é enviado para o ponto remoto para completar o processo de abertura do canal de dados; Isso invoca nosso método receiveChannelCallback(), que se parece com isso:

+ +
  function receiveChannelCallback(event) {
+    receiveChannel = event.channel;
+    receiveChannel.onmessage = handleReceiveMessage;
+    receiveChannel.onopen = handleReceiveChannelStatusChange;
+    receiveChannel.onclose = handleReceiveChannelStatusChange;
+  }
+ +

O evento{{event("datachannel")}} inclui, em sua propriedade de canal, uma referência a um {{domxref("RTCDataChannel")}} Representando o ponto remoto do canal. Isso é salvo, e nós configuramos, no canal, ouvintes de eventos para os eventos que queremos manipular. Uma vez feito isso, nosso método handleReceiveMessage() Será chamado cada vez que os dados são recebidos pelo ponto remoto, e o método handleReceiveChannelStatusChange() será chamado sempre que mudar o estado da conexão do canal, para que possamos reagir quando o canal estiver totalmente aberto e quando ele for fechado.

+ +

Lidando com as mudanças de status do canal

+ +

Ambos nossos pontos locais e remotos usam um único método para lidar com eventos que indicam alguma alteração no status da conexão do canal.

+ +

Quando o ponto local experimenta um evento aberto ou fechado, o métodohandleSendChannelStatusChange() é chamado:

+ +
  function handleSendChannelStatusChange(event) {
+    if (sendChannel) {
+      var state = sendChannel.readyState;
+
+      if (state === "open") {
+        messageInputBox.disabled = false;
+        messageInputBox.focus();
+        sendButton.disabled = false;
+        disconnectButton.disabled = false;
+        connectButton.disabled = true;
+      } else {
+        messageInputBox.disabled = true;
+        sendButton.disabled = true;
+        connectButton.disabled = false;
+        disconnectButton.disabled = true;
+      }
+    }
+  }
+ +

Se o estado do canal mudou para "open", isso indica que terminamos de estabelecer o link entre os dois pares. A interface do usuário é atualizada de forma correspondente: ativando o elemento de input de texto para a mensagem a ser enviada, focando este elemento de input para que o usuário comece imediatamente a digitar, habilitando os botões "Enviar" e "Desconectar", que são agora utilizáveis, E desativando o botão "Conectar", uma vez que não é necessário quando a conexão está aberta.

+ +

Se o estado do canal mudou para "closed", ocorre o conjunto oposto de ações: a caixa de entrada de texto e o botão "Enviar" estão desativados, o botão "Conectar" está habilitado para que o usuário possa abrir uma nova conexão se desejar, e o botão "Desconectar" está desativado, uma vez que não é útil quando não existe conexão.

+ +

Nosso exemplo de par remoto, por outro lado, ignora os eventos de alteração de status, exceto para registrar o evento no console:

+ +
  function handleReceiveChannelStatusChange(event) {
+    if (receiveChannel) {
+      console.log("Receive channel's status has changed to " +
+                  receiveChannel.readyState);
+    }
+  }
+ +

O método handleReceiveChannelStatusChange() recebe como parâmetro de entrada o evento que ocorreu; Este será um {{domxref("RTCDataChannelEvent")}}.

+ +

Enviando mensagens

+ +

Quando o usuário pressiona o botão "Enviar", o método sendMessage() que estabelecemos como o manipulador para o evento do botão {{event("click")}} é chamado. Esse método é bastante simples:

+ +
  function sendMessage() {
+    var message = messageInputBox.value;
+    sendChannel.send(message);
+
+    messageInputBox.value = "";
+    messageInputBox.focus();
+  }
+ +

Primeiro, o texto da mensagem é obtido dos atributos do elemento de input {{htmlattrxref("value", "input")}} . Isso é enviado para o ponto remoto, ligando para {{domxref("RTCDataChannel.send", "sendChannel.send()")}}. E está tudo aí! O resto deste método é apenas um pouco de açúcar para experiência do usuário - a caixa de entrada é esvaziada e re-focada para que o usuário comece imediatamente a digitar outra mensagem.

+ +

Recebendo mensagens

+ +

Quando ocorre um evento de "mensagem" no canal remoto, nosso método handleReceiveMessage() é chamado como o manipulador de eventos.

+ +
  function handleReceiveMessage(event) {
+    var el = document.createElement("p");
+    var txtNode = document.createTextNode(event.data);
+
+    el.appendChild(txtNode);
+    receiveBox.appendChild(el);
+  }
+ +

Este método simplesmente executa alguns injeções básicas {{Glossary("DOM")}} ; cria um novo {{HTMLElement("p")}} (paragraph) elemento, então cria um novo nó {{domxref("Text")}} contendo o texto da mensagem, que é recebido na propriedade de dados do evento. Este nó de texto é anexado como um filho do novo elemento, que é então inserido no bloco receiveBox, fazendo com que ele desenhe na janela do navegador.

+ +

Desconectando os pares (peers)

+ +

Quando o usuário clica no botão "Desconectar", o método disconnectPeers() previamente configurado como o manipulador desse botão é chamado.

+ +
  function disconnectPeers() {
+
+    // Close the RTCDataChannels if they're open.
+
+    sendChannel.close();
+    receiveChannel.close();
+
+    // Close the RTCPeerConnections
+
+    localConnection.close();
+    remoteConnection.close();
+
+    sendChannel = null;
+    receiveChannel = null;
+    localConnection = null;
+    remoteConnection = null;
+
+    // Update user interface elements
+
+    connectButton.disabled = false;
+    disconnectButton.disabled = true;
+    sendButton.disabled = true;
+
+    messageInputBox.value = "";
+    messageInputBox.disabled = true;
+  }
+
+ +

Isso começa por fechar cada par {{domxref("RTCDataChannel")}}, então, de forma semelhante, cada um {{domxref("RTCPeerConnection")}}. Então, todas as referências salvas desses objetos são definidas como null para evitar a reutilização acidental, e a interface do usuário é atualizada para refletir o fato de que a conexão foi fechada.

+ +

Próximos passos

+ +

Você poderia tentar este exemplo e dar uma olhada no código fonte webrtc-simple-datachannel, disponível no GitHub.

diff --git a/files/pt-br/web/api/websocket/index.html b/files/pt-br/web/api/websocket/index.html new file mode 100644 index 0000000000..8eb46000c9 --- /dev/null +++ b/files/pt-br/web/api/websocket/index.html @@ -0,0 +1,323 @@ +--- +title: WebSocket +slug: Web/API/WebSocket +tags: + - API + - WebSocket + - WebSockets +translation_of: Web/API/WebSocket +--- +
{{APIRef("Web Sockets API")}}{{SeeCompatTable}}
+ +

O objeto WebSocket provê uma API para criação e gerenciamento de uma conexão WebSocket com um servidor, bem como o envio e recebimento de dados através dessa conexão.

+ +

O construtor do WebSocket aceita um parâmetro obrigatório e um opcional:

+ +
WebSocket WebSocket(
+  in DOMString url,
+  in optional DOMString protocols
+);
+
+WebSocket WebSocket(
+  in DOMString url,
+  in optional DOMString[] protocols
+);
+
+ +
+
url
+
A URL da devida conexão; esta deve ser a URL da qual o servidor WebSocket irá responder.
+
protocols {{optional_inline}}
+
Um único protocolo em formato texto ou uma lista de textos de protocolo. Estes textos são usados para indicar sub-protocolos, assim então um único servidor pode implementar múltiplos sub-protocolos WebSocket (por exemplo, você pode querer um servidor capaz de manipular diferentes tipos de interações dependendo do protocolo especificado). se você não especificar um protocolo em texto, será assumido um texto vazio.
+
+ +

O construtor pode lançar exceções:

+ +
+
SECURITY_ERR
+
A porta a qual a conexão está sendo executada está bloqueada.
+
+ +

Visão Geral do método

+ + + + + + + + + + +
void close(É opcional: unsigned long code, É opcional: DOMString reason);
void send(in DOMString data);
+ +

Atributos

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributoTipoDescrição
binaryType{{DOMXref("DOMString")}} +

Uma string indica o tipo de dado binário que está sendo transmitido pela conexão. Este deve ser tanto "blob" se o objeto DOM {{domxref("Blob")}} estiver sendo usado ou "arraybuffer" se os objetos {{jsxref("ArrayBuffer")}} estiver sendo usada

+
bufferedAmountunsigned long +

O número de bites de dados que tem sid consultado usando chamadas para {{manch("send")}} mas não ainda para a rede.Estes valor reseta para zero uma vez que todos os dados tem sido mandados.Este valor não reseta para zero quando a conexão está fechada, se você continuar chamando {{manch("send")}}, isto continuará escalando. Leitura online

+
extensions{{DOMXref("DOMString")}}As extensões selecionadas pelo servidor. Este é atualmente apenas a string vazia ou uma lista de extensões negociadas pela conexão.
onclose{{domxref("EventListener")}}Um event listener para ser chamado quando o readyState da conexão do WebSocket mudar para CLOSED . O listener recebe um CloseEvent "close".
onerror{{domxref("EventListener")}}Um event listener para ser chamado quando ocorrer um erro. Este é um evento simples chamado "erro".
onmessage{{domxref("EventListener")}}Um event listener para ser chamado quando uma mensagem é recebida do servidor. O listener recebe um MessageEvent "message".
onopen{{domxref("EventListener")}}Um event listener para ser chamado quando o readyState da conexão do WebSocket mudar para OPEN , isso indica que a conexão está pronta para enviar e receber dados. O evento é simples, com o nome "open".
protocol{{DOMXref("DOMString")}}Uma sequência de caracteres que indica o nome do sub-protocolo selecionado pelo servidor, este será um dos parâmetros especificados no protocolo ao criar o objeto WebSocket.
readyStateunsigned shortO estado atual da conexão, este é um dos {{anch("Ready state constants")}}. Apenas leitura.
url{{DOMXref("DOMString")}}O URL resolvido pelo construtor. Este é sempre um URL absoluto. Apenas leitura.
+ +

Constantes

+ +

Estados de constantes prontas

+ +

Essas constantes são usadas pelo atributo readyState para descrever o estado da conexão do WebSocket.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstanteValorDescrição
CONNECTING0A conexão ainda não está aberta.
OPEN1A conexão está aberta e pronta para se comunicar.
CLOSING2A conexão está em processo de fechamento.
CLOSED3A conexão está fechada ou não foi possível abrir.
+ +

Métodos

+ +

close()

+ +

Fecha a conexão do WebSocket ou a tentativa de conexão, se houver. Se a conexão já for CLOSED , este método não faz nada.

+ +
void close(
+  É opcional: unsigned short code,
+  É opcional: DOMString reason
+);
+
+ +

Parametros

+ +
+
code {{optional_inline}}
+
Um valor numérico que indica o código de status explicando por que a conexão está sendo fechada. Se esse parâmetro não for especificado, é assumido um valor padrão de 1000 (indicando um fechamento "completo da transação"). Veja a lista de status de códigos na CloseEvent página de valores permitidos.
+
reason {{optional_inline}}
+
Uma string legível para humanos que explica por que a conexão está se fechando. Esta seqüência de caracteres não deve ter mais de 123 bytes de texto UTF-8 (não caracteres).
+
+ +

Exceções lançadas

+ +
+
INVALID_ACCESS_ERR
+
Foi especificado um códigoinválido.
+
SYNTAX_ERR
+
A string reason é muito longa ou contém substitutos não comparados.
+
+ +
+

Note: No Gecko, este método não suporta nenhum parâmetro antes do Gecko 8.0 {{geckoRelease("8.0")}}.

+
+ +

send()

+ +

Transmite dados para o servidor através da conexão WebSocket.

+ +

+void send(
+  in DOMString data
+);
+
+void send(
+  in ArrayBuffer data
+);
+
+void send(
+  in Blob data
+);
+
+ +

Parametros

+ +
+
data
+
Uma sequência de texto para enviar para o servidor.
+
+ +

Exceções lançadas

+ +
+
INVALID_STATE_ERR
+
A conexão não está atualmente OPEN .
+
SYNTAX_ERR
+
Os dados são uma string que tem substituto não comparado.
+
+ +
+

Nota: A implementação do método send () de Gecko difere um pouco da especificação em {{Gecko("6.0")}}. Gecko retorna um boolean indicando se a conexão ainda está aberta (por extensão, ou os dados estão em fila ou transmitidos com sucesso). Isso é corrigido em {{Gecko("8.0")}}.

+ +

A partir de {{Gecko("11.0")}}, o suporte para {{jsxref ("ArrayBuffer")}} está implementado, mas não {{domxref("Blob")}} tipos de dados.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName("Websockets", "#the-websocket-interface", "WebSocket")}}{{Spec2("Websockets")}}Definição inicial
+ + + +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
Suporte sub-protocolo{{CompatUnknown}}{{CompatGeckoDesktop("6.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("7.0")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Suporte sub-protocolo{{CompatUnknown}}{{CompatGeckoMobile("7.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Iniciado no Gecko 6.0 {{geckoRelease("6.0")}}, o construtor está prefixado. Você precisará usar MozWebSocket() : var mySocket = new MozWebSocket("http://www.example.com/socketserver");

+ +

As extensões atribuídas não eram suportadas no Gecko até Gecko 8.0.

+ +

Antes do Gecko 11.0 {{geckoRelease("11.0")}}, as mensagens de saída enviadas usavam o método send(), eram limitadas a 16MB. Agora elas podem ter até 2GB de tamanho.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/webvr_api/index.html b/files/pt-br/web/api/webvr_api/index.html new file mode 100644 index 0000000000..3046e3f086 --- /dev/null +++ b/files/pt-br/web/api/webvr_api/index.html @@ -0,0 +1,151 @@ +--- +title: WebVR API +slug: Web/API/WebVR_API +translation_of: Web/API/WebVR_API +--- +
{{draft("The WebVR API documentation is currently being updated to cover the v1.0 spec, therefore some of this information will be out of date. Contact ~~chrisdavidmills if you have any questions about this work.")}}{{DefaultAPISidebar("WebVR API")}}{{SeeCompatTable}}
+ +

O WebVR oferece suporte para expor dispositivos de realidade virtual - por exemplo, telas montadas na cabeça, como o Oculus Rift - para aplicativos da web, permitindo que os desenvolvedores traduzam informações de posição e movimento da tela para movimento em torno de uma cena 3D. Isso tem inúmeras aplicações muito interessantes, de passeios de produtos virtuais e aplicativos de treinamento interativo para super imersivo jogos em primeira pessoa.

+ +

Conceitos e uso

+ +

Sketch of a person in a chair with wearing goggles labelled Head mounted display (HMD) facing a monitor with a webcam labelled Position sensor

+ +

Todos os dispositivos VR ligados ao computador serão devolvidos pelo {{domxref("Navigator.getVRDisplays()")}} método. Que retorna uma matriz de objetos para representar os dispositivos conectados, que herdam do objeto geral {{domxref("VRDevice")}} Geralmente o display usado na cabeça terá dois dispositivos - o próprio display montado na cabeça, representado por {{domxref("HMDVRDevice")}}, e uma câmera com sensor na posição que manterá o controle de sua posição de cabeça, representada por {{domxref("PositionSensorVRDevice")}}.

+ +

O objeto {{domxref("PositionSensorVRDevice")}} contém o método {{domxref("PositionSensorVRDevice.getState", "getState()")}}, que retorna um objeto {{domxref("VRPositionState")}} - isto representa o estado do sensor num dado carimbo de data e inclui propriedades que contêm dados úteis tais como velocidade, aceleração e orientação atuais, úteis para atualizar o processamento de uma cena em cada trama de acordo com o movimento do visor montado na cabeça VR.

+ +

O método {{domxref("HMDVRDevice.getEyeParameters()")}} retorna um objeto {{domxref("VREyeParameters")}}, que pode ser usado para retornar informações do campo de exibição - quanto da cena a tela montada na cabeça pode ver.O {{domxref("VREyeParameters.currentFieldOfView")}} retorna um objeto {{domxref("VRFieldOfView")}} que contém 4 ângulos que descrevem a vista atual a partir de um ponto central. Você também pode alterar o campo de visualização usando {{domxref("HMDVRDevice.setFieldOfView()")}}.

+ +
+

WebVR Interfaces

+ +

{{domxref("VRDisplay")}}
+ Representa qualquer dispositivo VR suportado por esta API. Ele inclui informações genéricas, como IDs de dispositivo e descrições, bem como métodos para começar a apresentar uma cena VR, recuperar os parâmetros do olho e exibir capacidades e outras funcionalidades importantes.
+ {{domxref("VRDisplayCapabilities")}}
+ Descreve os recursos de um {{domxref("VRDisplay")}} - seus recursos podem ser usados ​​para executar testes de capacidade do dispositivo VR, por exemplo, ele pode retornar informações de posição.
+ {{domxref("VRPose")}}
+ Representa o estado de posição em um dado carimbo de data/hora (que inclui orientação, posição, velocidade e aceleração).
+ {{domxref ("VREyeParameters")}}
+ Fornece acesso a todas as informações necessárias para processar corretamente uma cena para cada olho, incluindo informações de campo de visão.
+ {{domxref("VRFieldOfView")}}
+ Representa um campo de visão definido por 4 valores de graus diferentes que descrevem a vista a partir de um ponto central.
+ {{Domxref("VRLayer")}}
+ Representa uma camada a ser apresentada em {{domxref("VRDisplay")}}.
+ {{domxref("VRStageParameters")}}
+ Representa os valores que descrevem a área de estágio para dispositivos que suportam experiências em escala de sala.

+ +

Extensões para outras interfaces

+ +

{{domxref("Gamepad.displayId")}} {{readonlyInline}}
+ Retorna o {{domxref("VRDisplay.displayId")}} do associado {{domxref("VRDisplay")}} - o VRDisplay que o gamepad está controlando a cena exibida de.
+ {{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}
+ Retorna uma matriz contendo todos os objetos {{domxref("VRDisplay")}} que está sendo apresentado ({{domxref("VRDisplay.ispresenting")}}).
+ {{domxref("Navigator.getVRDisplays()")}}
+ Retorna uma promessa que resolve uma matriz de objetos {{domxref("VRDisplay")}} que representa qualquer dispositivo VR disponível conectado ao computador.
+ {{domxref("Window.onvrdisplayconnected")}}
+ Representa um manipulador de eventos que será executado quando um dispositivo VR compatível tiver sido conectado ao computador (quando o evento {{event("vrdisplayconnected")}} for acionado).
+ {{domxref("Window.onvrdisplaydisconnected")}}
+ Representa um manipulador de eventos que será executado quando um dispositivo VR compatível tiver sido desconectado do computador (quando o evento {{event("vrdisplaydisconnected")}} for acionado).
+ {{domxref("Window.onvrdisplaypresentchange")}}
+ Representa um manipulador de eventos que será executado quando o estado de apresentação de um dispositivo VR mudar - isto é, vai de apresentar a não apresentar, ou vice-versa (quando o evento {{event("onvrdisplaypresentchange")}} é acionado).

+
+ +

Examplos

+ +

Você pode encontrar uma série de exemplos nesses repositórios Github:

+ + + +

Especificações

+ + + + + + + + + + + + + + +
SpecificaçãoStatusComentario
{{SpecName('WebVR')}}{{Spec2('WebVR')}}Initial definition
+ +

Compatibilidade do Browser (navegador)

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeChromiumFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
+

Suporte Básico

+
{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for AndroidSamsung Internet for GearVR
+

Suporte Básico

+
{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/webvr_api/using_the_webvr_api/index.html b/files/pt-br/web/api/webvr_api/using_the_webvr_api/index.html new file mode 100644 index 0000000000..88c0697bdb --- /dev/null +++ b/files/pt-br/web/api/webvr_api/using_the_webvr_api/index.html @@ -0,0 +1,440 @@ +--- +title: Using the WebVR API +slug: Web/API/WebVR_API/Using_the_WebVR_API +translation_of: Web/API/WebVR_API/Using_the_WebVR_API +--- +
{{APIRef("WebVR API")}}{{deprecated_header}}
+ +
Note: WebVR API is replaced by WebXR API. WebVR was never ratified as a standard, was implemented and enabled by default in very few browsers and supported a small number of devices.
+ +

The WebVR API is a fantastic addition to the web developer's toolkit, allowing WebGL scenes to be presented in virtual reality displays such as the Oculus Rift and HTC Vive. But how do you get started with developing VR apps for the Web? This article will guide you through the basics.

+ +
+

Note: The WebVR API's most stable version — 1.1 — has recently been implemented in Firefox 55 (Windows in release version, and Mac OS X on Nightly only) and is also available in Chrome when used with Google Daydream hardware. There is also a later evolution of the spec — 2.0 — but this is at an early stage right now. You can find information on the latest state of the specs at WebVR Spec Version List.

+
+ +

Getting started

+ +

To get started, you need:

+ + + +

Once you have everything assembled, you can test to see whether your setup works with WebVR by going to our simple A-Frame demo, and seeing whether the scene renders and whether you can enter VR display mode by pressing the button at the bottom right.

+ +

A-Frame is by far the best option if you want to create a WebVR-compatible 3D scene quickly, without needing to understand a bunch of new JavaScript code. It doesn't however teach you how the raw WebVR API works, and this is what we'll get on to next.

+ +

Introducing our demo

+ +

To illustrate how the WebVR API works, we'll study our raw-webgl-example, which looks a bit like this:

+ +

+ +
+

Note: You can find the source code of our demo on GitHub, and view it live also.

+
+ +
+

Note: If WebVR isn't working in your browser, you might need to make sure it is running through your graphics card. For example for NVIDIA cards, if you've got the NVIDIA control panel set up successfully, there will be a context menu option available — right click on Firefox, then choose Run with graphics processor > High-performance NVIDIA processor.

+
+ +

Our demo features the holy grail of WebGL demos — a rotating 3D cube. We've implemented this using raw WebGL API code. We won't be teaching any basic JavaScript or WebGL, just the WebVR parts.

+ +

Our demo also features:

+ + + +

When you look through the source code of our demo's main JavaScript file, you can easily find the WebVR-specific parts by searching for the string "WebVR" in preceding comments.

+ +
+

Note: To find out more about basic JavaScript and WebGL, consult our JavaScript learning material, and our WebGL Tutorial.

+
+ +

How does it work?

+ +

At this point, let's look at how the WebVR parts of the code work.

+ +

A typical (simple) WebVR app works like this:

+ +
    +
  1. {{domxref("Navigator.getVRDisplays()")}} is used to get a reference to your VR display.
  2. +
  3. {{domxref("VRDisplay.requestPresent()")}} is used to start presenting to the VR display.
  4. +
  5. WebVR's dedicated {{domxref("VRDisplay.requestAnimationFrame()")}} method is used to run the app's rendering loop at the correct refresh rate for the display.
  6. +
  7. Inside the rendering loop, you grab the data required to display the current frame ({{domxref("VRDisplay.getFrameData()")}}), draw the displayed scene twice — once for the view in each eye — then submit the rendered view to the display to show to the user via ({{domxref("VRDisplay.submitFrame()")}}).
  8. +
+ +

In the below sections we'll look at our raw-webgl-demo in detail, and see where exactly the above features are used.

+ +

Starting with some variables

+ +

The first WebVR-related code you'll meet is this following block:

+ +
// WebVR variables
+
+var frameData = new VRFrameData();
+var vrDisplay;
+var btn = document.querySelector('.stop-start');
+var normalSceneFrame;
+var vrSceneFrame;
+
+var poseStatsBtn = document.querySelector('.pose-stats');
+var poseStatsSection = document.querySelector('section');
+poseStatsSection.style.visibility = 'hidden'; // hide it initially
+
+var posStats = document.querySelector('.pos');
+var orientStats = document.querySelector('.orient');
+var linVelStats = document.querySelector('.lin-vel');
+var linAccStats = document.querySelector('.lin-acc');
+var angVelStats = document.querySelector('.ang-vel');
+var angAccStats = document.querySelector('.ang-acc');
+var poseStatsDisplayed = false;
+ +

Let's briefly explain these:

+ + + +

Getting a reference to our VR display

+ +

One of the major functions inside our code is start() — we run this function when the body has finished loading:

+ +
// start
+//
+// Called when the body has loaded is created to get the ball rolling.
+
+document.body.onload = start;
+ +

To begin with, start() retrieves a WebGL context to use to render 3D graphics into the {{htmlelement("canvas")}} element in our HTML. We then check whether the gl context is available — if so, we run a number of functions to set up the scene for display.

+ +
function start() {
+  canvas = document.getElementById("glcanvas");
+
+  initWebGL(canvas);      // Initialize the GL context
+
+  // WebGL setup code here
+ +

Next, we start the process of actually rendering the scene onto the canvas, by setting the canvas to fill the entire browser viewport, and running the rendering loop (drawScene()) for the first time. This is the non-WebVR — normal — rendering loop.

+ +
    // draw the scene normally, without WebVR - for those who don't have it and want to see the scene in their browser
+
+    canvas.width = window.innerWidth;
+    canvas.height = window.innerHeight;
+    drawScene();
+ +

Now onto our first WebVR-specific code. First of all, we check to see if {{domxref("Navigator.getVRDisplays")}} exists — this is the entry point into the API, and therefore good basic feature detection for WebVR. You'll see at the end of the block (inside the else clause) that if this doesn't exist, we log a message to indicate that WebVR 1.1 isn't supported by the browser.

+ +
    // WebVR: Check to see if WebVR is supported
+    if(navigator.getVRDisplays) {
+      console.log('WebVR 1.1 supported');
+ +

Inside our if() { ... } block, we run the {{domxref("Navigator.getVRDisplays()")}} function. This returns a promise, which is fulfilled with an array containing all the VR display devices connected to the computer. If none are connected, the array will be empty.

+ +
      // Then get the displays attached to the computer
+      navigator.getVRDisplays().then(function(displays) {
+ +

Inside the promise then() block, we check whether the array length is more than 0; if so, we set the value of our vrDisplay variable to the 0 index item inside the array. vrDisplay now contains a {{domxref("VRDisplay")}} object representing our connected display!

+ +
        // If a display is available, use it to present the scene
+        if(displays.length > 0) {
+          vrDisplay = displays[0];
+          console.log('Display found');
+ +
+

Note: It is unlikely that you'll have multiple VR displays connected to your computer, and this is just a simple demo, so this will do for now.

+
+ +

Starting and stopping the VR presentation

+ +

Now we have a {{domxref("VRDisplay")}} object, we can use it do a number of things. The next thing we want to do is wire up functionality to start and stop presentation of the WebGL content to the display.

+ +

Continuing on with the previous code block, we now add an event listener to our start/stop button (btn) — when this button is clicked we want to check whether we are presenting to the display already (we do this in a fairly dumb fashion, by checking what the button textContent contains).

+ +

If the display is not already presenting, we use the {{domxref("VRDisplay.requestPresent()")}} method to request that the browser start presenting content to the display. This takes as a parameter an array of the {{domxref("VRLayerInit")}} objects representing the layers you want to present in the display.

+ +

Since the maximum number of layers you can display is currently 1, and the only required object member is the {{domxref("VRLayerInit.source")}} property (which is a reference to the {{htmlelement("canvas")}} you want to present in that layer; the other parameters are given sensible defaults — see {{domxref("VRLayerInit.leftBounds", "leftBounds")}} and {{domxref("VRLayerInit.rightBounds", "rightBounds")}})), the parameter is simply [{ source: canvas }].

+ +

requestPresent() returns a promise that is fulfilled when the presentation begins successfully.

+ +
          // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
+          btn.addEventListener('click', function() {
+            if(btn.textContent === 'Start VR display') {
+              vrDisplay.requestPresent([{ source: canvas }]).then(function() {
+                console.log('Presenting to WebVR display');
+ +

With our presentation request successful, we now want to start setting up to render content to present to the VRDisplay. First of all we set the canvas to the same size as the VR display area. We do this by getting the {{domxref("VREyeParameters")}} for both eyes using {{domxref("VRDisplay.getEyeParameters()")}}.

+ +

We then do some simple math to calculate the total width of the VRDisplay rendering area based on the eye {{domxref("VREyeParameters.renderWidth")}} and {{domxref("VREyeParameters.renderHeight")}}.

+ +
                // Set the canvas size to the size of the vrDisplay viewport
+
+                var leftEye = vrDisplay.getEyeParameters('left');
+                var rightEye = vrDisplay.getEyeParameters('right');
+
+                canvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2;
+                canvas.height = Math.max(leftEye.renderHeight, rightEye.renderHeight);
+ +

Next, we {{domxref("Window.cancelAnimationFrame()", "cancel the animation loop")}} previously set in motion by the {{domxref("Window.requestAnimationFrame()")}} call inside the drawScene() function, and instead invoke drawVRScene(). This function renders the same scene as before, but with some special WebVR magic going on. The loop inside here is maintained by WebVR's special {{domxref("VRDisplay.requestAnimationFrame")}} method.

+ +
                // stop the normal presentation, and start the vr presentation
+                window.cancelAnimationFrame(normalSceneFrame);
+                drawVRScene();
+ +

Finally, we update the button text so that the next time it is pressed, it will stop presentation to the VR display.

+ +
                btn.textContent = 'Exit VR display';
+              });
+ +


+ To stop the VR presentation when the button is subsequently pressed, we call {{domxref("VRDisplay.exitPresent()")}}. We also reverse the button's text content, and swap over the requestAnimationFrame calls. You can see here that we are using {{domxref("VRDisplay.cancelAnimationFrame")}} to stop the VR rendering loop, and starting the normal rendering loop off again by calling drawScene().

+ +
            } else {
+              vrDisplay.exitPresent();
+              console.log('Stopped presenting to WebVR display');
+
+              btn.textContent = 'Start VR display';
+
+              // Stop the VR presentation, and start the normal presentation
+              vrDisplay.cancelAnimationFrame(vrSceneFrame);
+              drawScene();
+            }
+          });
+        }
+      });
+    } else {
+      console.log('WebVR API not supported by this browser.');
+    }
+  }
+}
+ +

Once the presentation starts, you'll be able to see the stereoscopic view displayed in the browser:

+ +

+ +

You'll learn below how the stereoscopic view is actually produced.

+ +

Why does WebVR have its own requestAnimationFrame()?

+ +

This is a good question. The reason is that for smooth rendering inside the VR display, you need to render the content at the display's native refresh rate, not that of the computer. VR display refresh rates are greater than PC refresh rates, typically up to 90fps. The rate will be differ from the computer's core refresh rate.

+ +

Note that when the VR display is not presenting, {{domxref("VRDisplay.requestAnimationFrame")}} runs identically to {{domxref("Window.requestAnimationFrame")}}, so if you wanted, you could just use a single rendering loop, rather than the two we are using in our app. We have used two because we wanted to do slightly different things depending on whether the VR display is presenting or not, and keep things separated for ease of comprehension.

+ +

Rendering and display

+ +

At this point, we've seen all the code required to access the VR hardware, request that we present our scene to the hardware, and start running the rending loop. Let's now look at the code for the rendering loop, and explain how the WebVR-specific parts of it work.

+ +

First of all, we begin the definition of our rendering loop function — drawVRScene(). The first thing we do inside here is make a call to {{domxref("VRDisplay.requestAnimationFrame()")}} to keep the loop running after it has been called once (this occurred earlier on in our code when we started presenting to the VR display). This call is set as the value of the global vrSceneFrame variable, so we can cancel the loop with a call to {{domxref("VRDisplay.cancelAnimationFrame()")}} once we exit VR presenting.

+ +
function drawVRScene() {
+  // WebVR: Request the next frame of the animation
+  vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);
+ +

Next, we call {{domxref("VRDisplay.getFrameData()")}}, passing it the name of the variable that we want to use to contain the frame data. We initialized this earlier on — frameData. After the call completes, this variable will contain the data need to render the next frame to the VR device, packaged up as a {{domxref("VRFrameData")}} object. This contains things like projection and view matrices for rendering the scene correctly for the left and right eye view, and the current {{domxref("VRPose")}} object, which contains data on the VR display such as orientation, position, etc.

+ +

This has to be called on every frame so the rendered view is always up-to-date.

+ +
  // Populate frameData with the data of the next frame to display
+  vrDisplay.getFrameData(frameData);
+ +

Now we retrieve the current {{domxref("VRPose")}} from the {{domxref("VRFrameData.pose")}} property, store the position and orientation for use later on, and send the current pose to the pose stats box for display, if the poseStatsDisplayed variable is set to true.

+ +
  // You can get the position, orientation, etc. of the display from the current frame's pose
+
+  var curFramePose = frameData.pose;
+  var curPos = curFramePose.position;
+  var curOrient = curFramePose.orientation;
+  if(poseStatsDisplayed) {
+    displayPoseStats(curFramePose);
+  }
+ +

  We now clear the canvas before we start drawing on it, so that the next frame is clearly seen, and we don't also see previous rendered frames:

+ +
  // Clear the canvas before we start drawing on it.
+
+  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+ +

We now render the view for both the left and right eyes. First of all we need to create projection and view locations for use in the rendering. these are {{domxref("WebGLUniformLocation")}} objects, created using the {{domxref("WebGLRenderingContext.getUniformLocation()")}} method, passing it the shader program's identifier and an identifying name as parameters.

+ +
  // WebVR: Create the required projection and view matrix locations needed
+  // for passing into the uniformMatrix4fv methods below
+
+  var projectionMatrixLocation = gl.getUniformLocation(shaderProgram, "projMatrix");
+  var viewMatrixLocation = gl.getUniformLocation(shaderProgram, "viewMatrix");
+ +

The next rendering step involves:

+ + + +
  // WebVR: Render the left eye’s view to the left half of the canvas
+  gl.viewport(0, 0, canvas.width * 0.5, canvas.height);
+  gl.uniformMatrix4fv(projectionMatrixLocation, false, frameData.leftProjectionMatrix);
+  gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.leftViewMatrix);
+  drawGeometry();
+ +

We now do exactly the same thing, but for the right eye:

+ +
  // WebVR: Render the right eye’s view to the right half of the canvas
+  gl.viewport(canvas.width * 0.5, 0, canvas.width * 0.5, canvas.height);
+  gl.uniformMatrix4fv(projectionMatrixLocation, false, frameData.rightProjectionMatrix);
+  gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.rightViewMatrix);
+  drawGeometry();
+ +

Next we define our drawGeometry() function. Most of this is just general WebGL code required to draw our 3D cube. You'll see some WebVR-specific parts in the mvTranslate() and mvRotate() function calls — these pass matrices into the WebGL program that define the translation and rotation of the cube for the current frame

+ +

You'll see that we are modifying these values by the position (curPos) and orientation (curOrient) of the VR display we got from the {{domxref("VRPose")}} object. The result is that, for example, as you move or rotate your head left, the x position value (curPos[0]) and y rotation value ([curOrient[1]) are added to the x translation value, meaning that the cube will move to the right, as you'd expect when you are looking at something and then move/turn your head left.

+ +

This is a quick and dirty way to use VR pose data, but it illustrates the basic principle.

+ +
  function drawGeometry() {
+    // Establish the perspective with which we want to view the
+    // scene. Our field of view is 45 degrees, with a width/height
+    // ratio of 640:480, and we only want to see objects between 0.1 units
+    // and 100 units away from the camera.
+
+    perspectiveMatrix = makePerspective(45, 640.0/480.0, 0.1, 100.0);
+
+    // Set the drawing position to the "identity" point, which is
+    // the center of the scene.
+
+    loadIdentity();
+
+    // Now move the drawing position a bit to where we want to start
+    // drawing the cube.
+
+    mvTranslate([
+                  0.0 - (curPos[0] * 25) + (curOrient[1] * 25),
+                  5.0 - (curPos[1] * 25) - (curOrient[0] * 25),
+                  -15.0 - (curPos[2] * 25)
+               ]);
+
+    // Save the current matrix, then rotate before we draw.
+
+    mvPushMatrix();
+    mvRotate(cubeRotation, [0.25, 0, 0.25 - curOrient[2] * 0.5]);
+
+    // Draw the cube by binding the array buffer to the cube's vertices
+    // array, setting attributes, and pushing it to GL.
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesBuffer);
+    gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
+
+    // Set the texture coordinates attribute for the vertices.
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesTextureCoordBuffer);
+    gl.vertexAttribPointer(textureCoordAttribute, 2, gl.FLOAT, false, 0, 0);
+
+    // Specify the texture to map onto the faces.
+
+    gl.activeTexture(gl.TEXTURE0);
+    gl.bindTexture(gl.TEXTURE_2D, cubeTexture);
+    gl.uniform1i(gl.getUniformLocation(shaderProgram, "uSampler"), 0);
+
+    // Draw the cube.
+
+    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);
+    setMatrixUniforms();
+    gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);
+
+    // Restore the original matrix
+
+    mvPopMatrix();
+  }
+
+ +

The next bit of the code has nothing to do with WebVR — it just updates the rotation of the cube on each frame:

+ +
  // Update the rotation for the next draw, if it's time to do so.
+
+  var currentTime = (new Date).getTime();
+  if (lastCubeUpdateTime) {
+    var delta = currentTime - lastCubeUpdateTime;
+
+    cubeRotation += (30 * delta) / 1000.0;
+  }
+
+  lastCubeUpdateTime = currentTime;
+ +

The last part of the rendering loop involves us calling {{domxref("VRDisplay.submitFrame()")}} — now all the work has been done and we've rendered the display on the {{htmlelement("canvas")}}, this method then submits the frame to the VR display so it is displayed on there as well.

+ +
  // WebVR: Indicate that we are ready to present the rendered frame to the VR display
+  vrDisplay.submitFrame();
+}
+ +

Displaying the pose (position, orientation, etc.) data

+ +

In this section we'll discuss the displayPoseStats() function, which displays our updated pose data on each frame. The function is fairly simple.

+ +

First of all, we store the six different property values obtainable from the {{domxref("VRPose")}} object in their own variables — each one is a {{domxref("Float32Array")}}.

+ +
function displayPoseStats(pose) {
+  var pos = pose.position;
+  var orient = pose.orientation;
+  var linVel = pose.linearVelocity;
+  var linAcc = pose.linearAcceleration;
+  var angVel = pose.angularVelocity;
+  var angAcc = pose.angularAcceleration;
+ +

We then write out the data into the information box, updating it on every frame. We've clamped each value to three decimal places using toFixed(), as the values are hard to read otherwise.

+ +

You should note that we've used a conditional expression to detect whether the linear acceleration and angular acceleration arrays are successfully returned before we display the data. These values are not reported by most VR hardware as yet, so the code would throw an error if we did not do this (the arrays return null if they are not successfully reported).

+ +
  posStats.textContent = 'Position: x ' + pos[0].toFixed(3) + ', y ' + pos[1].toFixed(3) + ', z ' + pos[2].toFixed(3);
+  orientStats.textContent = 'Orientation: x ' + orient[0].toFixed(3) + ', y ' + orient[1].toFixed(3) + ', z ' + orient[2].toFixed(3);
+  linVelStats.textContent = 'Linear velocity: x ' + linVel[0].toFixed(3) + ', y ' + linVel[1].toFixed(3) + ', z ' + linVel[2].toFixed(3);
+  angVelStats.textContent = 'Angular velocity: x ' + angVel[0].toFixed(3) + ', y ' + angVel[1].toFixed(3) + ', z ' + angVel[2].toFixed(3);
+
+  if(linAcc) {
+    linAccStats.textContent = 'Linear acceleration: x ' + linAcc[0].toFixed(3) + ', y ' + linAcc[1].toFixed(3) + ', z ' + linAcc[2].toFixed(3);
+  } else {
+    linAccStats.textContent = 'Linear acceleration not reported';
+  }
+
+  if(angAcc) {
+    angAccStats.textContent = 'Angular acceleration: x ' + angAcc[0].toFixed(3) + ', y ' + angAcc[1].toFixed(3) + ', z ' + angAcc[2].toFixed(3);
+  } else {
+    angAccStats.textContent = 'Angular acceleration not reported';
+  }
+}
+ +

WebVR events

+ +

The WebVR spec features a number of events that are fired, allowing our app code to react to changes in the state of the VR display (see Window events). For example:

+ + + +

To demonstrate how they work, our simple demo includes the following example:

+ +
window.addEventListener('vrdisplaypresentchange', function(e) {
+  console.log('Display ' + e.display.displayId + ' presentation has changed. Reason given: ' + e.reason + '.');
+});
+ +

As you can see, the {{domxref("VRDisplayEvent", "event object")}} provides two useful properties — {{domxref("VRDisplayEvent.display")}}, which contains a reference to the {{domxref("VRDisplay")}} the event was fired in response to, and {{domxref("VRDisplayEvent.reason")}}, which contains a human-readable reason why the event was fired.

+ +

This is a very useful event; you could use it to handle cases where the display gets disconnected unexpectedly, stopping errors from being thrown and making sure the user is aware of the situation. In Google's Webvr.info presentation demo, the event is used to run an onVRPresentChange() function, which updates the UI controls as appropriate and resizes the canvas.

+ +

Summary

+ +

This article has given you the very basics of how to create a simple WebVR 1.1 app, to help you get started.

diff --git a/files/pt-br/web/api/window/alert/index.html b/files/pt-br/web/api/window/alert/index.html new file mode 100644 index 0000000000..028eba5e6c --- /dev/null +++ b/files/pt-br/web/api/window/alert/index.html @@ -0,0 +1,47 @@ +--- +title: Window.alert +slug: Web/API/Window/alert +translation_of: Web/API/Window/alert +--- +

{{ APIRef }}

+ +

O método Window.alert() mostra uma caixa de diálogo de aviso com o conteúdo opcionalmente especificado e um botão OK.

+ +

Sintaxe

+ +
window.alert(message);
+ + + +

Exemplo

+ +
window.alert("Hello world!");
+
+ +

resulta em:

+ +

Image:AlertHelloWorld.png

+ +

Notas

+ +

A caixa de diálogo de aviso deve ser utilizada para mensagens que não requeiram nenhuma resposta da parte do usuário, a não ser o reconhecimento da mensagem.

+ +

The following text is shared between this article, DOM:window.prompt and DOM:window.confirmCaixas de diálogo são janelas modais - elas evitam que o usuário acesse o resto da interface do programa sem ter fechado a caixa de diálogo. Por essa razão, você não deve utilizar excessivamente nenhuma função que crie caixas de diálogo (ou janelas modais).

+ +

Usuários do Chrome (por exemplo, em extensões) devem utilizar os métodos da interface {{interface("nsIPromptService")}} como alternativa.

+ +

{{gecko_minversion_inline("23.0")}} O argumento agora é opcional conforme exigido na especificação.

+ +

Especificação

+ +

Especificado no HTML5.

+ +

Ver também

+ + diff --git a/files/pt-br/web/api/window/applicationcache/index.html b/files/pt-br/web/api/window/applicationcache/index.html new file mode 100644 index 0000000000..d4210a0543 --- /dev/null +++ b/files/pt-br/web/api/window/applicationcache/index.html @@ -0,0 +1,33 @@ +--- +title: Window.applicationCache +slug: Web/API/Window/applicationCache +translation_of: Web/API/Window/applicationCache +--- +

{{APIRef}}

+ +

Sumário

+ +

Returna uma referência para o objeto de cache da janela.

+ +

Sintaxe

+ +
cache = window.applicationCache
+
+ +

Parâmetros

+ + + +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/window/closed/index.html b/files/pt-br/web/api/window/closed/index.html new file mode 100644 index 0000000000..a7f65aff5f --- /dev/null +++ b/files/pt-br/web/api/window/closed/index.html @@ -0,0 +1,59 @@ +--- +title: Window.closed +slug: Web/API/Window/closed +translation_of: Web/API/Window/closed +--- +
{{APIRef}}
+ +

Sumário

+ +

Essa propriedade (read-only) indica se a janela referenciada está ou não fechada.

+ +

Sintaxe

+ +
isClosed = windowRef.closed;
+
+ +
+
isClosed
+
Um booleano. Valores possíveis: +
    +
  • true: A janela foi fechada.
  • +
  • false: A janela está aberta.
  • +
+
+
+ +

Exemplos

+ +

Mudar a URL de uma janela a partir de um popup

+ +

O seguinte exemplo demonstra com uma janela de popup pode alterar a URL da janela que abriu ela. Antes de tentarmos mudar a URL da janela que a abriu, verificamos se a janela atual tem uma janela pai que a abriu usando a propriedade window.opener e que esta não está fechada:

+ +
// Verifique se o opener existe e não está fechado
+if (window.opener && !window.opener.closed) {
+  window.opener.location.href = "http://www.mozilla.org";
+}
+ +

Note que popups podem somente acessar a janela que os abriu.

+ +

Atualizando um popup anteriormente aberto

+ +

Neste exemplo, a função refreshPopupWindow() chama o método reload do objeto location do popup para atualizar seus dados. Se o popup não foi aberto ainda ou o usuário o fechou,  uma nova janela é aberta.

+ +
var popupWindow = null;
+
+function refreshPopupWindow() {
+  if (popupWindow && !popupWindow.closed) {
+    // popupWindow está aberto, atualize-o
+    popupWindow.location.reload(true);
+  } else {
+    // Abra uma nova janela de popup
+    popupWindow = window.open("popup.html","dataWindow");
+  }
+}
+
+ +

Especificação

+ +

HTML5

diff --git a/files/pt-br/web/api/window/confirm/index.html b/files/pt-br/web/api/window/confirm/index.html new file mode 100644 index 0000000000..e3ced2de5a --- /dev/null +++ b/files/pt-br/web/api/window/confirm/index.html @@ -0,0 +1,49 @@ +--- +title: Window.confirm() +slug: Web/API/Window/confirm +translation_of: Web/API/Window/confirm +--- +
{{ApiRef("Window")}}
+ +

O método Window.confirm() mostra uma janela modal com uma mensagem opcional e dois botões, OK e Cancelar.

+ +

Sintaxe

+ +
resultado = window.confirm(mensagem);
+
+ + + +

Exemplo

+ +
if (window.confirm("Você realmente quer sair?")) {
+  window.open("sair.html", "Obrigado pela visita!");
+}
+
+ +

Produzirá:

+ +

firefox confirm
+  

+ +

Notas

+ +

The following text is shared between this article, DOM:window.prompt and DOM:window.alert Caixas de diálogo são janelas modais - elas previnem o usuário de acessar o resto da interface da aplicação enquanto a caixa de diálogo não for fechada. Por esta razão, você não deve usar abusivamente nenhuma função que crie uma caixa de diálogo (ou uma janela modal). E independente disso, existem boas razões para evitar o uso de caixas de diálogo para confirmações.

+ +

Usuários do Mozilla Chrome (Ex.: Extensões do Firefox) devem utilizar métodos de {{interface("nsIPromptService")}}.

+ +

{{gecko_minversion_inline("23.0")}}O argumento é opcional e não é requerido por especificações.

+ +

Especificação

+ +

Especificado em HTML5.

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/window/crypto/index.html b/files/pt-br/web/api/window/crypto/index.html new file mode 100644 index 0000000000..d303c9dd74 --- /dev/null +++ b/files/pt-br/web/api/window/crypto/index.html @@ -0,0 +1,128 @@ +--- +title: Window.crypto +slug: Web/API/Window/crypto +tags: + - API + - HTML DOM + - Janela + - NeedsCompatTable + - Propriedade + - Referencia + - Window +translation_of: Web/API/Window/crypto +--- +
{{APIRef}}
+ +

{{domxref("Window.crypto")}} propriedade somente de leitura, devolve um objeto do tipo {{domxref("Crypto")}} associado ao objeto global. Este objeto permite que páginas da web utilizem recursos de criptografia.

+ +

Sintaxe

+ +
var cryptoObj = window.crypto || window.msCrypto; // for IE 11
+
+ +

Exemplo

+ +

Usando a propriedade {{domxref("Window.crypto")}}  para acessar o método getRandomValues().

+ +

JavaScript

+ +
genRandomNumbers = function getRandomNumbers() {
+  var array = new Uint32Array(10);
+  window.crypto.getRandomValues(array);
+
+  var randText = document.getElementById("myRandText");
+  randText.innerHTML = "The random numbers are: "
+  for (var i = 0; i < array.length; i++) {
+    randText.innerHTML += array[i] + " ";
+  }
+}
+ +

HTML

+ +
<p id="myRandText">The random numbers are: </p>
+<button type="button" onClick='genRandomNumbers()'>Generate 10 random numbers</button>
+ +

Resultado

+ +

{{ EmbedLiveSample('Example') }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Web Crypto API", "#dfn-GlobalCrypto", "Window.crypto")}}{{Spec2("Web Crypto API")}}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Suporte básico44 {{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}11 {{property_prefix("ms")}}2019{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChrome for AndroidEdgeFirefox MobileFirefox OSIE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/document/index.html b/files/pt-br/web/api/window/document/index.html new file mode 100644 index 0000000000..f7cfc4d860 --- /dev/null +++ b/files/pt-br/web/api/window/document/index.html @@ -0,0 +1,56 @@ +--- +title: Window.document +slug: Web/API/Window/document +tags: + - API + - DOM HTML + - NeedsCompatTable + - NeedsExample + - NeedsMarkupWork + - NeedsSpecTable + - Propriedade + - Referencia + - Window +translation_of: Web/API/Window/document +--- +
{{APIRef}}
+ +

Resumo

+ +

Retorna a referência para o documento contido na janela.

+ +
Nota: {{Fx_minversion_inline(3)}} Firefox 3 altera a segurança para documentos de uma janela de modo que apenas o domínio a partir do qual foi localizado possa acessar o documento. Enquanto isso pode quebrar alguns sites existentes, é um movimento feito por ambos Firefox 3 e Internet Explorer 7, e resulta na melhoria de segurança.
+ +

Sintaxe

+ +
doc = window.document
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+   <title>Hello, World!</title>
+</head>
+<body>
+
+<script type="text/javascript">
+   var doc = window.document;
+   alert( doc.title);    // alerts: Hello, World!
+</script>
+
+</body>
+</html>
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/window/event/index.html b/files/pt-br/web/api/window/event/index.html new file mode 100644 index 0000000000..49452c20de --- /dev/null +++ b/files/pt-br/web/api/window/event/index.html @@ -0,0 +1,72 @@ +--- +title: Window.event +slug: Web/API/Window/event +translation_of: Web/API/Window/event +--- +

{{APIRef}}

+ +

{{ Non-standard_header() }}

+ +

window.event é uma propriedade proprietária do Microsoft Internet Explorer que só está disponível enquanto um manipulador de eventos DOM é chamado. Seu valor é o objeto Event atualmente tratado.

+ +

Especificações

+ +

Não é parte de nenhuma especificação.

+ +

Microsoft tem uma descrição na MSDN.

+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/fullscreen/index.html b/files/pt-br/web/api/window/fullscreen/index.html new file mode 100644 index 0000000000..666b763bf5 --- /dev/null +++ b/files/pt-br/web/api/window/fullscreen/index.html @@ -0,0 +1,44 @@ +--- +title: Window.fullScreen +slug: Web/API/Window/fullScreen +translation_of: Web/API/Window/fullScreen +--- +
{{APIRef}}
+ +

Sumário

+ +

Esta propriedade indica se a janela está sendo exibida em modo de tela cheia ("full screen") ou não. Ela é confiável apenas no Gecko 1.9 (Firefox 3) e posteriores, veja as  Notas abaixo.

+ +

Sintaxe

+ +
isInFullScreen = windowRef.fullScreen;
+
+ +

Com "chrome privileges" (privilégios para acesso a funções de baixo nível), a propriedade é de leitura e escrita, caso contrário é de apenas leitura. Tenha em mente que se você tentar definir esta propriedade sem chrome privileges, isto não irá gerar uma excessão; ao invés disto, irá simples e silenciosamente falhar. Isto é para prevenir que scripts projetados para definir esta propriedade no Internet Explorer se quebrem.

+ +

Valor de Retorno

+ +
+
isInFullScreen
+
Um booleano. Valores possíveis:
+
+ + + +

Exemplos

+ +

{{todo}}

+ +

Especificação

+ +

DOM Level 0. window.fullScreen não é parte de nenhuma especificação do W3C ou recomendação técnica.

+ +

Notas

+ + diff --git a/files/pt-br/web/api/window/getselection/index.html b/files/pt-br/web/api/window/getselection/index.html new file mode 100644 index 0000000000..7afcb23ef6 --- /dev/null +++ b/files/pt-br/web/api/window/getselection/index.html @@ -0,0 +1,129 @@ +--- +title: Window.getSelection() +slug: Web/API/Window/getSelection +translation_of: Web/API/Window/getSelection +--- +
{{ ApiRef() }}
+ +

Resumo

+ +

Retorna um objeto {{domxref("Selection")}} representando a parte do texto selecionada pelo usuário ou a posição atual do cursor.

+ +

Syntax

+ +
selection = window.getSelection();
+ + + +

Example

+ +
function foo() {
+    var selObj = window.getSelection();
+    alert(selObj);
+    var selRange = selObj.getRangeAt(0);
+    // do stuff with the range
+}
+ +

Nota

+ +

Representação do objeto Selection em String

+ +

No  JavaScript, quando um objeto é passado para uma função que espera uma string (como {{ Domxref("window.alert()") }} ou {{ Domxref("document.write()") }}), o método {{jsxref("Object.toString", "toString()")}} do objeto é chamado e o valor retornado é passado para a função. Isso pode fazer com que o objeto pareça ser uma string quando usado com outras funções quando na verdade é um objeto com propriedades e métodos.

+ +

No exemplo acima, selObj.toString() é chamado automaticamente quando é passado para {{domxref("window.alert()")}}. Contudo,  tentar usar propriedades ou métodos do objeto JavaScript String como length ou substr diretamente no objeto {{domxref("Selection")}} resultará em erro se o objeto não possuir essa propriedade ou método e pode retornar valores inesperados mesmo se os tiver. Para usar um objecto Selection como uma string, faça a chamada do seu método toString() diretamente:

+ +
var selectedText = selObj.toString();
+ + + +

Objectos Relacionados

+ +

É útil também notar que você pode chamar {{domxref("Document.getSelection()")}},  que funciona de forma idêntica.

+ +

Inputs HTML provêm APIs mais simples para se trabalhar com seleções (veja {{domxref("HTMLInputElement.setSelectionRange()")}}).

+ +

Note a diferença entre selection e focus. {{domxref("Document.activeElement")}} retorna o elemento com foco.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("HTML Editing", "#dom-window-getselection", "Window.getSelection()")}}{{Spec2("HTML Editing")}}Definição inicial
+ +

Compatibilidade dos Browsers

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}9{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/history/index.html b/files/pt-br/web/api/window/history/index.html new file mode 100644 index 0000000000..cc96ab5be5 --- /dev/null +++ b/files/pt-br/web/api/window/history/index.html @@ -0,0 +1,52 @@ +--- +title: Window.history +slug: Web/API/Window/history +translation_of: Web/API/Window/history +--- +

{{ APIRef }}

+ +

A propriedade só de leitura Window.history retorna uma referência ao objeto History, que fornece uma interface para manipular o histórico de sessão do navegador (páginas visitadas na guia ou quadro em que a página atual é carregada).

+ +

Consulte Manipulação do histórico do navegador para obter exemplos e detalhes. Em particular, esse artigo explica os recursos de segurança dos métodos pushState () e replaceState () que você deve conhecer antes de usá-los.

+ +

Syntax

+ +
var historyObj = window.history;
+
+ +

Example

+ +
History.back (); // equivalente ao clique no botão Voltar
+History.go (-1); // equivalente a history.back ();
+
+ +

Notas

+ +


+ Para páginas de nível superior, você pode ver a lista de páginas no histórico da sessão, acessível através do objeto Histórico, nos menus suspensos do navegador ao lado dos botões para trás e para frente.

+ +

Por motivos de segurança, o objeto Histórico não permite que o código não privilegiado acesse os URLs de outras páginas no histórico da sessão, mas permite que ele navegue pelo histórico da sessão.

+ +

Não há nenhuma maneira de limpar o histórico da sessão ou desabilitar a navegação para trás / para frente do código não privilegiado. A solução disponível mais próxima é o método location.replace (), que substitui o item atual do histórico da sessão pelo URL fornecido.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('HTML WHATWG', 'browsers.html#the-history-interface', 'The History interface')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#the-history-interface', 'The History interface')}}{{Spec2('HTML5 W3C')}} 
diff --git a/files/pt-br/web/api/window/index.html b/files/pt-br/web/api/window/index.html new file mode 100644 index 0000000000..45b7ce7759 --- /dev/null +++ b/files/pt-br/web/api/window/index.html @@ -0,0 +1,381 @@ +--- +title: Window +slug: Web/API/Window +translation_of: Web/API/Window +--- +

{{APIRef}}

+ +

O objeto window representa uma janela que contém um elemento DOM; a propriedade document aponta para o documento DOM document carregado naquela janela. Uma janela para um dado documento pode ser obtido usando a propriedade {{Domxref("document.defaultView")}}.

+ +

Esta seção provê uma breve referência a todos os métodos, propriedades e eventos disponíveis através do objeto DOM window. O objeto window implementa a interface Window, o qual herda da interface AbstractView. Algumas funções globais, objeto de namespace, interfaces e construtores, apesar de não tipicamente associados ao objeto em questão, estão disponíveis e estão listados nas referências JavaScript Reference e DOM Reference.

+ +

Em um navegador com suporte a abas, como o Firefox, cada aba contém seu próprio objeto window (e, se você estiver escrevendo uma extensão, a janela do navegador é uma janela distinta também - veja Working with windows in chrome code para mais informação). Isto é, o objeto window não é compartilhado entre as abas na mesma janela. Alguns métodos, nomeadamente {{Domxref("window.resizeTo")}} e {{Domxref("window.resizeBy")}} aplicam-se à janela toda e não à aba em questão ao que o objeto window pertence. Geralmente, qualquer coisa que não pode racionalmente pertencer a uma aba, pertence a uma janela..

+ +

Propriedades

+ +

Esta interface herda propriedades da interface {{domxref("EventTarget")}} e implementa propriedades de {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, e {{domxref("WindowEventHandlers")}}.

+ +

Perceba que propriedades que são objetos (ex.: sobrecarregar o protótipo de elementos built-in) são listados em uma sessão separada abaixo.

+ +
+
{{domxref("Window.applicationCache")}}  {{readOnlyInline}} {{gecko_minversion_inline("1.9")}}
+
Um objeto {{domxref("OfflineResourceList")}} fornece acesso aos recursos offline para o window.
+
{{domxref("Window.closed")}} {{Non-standard_inline}}{{readOnlyInline}}
+
Esta propriedade indica quando a window atual está fechada ou não.
+
Window.Components {{Non-standard_inline}}
+
O ponto de entrada para muitas características XPCOM. Algumas propriedades, por exemplo, classes, estão apenas disponíveis para código suficientemente privilegiado. Código de Web não deve usar essa propriedade.
+
{{domxref("console","Window.console")}} {{Non-standard_inline}} {{ReadOnlyInline}}
+
Retorna uma referência para o objeto console fornecendo acesso ao console debugging do navegador.
+
{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}}{{ReadOnlyInline}}
+
Retorna uma referência para o elemento de conteúdo na janela atual. A variante obsoleta com sublinhado não está disponível a partir do conteúdo da Web.
+
{{domxref("Window.controllers")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
Retorna os objetos de controlador XUL para a janela atual do crome.
+
{{domxref("Window.crypto")}} {{readOnlyInline}}
+
Retorna o objeto de criptografia do navegador.
+
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
+
Obtém/define o texto da barra de status para determinada janela.
+
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}}{{ReadOnlyInline}}
+
Returns the ratio between physical pixels and device independent pixels in the current display.
+
{{domxref("Window.dialogArguments")}} {{Fx_minversion_inline(3)}} {{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}}
+
Retorna a referência à propriedade document que a janela contém.
+
{{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}}
+
Retorna a referência ao objeto history.
+
{{domxref("Window.innerHeight")}}
+
Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.
+
{{domxref("window.innerWidth")}}
+
Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.
+
{{domxref("Window.length")}} {{readOnlyInline}}
+
Returns the number of frames in the window. See also {{domxref("window.frames")}}.
+
{{domxref("Window.location")}} {{ReadOnlyInline}}
+
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("WindowStorage.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")}}
+
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")}}
+
Pega/attribui o nome ao objeto 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.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("WindowSession.sessionStorage")}} {{readOnlyInline}}
+
+
{{domxref("SpeechSynthesisGetter.speechSynthesis")}} {{readOnlyInline}}
+
+
{{domxref("Window.parent")}} {{readOnlyInline}}
+
Returns a reference to the parent of the current window or subframe.
+
{{domxref("Window.performance")}} {{readOnlyInline}}
+
Provides a hosting area for performance related attributes.
+
{{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")}} {{Fx_minversion_inline(3)}}
+
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")}} {{Fx_minversion_inline("2.0")}}
+
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.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.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.
+
+ +

Methods

+ +

This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, and {{domxref("WindowEventHandlers")}}.

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
Register an event handler to a specific event type on the window.
+
{{domxref("Window.alert()")}}
+
Displays an alert dialog.
+
{{domxref("WindowBase64.atob()")}}
+
Decodes a string of data which has been encoded using base-64 encoding.
+
{{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("WindowBase64.btoa()")}}
+
Creates a base-64 encoded ASCII string from a string of binary data.
+
{{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("WindowTimers.clearInterval()")}}
+
Cancels the repeated execution set using {{domxref("WindowTimers.setInterval()")}}.
+
{{domxref("WindowTimers.clearTimeout()")}}
+
Cancels the repeated execution set using {{domxref("WindowTimers.setTimeout()")}}.
+
{{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()")}}
+
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()")}}
+
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.getDefaulComputedStyle()")}}
+
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.mozRequestAnimationFrame()")}} {{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. This will cause a MozBeforePaint event to fire before that repaint occurs.
+
{{domxref("Window.open()")}}
+
Opens a new window.
+
{{domxref("Window.openDialog()")}}
+
Opens a new dialog window.
+
{{domxref("Window.postMessage()")}} {{Fx_minversion_inline(3)}}
+
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, in a secure manner.
+
{{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()")}} {{Deprecated_inline}}
+
Releases the window from trapping events of a specific type.
+
{{domxref("element.removeEventListener","Window.removeEventListener()")}}
+
Removes an event listener from the window.
+
{{domxref("Window.resizeBy()")}}
+
Resizes the current window by a certain amount.
+
{{domxref("Window.resizeTo()")}}
+
Dynamically resizes window.
+
{{domxref("Window.restore()")}}
+
{{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()")}}
+
Scrolls the document by the given number of lines.
+
{{domxref("Window.scrollByPages()")}}
+
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()")}}
+
Changes the cursor for the current window
+
{{domxref("Window.setImmediate()")}}
+
Executes a function after the browser has finished other heavy tasks
+
{{domxref("WindowTimers.setInterval()")}}
+
Schedules the execution of a function each X milliseconds.
+
{{domxref("Window.setResizable")}}
+
{{todo("NeedsContents")}}
+
{{domxref("WindowTimers.setTimeout()")}}
+
Sets a delay for executing a function.
+
{{domxref("Window.showModalDialog()")}} {{Fx_minversion_inline(3)}}
+
Displays a modal dialog.
+
{{domxref("Window.sizeToContent()")}}
+
Sizes the window according to its content.
+
{{domxref("Window.stop()")}}
+
This method stops window loading.
+
{{domxref("Window.updateCommands()")}}
+
Updates the state of commands of the current chrome window (UI).
+
+ +

Event handlers

+ +

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("WindowTimers")}}, {{domxref("WindowBase64")}}, and {{domxref("WindowEventHandlers")}}.

+ +
+

Note: 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")}}
+
An event handler property for abort events on the window.
+
{{domxref("WindowEventHandlers.onbeforeunload")}}
+
An event handler property for before-unload events on the window.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
An event handler property for blur events on the window.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
An event handler property for change events on the window.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
An event handler property for click events on the window.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
An event handler property for handling the window close event.
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
An event handler property for right-click events on the window.
+
{{domxref("Window.ondevicelight")}}
+
An event handler property for any ambient light levels changes
+
{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}
+
An event handler property for any device orientation changes
+
{{domxref("Window.ondeviceproximity")}}
+
An event handler property for device proximity event
+
{{domxref("GlobalEventHandlers.onerror")}}
+
An event handler property for {{event("error")}} events raised on the window.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
An event handler property for {{event("focus")}} events on the window.
+
{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}
+
An event handler property for hash change events on the window; called when the part of the URL after the hash mark ("#") changes.
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
An event handler property for {{event("keydown")}} events on the window.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
An event handler property for {{event("keypress")}} events on the window.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
An event handler property for {{event("keyup")}} events on the window.
+
{{domxref("WindowEventHandlers.onlanguagechange")}}
+
An event handler property for {{event("languagechange")}} events on the window.
+
{{domxref("GlobalEventHandlers.onload")}}
+
An event handler property for window loading.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
An event handler property for mousedown events on the window.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
An event handler property for mousemove events on the window.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
An event handler property for mouseout events on the window.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
An event handler property for mouseover events on the window.
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
An event handler property for mouseup events on the window.
+
{{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.onpageshow")}}
+
An event handler property for pageshow events on the window.
+
{{domxref("WindowEventHandlers.onpagehide")}}
+
An event handler property for pagehide events on the window.
+
{{domxref("Window.onpaint")}}
+
An event handler property for paint events on the window.
+
{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}
+
An event handler property for popstate events, which are fired when navigating to a session history entry representing a state object.
+
{{domxref("GlobalEventHandlers.onreset")}}
+
An event handler property for reset events on the window.
+
{{domxref("GlobalEventHandlers.onresize")}}
+
An event handler property for window resizing.
+
{{domxref("GlobalEventHandlers.onscroll")}}
+
An event handler property for window scrolling.
+
{{domxref("GlobalEventHandlers.onselect")}}
+
An event handler property for window selection.
+
{{domxref("GlobalEventHandlers.onsubmit")}}
+
An event handler property for submits on window forms.
+
{{domxref("Window.onunload")}}
+
An event handler property for unload events on the window.
+
{{domxref("Window.onuserproximity")}}
+
An event handler property for user proximity events
+
+ +

Constructors

+ +

See also the DOM Interfaces.

+ +
+
{{domxref("Window.DOMParser")}}
+
{{todo("NeedsContents")}}
+
{{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

+ +

See DOM Reference

+ +

See also

+ + diff --git a/files/pt-br/web/api/window/innerheight/index.html b/files/pt-br/web/api/window/innerheight/index.html new file mode 100644 index 0000000000..5caf8ae916 --- /dev/null +++ b/files/pt-br/web/api/window/innerheight/index.html @@ -0,0 +1,137 @@ +--- +title: Window.innerHeight +slug: Web/API/Window/innerHeight +translation_of: Web/API/Window/innerHeight +--- +
{{APIRef}}
+ +

Altura (em pixels) da janela de visualização do navegador, incluindo, se renderizado, a barra de rolagem horizontal.

+ +
Note: If you use {{ifmethod("nsIDOMWindowUtils", "setCSSViewport")}} to set the virtual window size for page layout purposes, the value returned by this property corresponds to the viewport height set using that method.
+ +

Syntax

+ +
var intViewportHeight = window.innerHeight;
+ +

Value

+ +

On return, intViewportHeight is the height of the browser window's viewport.

+ +

The window.innerHeight property is read only; it has no default value.

+ +

Notes

+ +

The innerHeight property is supported in any window object like a {{domxref("window")}}, a frame, a frameset, or a secondary window.

+ +

There is an algorithm to obtain the height of the viewport excluding, if rendered, the horizontal scrollbar.

+ +

Example

+ +

Assuming a frameset

+ +
var intFrameHeight = window.innerHeight; // or
+
+var intFrameHeight = self.innerHeight;
+// will return the height of the frame viewport within the frameset
+
+var intFramesetHeight = parent.innerHeight;
+// will return the height of the viewport of the closest frameset
+
+var intOuterFramesetHeight = top.innerHeight;
+// will return the height of the viewport of the outermost frameset
+
+ +

{{todo("link to an interactive demo here")}}

+ +

To change the size of a window, see {{domxref("window.resizeBy()")}} and {{domxref("window.resizeTo()")}}.

+ +

To get the outer height of a window, i.e. the height of the whole browser window, see {{domxref("window.outerHeight")}}.

+ +

Graphical example

+ +

The following figure shows the difference between outerHeight and innerHeight.

+ +

innerHeight vs outerHeight illustration

+ +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-window-innerheight', 'window.innerHeight')}}{{Spec2('CSSOM View')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}[1]993
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}[1]993
+
+ +

[1] From Firefox 4 to 24 this property was buggy and could give a wrong value before page load on certain circumstances, see {{bug(641188)}}.

+ +

See also

+ + diff --git a/files/pt-br/web/api/window/length/index.html b/files/pt-br/web/api/window/length/index.html new file mode 100644 index 0000000000..b99fa5747a --- /dev/null +++ b/files/pt-br/web/api/window/length/index.html @@ -0,0 +1,52 @@ +--- +title: Window.length +slug: Web/API/Window/length +tags: + - API + - DOM + - Gecko + - Propriedade + - Referencia + - Referência do DOM + - Referência do DOM do Gecko + - WebAPI + - Window +translation_of: Web/API/Window/length +--- +
{{ ApiRef() }}
+ +

Resumo

+ +

Retorna o número de frames (tanto elementos frame ou iframe) dentro da janela.

+ +

Sintaxe

+ +
quantidadeFrames = window.length;
+
+ + + +

Exemplo

+ +
if (window.length) {
+  // este é um documento com subframes
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','browsers.html#dom-length','Window.length')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/pt-br/web/api/window/location/index.html b/files/pt-br/web/api/window/location/index.html new file mode 100644 index 0000000000..09198523b3 --- /dev/null +++ b/files/pt-br/web/api/window/location/index.html @@ -0,0 +1,272 @@ +--- +title: Window.location +slug: Web/API/Window/location +translation_of: Web/API/Window/location +--- +

{{APIRef}}

+ +

O Window.location é uma propriedade de leitura que retorna um objeto {{domxref("Location")}} com informações de localização do documento atual.
+
+ Embora Window.location seja apenas um objeto de leitura de localização, você pode também atribuir uma {{domxref("DOMString")}} para ele. Isto significa que você pode trabalhar com location como se fosse uma string na maioria dos casos: location = 'http://www.exemplo.com' é um sinônimo de location.href = 'http://www.exemplo.com'.

+ +

Sintaxe

+ +
var oldLocation = location;
+location = newLocation;
+
+ +

Exemplos

+ +

Exemplo básico

+ +
alert(location); // alerta "https://developer.mozilla.org/en-US/docs/Web/API/Window.location"
+ +

Exemplo #1: Navegando para uma nova página

+ +

Sempre que um novo valor é atribuído a um objeto de localização, um documento será carregado usando a URL como se location.assign() tivesse sido chamado com a URL modificada. Observe que as configurações de segurança, como CORS, pode impedir que isso aconteça de forma eficaz.

+ +
location.assign("http://www.mozilla.org"); // ou
+location = "http://www.mozilla.org";
+
+ +

Exemplo #2: Forçando recerregamento da página atual do servidor

+ +
location.reload(true);
+ +

Exemplo #3

+ +

Considere o exemplo a seguir, que vai recarregar a página usando o método replace() para inserir o valor do location.pathname depois da hash:

+ +
function reloadPageWithHash() {
+  var initialPage = location.pathname;
+  location.replace('http://example.com/#' + initialPage);
+}
+
+ +
Nota: O exemplo acima funciona em situações onde location.hash não precisa ser retida. Contudo, em navegadores baseados em Gecko, definindo location.pathname desta forma irá apagar qualquer informação em location.hash, enquanto que no WebKit(e possivelmente em outro navegador), definir o pathname não vai alterar  o hash. Se você precisa mudar o pathname mas manter o hash como é, use o método replace(), que deve funcionar de forma consistente em todos os navegadores.
+ +

Exemplo #4: Mostrar as propriedades da URL atual em um alerta:

+ +
function showLoc() {
+  var oLocation = location, aLog = ["Property (Typeof): Value", "location (" + (typeof oLocation) + "): " + oLocation ];
+  for (var sProp in oLocation){
+    aLog.push(sProp + " (" + (typeof oLocation[sProp]) + "): " +  (oLocation[sProp] || "n/a"));
+  }
+  alert(aLog.join("\n"));
+}
+
+// no html: <button onclick="showLoc();">Mostrar propriedades de localização</button>
+
+ + + +
function sendData (sData) {
+  location.search = sData;
+}
+
+// no html: <button onclick="sendData('Algum dado');">Enviar dados</button>
+
+ +

A URL atual com "?Some%20data" anexada é enviada para o servidor (se nenhuma ação for captada pelo servidor, o documento atual é recarregado com o a linha de pesquisa modificada).

+ +

Exemplo #6: Usando favoritos sem mudar a propriedade hash:

+ +
<!doctype html>
+<html>
+<head>
+<meta charset="UTF-8"/>
+<title>MDN Exemplo</title>
+<script>
+function showNode (oNode) {
+  var nLeft = 0, nTop = 0;
+  for (var oItNode = oNode; oItNode; nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent);
+  document.documentElement.scrollTop = nTop;
+  document.documentElement.scrollLeft = nLeft;
+}
+
+function showBookmark (sBookmark, bUseHash) {
+  if (arguments.length === 1 || bUseHash) { location.hash = sBookmark; return; }
+  var oBookmark = document.querySelector(sBookmark);
+  if (oBookmark) { showNode(oBookmark); }
+}
+</script>
+<style>
+span.intLink {
+    cursor: pointer;
+    color: #0000ff;
+    text-decoration: underline;
+}
+</style>
+</head>
+
+<body>
+<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum.</p>
+<p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibendum quis. Cras adipiscing ultricies fermentum. Praesent bibendum condimentum feugiat.</p>
+<p id="myBookmark1">[&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark2');">Go to bookmark #2</span>&nbsp;]</p>
+<p>Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt. Nulla vitae tempor nisl. Etiam congue, elit vitae egestas mollis, ipsum nisi malesuada turpis, a volutpat arcu arcu id risus.</p>
+<p>Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p>
+<p>Aenean viverra varius mauris, sed elementum lacus interdum non. Phasellus sit amet lectus vitae eros egestas pellentesque fermentum eget magna. Quisque mauris nisl, gravida vitae placerat et, condimentum id metus. Nulla eu est dictum dolor pulvinar volutpat. Pellentesque vitae sollicitudin nunc. Donec neque magna, lobortis id egestas nec, sodales quis lectus. Fusce cursus sollicitudin porta. Suspendisse ut tortor in mauris tincidunt rhoncus. Maecenas tincidunt fermentum facilisis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
+<p>Suspendisse turpis nisl, consectetur in lacinia ut, ornare vel mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin non lectus eu turpis vulputate cursus. Mauris interdum tincidunt erat id pharetra. Nullam in libero elit, sed consequat lectus. Morbi odio nisi, porta vitae molestie ut, gravida ut nunc. Ut non est dui, id ullamcorper orci. Praesent vel elementum felis. Maecenas ornare, dui quis auctor hendrerit, turpis sem ullamcorper odio, in auctor magna metus quis leo. Morbi at odio ante.</p>
+<p>Curabitur est ipsum, porta ac viverra faucibus, eleifend sed eros. In sit amet vehicula tortor. Vestibulum viverra pellentesque erat a elementum. Integer commodo ultricies lorem, eget tincidunt risus viverra et. In enim turpis, porttitor ac ornare et, suscipit sit amet nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque vel ultrices nibh. Sed commodo aliquam aliquam. Nulla euismod, odio ut eleifend mollis, nisi dui gravida nibh, vitae laoreet turpis purus id ipsum. Donec convallis, velit non scelerisque bibendum, diam nulla auctor nunc, vel dictum risus ipsum sit amet est. Praesent ut nibh sit amet nibh congue pulvinar. Suspendisse dictum porttitor tempor.</p>
+<p>Vestibulum dignissim erat vitae lectus auctor ac bibendum eros semper. Integer aliquet, leo non ornare faucibus, risus arcu tristique dolor, a aliquet massa mauris quis arcu. In porttitor, lectus ac semper egestas, ligula magna laoreet libero, eu commodo mauris odio id ante. In hac habitasse platea dictumst. In pretium erat diam, nec consequat eros. Praesent augue mi, consequat sed porttitor at, volutpat vitae eros. Sed pretium pharetra dapibus. Donec auctor interdum erat, lacinia molestie nibh commodo ut. Maecenas vestibulum vulputate felis, ut ullamcorper arcu faucibus in. Curabitur id arcu est. In semper mollis lorem at pellentesque. Sed lectus nisl, vestibulum id scelerisque eu, feugiat et tortor. Pellentesque porttitor facilisis ultricies.</p>
+<p id="myBookmark2">[&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark1');">Go to bookmark #1</span> | <span class="intLink" onclick="showBookmark('#myBookmark1', false);">Go to bookmark #1 without using location.hash</span> | <span class="intLink" onclick="showBookmark('#myBookmark3');">Go to bookmark #3</span>&nbsp;]</p>
+<p>Phasellus tempus fringilla nunc, eget sagittis orci molestie vel. Nulla sollicitudin diam non quam iaculis ac porta justo venenatis. Quisque tellus urna, molestie vitae egestas sit amet, suscipit sed sem. Quisque nec lorem eu velit faucibus tristique ut ut dolor. Cras eu tortor ut libero placerat venenatis ut ut massa. Sed quis libero augue, et consequat libero. Morbi rutrum augue sed turpis elementum sed luctus nisl molestie. Aenean vitae purus risus, a semper nisl. Pellentesque malesuada, est id sagittis consequat, libero mauris tincidunt tellus, eu sagittis arcu purus rutrum eros. Quisque eget eleifend mi. Duis pharetra mi ac eros mattis lacinia rutrum ipsum varius.</p>
+<p>Fusce cursus pulvinar aliquam. Duis justo enim, ornare vitae elementum sed, porta a quam. Aliquam eu enim eu libero mollis tempus. Morbi ornare aliquam posuere. Proin faucibus luctus libero, sed ultrices lorem sagittis et. Vestibulum malesuada, ante nec molestie vehicula, quam diam mollis ipsum, rhoncus posuere mauris lectus in eros. Nullam feugiat ultrices augue, ac sodales sem mollis in.</p>
+<p id="myBookmark3"><em>Here is the bookmark #3</em></p>
+<p>Proin vitae sem non lorem pellentesque molestie. Nam tempus massa et turpis placerat sit amet sollicitudin orci sodales. Pellentesque enim enim, sagittis a lobortis ut, tempus sed arcu. Aliquam augue turpis, varius vel bibendum ut, aliquam at diam. Nam lobortis, dui eu hendrerit pellentesque, sem neque porttitor erat, non dapibus velit lectus in metus. Vestibulum sit amet felis enim. In quis est vitae nunc malesuada consequat nec nec sapien. Suspendisse aliquam massa placerat dui lacinia luctus sed vitae risus. Fusce tempus, neque id ultrices volutpat, mi urna auctor arcu, viverra semper libero sem vel enim. Mauris dictum, elit non placerat malesuada, libero elit euismod nibh, nec posuere massa arcu eu risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer urna velit, dapibus eget varius feugiat, pellentesque sit amet ligula. Maecenas nulla nisl, facilisis eu egestas scelerisque, mollis eget metus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi sed congue mi.</p>
+<p>Fusce metus velit, pharetra at vestibulum nec, facilisis porttitor mi. Curabitur ligula sapien, fermentum vel porttitor id, rutrum sit amet magna. Sed sit amet sollicitudin turpis. Aenean luctus rhoncus dolor, et pulvinar ante egestas et. Donec ac massa orci, quis dapibus augue. Vivamus consectetur auctor pellentesque. Praesent vestibulum tincidunt ante sed consectetur. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Fusce purus metus, imperdiet vitae iaculis convallis, bibendum vitae turpis.</p>
+<p>Fusce aliquet molestie dolor, in ornare dui sodales nec. In molestie sollicitudin felis a porta. Mauris nec orci sit amet orci blandit tristique congue nec nunc. Praesent et tellus sollicitudin mauris accumsan fringilla. Morbi sodales, justo eu sollicitudin lacinia, lectus sapien ullamcorper eros, quis molestie urna elit bibendum risus. Proin eget tincidunt quam. Nam luctus commodo mauris, eu posuere nunc luctus non. Nulla facilisi. Vivamus eget leo rhoncus quam accumsan fringilla. Aliquam sit amet lorem est. Nullam vel tellus nibh, id imperdiet orci. Integer egestas leo eu turpis blandit scelerisque.</p>
+<p>Etiam in blandit tellus. Integer sed varius quam. Vestibulum dapibus mi gravida arcu viverra blandit. Praesent tristique augue id sem adipiscing pellentesque. Sed sollicitudin, leo sed interdum elementum, nisi ante condimentum leo, eget ornare libero diam semper quam. Vivamus augue urna, porta eget ultrices et, dapibus ut ligula. Ut laoreet consequat faucibus. Praesent at lectus ut lectus malesuada mollis. Nam interdum adipiscing eros, nec sodales mi porta nec. Proin et quam vitae sem interdum aliquet. Proin vel odio at lacus vehicula aliquet.</p>
+<p>Etiam placerat dui ut sem ornare vel vestibulum augue mattis. Sed semper malesuada mi, eu bibendum lacus lobortis nec. Etiam fringilla elementum risus, eget consequat urna laoreet nec. Etiam mollis quam non sem convallis vel consectetur lectus ullamcorper. Aenean mattis lacus quis ligula mattis eget vestibulum diam hendrerit. In non placerat mauris. Praesent faucibus nunc quis eros sagittis viverra. In hac habitasse platea dictumst. Suspendisse eget nisl erat, ac molestie massa. Praesent mollis vestibulum tincidunt. Fusce suscipit laoreet malesuada. Aliquam erat volutpat. Aliquam dictum elementum rhoncus. Praesent in est massa, pulvinar sodales nunc. Pellentesque gravida euismod mi ac convallis.</p>
+<p>Mauris vel odio vel nulla facilisis lacinia. Aliquam ultrices est at leo blandit tincidunt. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse porttitor adipiscing facilisis. Duis cursus quam iaculis augue interdum porttitor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis vulputate magna ac metus pretium condimentum. In tempus, est eget vestibulum blandit, velit massa dignissim nisl, ut scelerisque lorem neque vel velit. Maecenas fermentum commodo viverra. Curabitur a nibh non velit aliquam cursus. Integer semper condimentum tortor a pellentesque. Pellentesque semper, nisl id porttitor vehicula, sem dui feugiat lacus, vitae consequat augue urna vel odio.</p>
+<p>Vestibulum id neque nec turpis iaculis pulvinar et a massa. Vestibulum sed nibh vitae arcu eleifend egestas. Mauris fermentum ultrices blandit. Suspendisse vitae lorem libero. Aenean et pellentesque tellus. Morbi quis neque orci, eu dignissim dui. Fusce sollicitudin mauris ac arcu vestibulum imperdiet. Proin ultricies nisl sit amet enim imperdiet eu ornare dui tempus. Maecenas lobortis nisi a tortor vestibulum vel eleifend tellus vestibulum. Donec metus sapien, hendrerit a fermentum id, dictum quis libero.</p>
+<p>Pellentesque a lorem nulla, in tempor justo. Duis odio nisl, dignissim sed consequat sit amet, hendrerit ac neque. Nunc ac augue nec massa tempor rhoncus. Nam feugiat, tellus a varius euismod, justo nisl faucibus velit, ut vulputate justo massa eu nibh. Sed bibendum urna quis magna facilisis in accumsan dolor malesuada. Morbi sit amet nunc risus, in faucibus sem. Nullam sollicitudin magna sed sem mollis id commodo libero condimentum. Duis eu massa et lacus semper molestie ut adipiscing sem.</p>
+<p>Sed id nulla mi, eget suscipit eros. Aliquam tempus molestie rutrum. In quis varius elit. Nullam dignissim neque nec velit vulputate porttitor. Mauris ac ligula sit amet elit fermentum rhoncus. In tellus urna, pulvinar quis condimentum ut, porta nec justo. In hac habitasse platea dictumst. Proin volutpat elit id quam molestie ac commodo lacus sagittis. Quisque placerat, augue tempor placerat pulvinar, nisi nisi venenatis urna, eget convallis eros velit quis magna. Suspendisse volutpat iaculis quam, ut tristique lacus luctus quis.</p>
+<p>Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum.</p>
+</body>
+</html>
+
+ +
Nota: A função showNode é também um exemplo de uso do ciclo for sem uma section statement. Neste  caso o ponto e vírgula é sempre colocado imediatamente depois da declaração do ciclo.
+ +

... a mesma coisa mas com uma animação de rolagem na página:

+ +
var showBookmark = (function () {
+  var  _useHash, _scrollX, _scrollY, _nodeX, _nodeY, _itFrame, _scrollId = -1, _bookMark,
+       /*
+       * nDuration: the duration in milliseconds of each frame
+       * nFrames: number of frames for each scroll
+       */
+       nDuration = 200, nFrames = 10;
+
+  function _next () {
+    if (_itFrame > nFrames) { clearInterval(_scrollId); _scrollId = -1; return; }
+    _isBot = true;
+    document.documentElement.scrollTop = Math.round(_scrollY + (_nodeY - _scrollY) * _itFrame / nFrames);
+    document.documentElement.scrollLeft = Math.round(_scrollX + (_nodeX - _scrollX) * _itFrame / nFrames);
+    if (_useHash && _itFrame === nFrames) { location.hash = _bookMark; }
+    _itFrame++;
+  }
+
+  function _chkOwner () {
+    if (_isBot) { _isBot = false; return; }
+    if (_scrollId > -1) { clearInterval(_scrollId); _scrollId = -1; }
+  }
+
+  if (window.addEventListener) { window.addEventListener("scroll", _chkOwner, false); }
+  else if (window.attachEvent) { window.attachEvent("onscroll", _chkOwner); }
+
+  return function (sBookmark, bUseHash) {
+    _scrollY = document.documentElement.scrollTop;
+    _scrollX = document.documentElement.scrollLeft;
+    _bookMark = sBookmark;
+    _useHash = arguments.length === 1 || bUseHash;
+    for (
+      var nLeft = 0, nTop = 0, oNode = document.querySelector(sBookmark);
+      oNode;
+      nLeft += oNode.offsetLeft, nTop += oNode.offsetTop, oNode = oNode.offsetParent
+    );
+    _nodeX = nLeft, _nodeY = nTop, _itFrame = 1;
+    if (_scrollId === -1) { _scrollId = setInterval(_next, Math.round(nDuration / nFrames)); }
+  };
+})();
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstatusComentário
{{SpecName('HTML WHATWG', "history.html#the-location-interface", "Window.location")}}{{Spec2('HTML WHATWG')}}Sem mudanças a partir de {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Window.location")}}{{Spec2('HTML5 W3C')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
window.location.origin30.0.1599.101 (possibly earlier){{CompatGeckoDesktop("21.0")}}11[1]{{CompatUnknown}}7 (possibly earlier, see webkit bug 46558)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
window.location.origin30.0.1599.101 (possibly earlier){{CompatGeckoMobile("21.0")}}{{CompatUnknown}}{{CompatUnknown}}7 (possibly earlier, see webkit bug 46558)
+
+ +

[1] In Internet Explorer 11 on Windows 10 window.location.origin is undefined due to a bug, see https://connect.microsoft.com/IE/feedback/details/1763802/location-origin-is-undefined-in-ie-11-on-windows-10-but-works-on-windows-7.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/matchmedia/index.html b/files/pt-br/web/api/window/matchmedia/index.html new file mode 100644 index 0000000000..a6497ded0a --- /dev/null +++ b/files/pt-br/web/api/window/matchmedia/index.html @@ -0,0 +1,106 @@ +--- +title: Window.matchMedia() +slug: Web/API/Window/matchMedia +translation_of: Web/API/Window/matchMedia +--- +
{{APIRef}}
+ +

Resumo

+ +

Retorna um novo objeto {{domxref("MediaQueryList")}} representando o resultado analisado da string media query especificada.

+ +

Sintaxe

+ +
mql = window.matchMedia(mediaQueryString)
+ +

onde mediaQueryString é uma string representando a media query para o qual retorna um novo objeto {{domxref("MediaQueryList")}}.

+ +

Exemplo

+ +
if (window.matchMedia("(min-width: 400px)").matches) {
+  /* a viewport tem pelo menos 400 pixels de largura */
+} else {
+  /* a viewport menos que 400 pixels de largura */
+}
+ +

Este código permite-lhe lidar com as coisas de forma diferente quando a janela é muito estreita.

+ +

Veja Usando media queries a partir do código para mais exemplos.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComment
{{SpecName("CSSOM View", "#dom-window-matchmedia", "Window.matchMedia()")}}{{Spec2("CSSOM View")}}Initial definition
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9{{CompatGeckoDesktop("6.0")}}1012.15.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{CompatGeckoMobile("6.0")}}{{CompatNo}}12.15
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/navigator/index.html b/files/pt-br/web/api/window/navigator/index.html new file mode 100644 index 0000000000..c73ebe3f36 --- /dev/null +++ b/files/pt-br/web/api/window/navigator/index.html @@ -0,0 +1,54 @@ +--- +title: Window.navigator +slug: Web/API/Window/navigator +tags: + - API + - Propriedade + - Referencia + - Somente-leitura + - Window +translation_of: Web/API/Window/navigator +--- +
+ {{APIRef}}
+

A propriedade somente leitura Window.navigator retorna uma referência para o objeto {{domxref("Navigator")}}, que pode ser consultada para obter informações sobre a aplicação executando o script.

+

Sintaxe

+
navigatorObject = window.navigator
+

Exemplos

+

Exemplo #1: Detecta o navegador e retorna uma string

+
var sBrowser, sUsrAg = navigator.userAgent;
+
+if(sUsrAg.indexOf("Chrome") > -1) {
+    sBrowser = "Google Chrome";
+} else if (sUsrAg.indexOf("Safari") > -1) {
+    sBrowser = "Apple Safari";
+} else if (sUsrAg.indexOf("Opera") > -1) {
+    sBrowser = "Opera";
+} else if (sUsrAg.indexOf("Firefox") > -1) {
+    sBrowser = "Mozilla Firefox";
+} else if (sUsrAg.indexOf("MSIE") > -1) {
+    sBrowser = "Microsoft Internet Explorer";
+}
+
+alert("Você está utilizando: " + sBrowser);
+

Exemplo #2: Detecta o navegador e retorna um índice

+
function getBrowserId () {
+
+    var
+        aKeys = ["MSIE", "Firefox", "Safari", "Chrome", "Opera"],
+        sUsrAg = navigator.userAgent, nIdx = aKeys.length - 1;
+
+    for (nIdx; nIdx > -1 && sUsrAg.indexOf(aKeys[nIdx]) === -1; nIdx--);
+
+    return nIdx
+
+}
+
+console.log(getBrowserId());
+

Especificação

+ +

Veja também

diff --git a/files/pt-br/web/api/window/ondevicelight/index.html b/files/pt-br/web/api/window/ondevicelight/index.html new file mode 100644 index 0000000000..005ef03903 --- /dev/null +++ b/files/pt-br/web/api/window/ondevicelight/index.html @@ -0,0 +1,99 @@ +--- +title: Window.ondevicelight +slug: Web/API/Window/ondevicelight +translation_of: Web/API/Window/ondevicelight +--- +
{{APIRef}}
+ +

Especifica um event listener para receber eventos {{event("devicelight")}}. Esses eventos ocorrem quando um dispositivo com sensores de nível de luz detecta uma mudança na intensidade do nível de luz do ambiente.

+ +

Sintaxe

+ +
window.ondevicelight = funcRef
+ +

Onde funcRef é a função a ser chamada quando o evento {{event("devicelight")}} ocorre. Estes eventos são do tipo {{domxref("DeviceLightEvent")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificaçãoStatusComment
{{SpecName('AmbientLight', '#event-handlers', 'Ambient Light Events')}}{{Spec2('AmbientLight')}}Initial definition
+ +

Compatibilidade com os Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("15.0")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] The {{event("devicelight")}} event is implemented and by preference enabled by default in Firefox Mobile for Android (15.0) and in Firefox OS (B2G). Starting with Gecko 22.0 {{geckoRelease("22.0")}}, a desktop implementation for Mac OS X is also available. Support for Windows 7 is in progress (see {{bug(754199)}}).

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/onscroll/index.html b/files/pt-br/web/api/window/onscroll/index.html new file mode 100644 index 0000000000..9589f24eaa --- /dev/null +++ b/files/pt-br/web/api/window/onscroll/index.html @@ -0,0 +1,98 @@ +--- +title: window.onscroll +slug: Web/API/Window/onscroll +translation_of: Web/API/GlobalEventHandlers/onscroll +--- +

{{ ApiRef() }}

+

Sumário

+

Especifica a função a ser chamada quando é feito o scroll na janela.

+

Sintaxe

+
window.onscroll = funcRef;
+
+ +

Exemplos

+

Exemplo 1: Genérico

+
window.onscroll = function (oEvent) {
+  // executa um bloco de código ou funções, quando o scroll é feito na janela.
+}
+
+

Examplo 2: Dectando a rolagem

+

O exemplo a seguir, irá disparar um alerta sempre que o usuário rolar a página .

+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>onscroll test</title>
+<script type="text/javascript">
+window.onscroll = scroll;
+
+function scroll () {
+ alert("evento scroll detectado! " + window.pageXOffset + " " + window.pageYOffset);
+ // nota: você pode usar window.innerWidth e window.innerHeight para obter a largura e altura da área de visão.
+}
+</script>
+</head>
+
+<body>
+<p>Redimensione a janela</p>
+<p>para um tamanho pequeno,</p>
+<p>e use a barra de rolagem</p>
+<p>para mover ao redor do conteúdo da página</p>
+<p>na janela.</p>
+</body>
+</html>
+
+ +

O exemplo a seguir irá mostrar um link( uma imagem de seta ) no topo da página quando a rolagem vertical atingir 500 pixels

+

 

+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example</title>
+<script type="text/javascript">
+var bAppended = false, oBookmark = document.createElement("div");
+oBookmark.id = "arrowUp";
+oBookmark.innerHTML = "<a href=\"#\" title=\"Top of the page.\">&uarr;<\/a>";
+
+onscroll = function() {
+  var nVScroll = document.documentElement.scrollTop || document.body.scrollTop;
+  bAppended = nVScroll > 500 ?
+    bAppended || (document.body.appendChild(oBookmark), true)
+    : bAppended && (document.body.removeChild(oBookmark), false);
+};
+</script>
+<style type="text/css">
+#arrowUp {
+  position: fixed;
+  height: auto;
+  width: auto;
+  right: 10px;
+  top: 10px;
+  font-size: 48px;
+}
+#arrowUp a {
+  text-decoration: none;
+  color: black;
+  font-weight: bold;
+  font-family: serif;
+}
+</style>
+</head>
+
+<body>
+<p>Conteúdo da página aqui!</p>
+</body>
+
+</html>
+

Notas

+

{{ Bug(189308) }}, nas versões antigas do Gecko, o evento 'onscroll' era executado apenas quando a barra de rolagem era arrastada, não quando utilizada a seta do teclado ou scroll do mouse.
+ Esse bug foi corrigido no Gecko 1.8/Firefox 1.5

+

Quando o window.scrollX/scrollY não é 0 -- considerando que o scroll ocorreu por algum script ou uma ação manual -- recarregando a página irá disparar o evento onscroll imediatamente.

+

Especificação

+ +

{{ languages( { "zh-cn": "zh-cn/DOM/window.onscroll"} ) }}

diff --git a/files/pt-br/web/api/window/opendialog/index.html b/files/pt-br/web/api/window/opendialog/index.html new file mode 100644 index 0000000000..cb2e5f31ba --- /dev/null +++ b/files/pt-br/web/api/window/opendialog/index.html @@ -0,0 +1,90 @@ +--- +title: window.openDialog +slug: Web/API/Window/openDialog +translation_of: Web/API/Window/openDialog +--- +

{{ ApiRef() }}

+ +

Resumo

+ +

window.openDialog é uma extensão para window.open. Ela se comporta da mesma maneira, exceto que pode opcionalmente usar um ou mais parâmetros passado por windowFeatures, e windowFeatures em si é tratado um pouco diferente.

+ +

Parâmetros opcionais, se presentes, serão incluídos no JavaScript Array object e adicionados a nova janela criada como uma propriedade chamada window.arguments. Eles podem ser referenciados no javascript da janela a qualquer momento, incluindo durante a execução da load handler. Esses parâmetros podem ser usados, e depois, para passar argumentos para e da janela de diálogo.

+ +

Note que a chamada para openDialog() retorna imediatamente. Se você quer que a chamada seja bloqueada até o usuário fechar a janela de diálogo, forneça modal como um parâmetro windowFeatures. Note que isso significa que o usuário não poderá interagir com a janela que abriu a janela modal (modal dialog) enquanto o usuário não fechá-la.

+ +

Sintaxe

+ +
newWindow = openDialog(url, name, features, arg1, arg2, ...)
+
+ +
+
newWindow 
+
A janela aberta
+
url 
+
A URL a ser carregada na nova janela aberta.
+
name 
+
O nome da janela (opcional). Veja a descrição de window.open para informações detalhadas.
+
features 
+
Consulte window.open para descrição.
+
arg1, arg2, ... 
+
Os argumentos podem ser passados para a nova janela (opcional).
+
+ +

Exemplo

+ +
var win = openDialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98);
+
+ +

Observações

+ +

Novas funcionalidades

+ +

all - Initially activates (or deactivates ("all=no")) all chrome (except the behaviour flags chrome, dialog and modal). These can be overridden (so "menubar=no,all" turns on all chrome except the menubar.) This feature is explicitly ignored by window.open. window.openDialog finds it useful because of its different default assumptions.

+ +

Comportamento padrão

+ +

The chrome and dialog features are always assumed on, unless explicitly turned off ("chrome=no"). openDialog treats the absence of the features parameter as does window.open, (that is, an empty string sets all features to off) except chrome and dialog, which default to on. If the features parameter is a zero-length string, or contains only one or more of the behaviour features (chrome, dependent, dialog and modal) the chrome features are assumed "OS' choice." That is, window creation code is not given specific instructions, but is instead allowed to select the chrome that best fits a dialog on that operating system.

+ +

Passando parâmetros extras para o diálogo

+ +

Para passar parâmento extra para a janela de diálogo, você pode simplesmente pode fornece=lo depois do parâmetro windowFeatures:

+ +
openDialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98);
+
+ +

Os parâmetros serão empacotados em uma propriedade chamada arguments do tipo Array, e essa propriedade será adicionada para a nova janela de diálogo.

+ +

Para acessar esses parâmetros extras da janela de diálogo, use o seguinte esquema:

+ +
var food  = window.arguments[0];
+var price = window.arguments[1];
+
+ +

Note que você pode acessar esta propriedade de qualwuer lugar do código de diálogo.. (Outro exemplo).

+ +

Retornando valores do diálogo

+ +

Dado que window.close() apaga todas a propriedades associadas com a janela de diálogo (isto é, as variáveis especificadas no código javascript que é carregado a partir da janela de diálogo), não é possível passar os valores retornados depois da operação de fechamento usando variáveis globais (ou qualquer outro construtor).

+ +

Para ser possível passar valores de volta para a janela que chamou, você deve fornecer algum objeto via parâmetros extra. Em seguida, pode acessar esse objeto de dentro do código de diálogo e definir as propriedades nele, que contém os valores que você deseja retornar ou preservar passado a operação window.close().

+ +
var retVals = { address: null, delivery: null };
+openDialog("http://example.tld/zzz.xul", "dlg", "modal", "pizza", 6.98, retVals);
+
+ +

Se você definir as propriedades do objeto retVals no código de diálogo, conforme descrito abaixo, agora você pode acessá-los via array retVals depois do retorno da chamada de openDialog().

+ +

Dentro do código de diálogo, você pode definir as propriedades da seguinte forma:

+ +
var retVals = window.arguments[2];
+retVals.address  = enteredAddress;
+retVals.delivery = "immediate";
+
+ +

Veja também . (Outro exemplo).
+ veja também window.importDialog (mobile).

+ +

Especificação

+ +

{{ DOM0() }}

diff --git a/files/pt-br/web/api/window/performance/index.html b/files/pt-br/web/api/window/performance/index.html new file mode 100644 index 0000000000..6e7edcd558 --- /dev/null +++ b/files/pt-br/web/api/window/performance/index.html @@ -0,0 +1,33 @@ +--- +title: Window.performance +slug: Web/API/Window/performance +translation_of: Web/API/Window/performance +--- +
{{APIREf}}
+ +
A API Web Performance permite páginas da web acessarem algumas funções para medir a performance de páginas e aplicações da web, incluindo a API Navigation Timing e dados de tempo de alta resolução.
+ +
 
+ +

Métodos

+ +
+
{{domxref("Performance.mark()", "performance.mark()")}}
+
Mapeia um {{domxref("DOMHighResTimeStamp")}} para o nome especificado representando a quantidade de milissegundos passados desde um momento de referência.
+
+ +
+
{{domxref("Performance.now()", "performance.now()")}}
+
Retorna um {{domxref("DOMHighResTimeStamp")}} representando a quantidade de milissegundos passados desde um momento de referência.
+
+ +

Propriedades

+ +
+
{{domxref("Performance.timing", "performance.timing")}}
+
É um objeto {{domxref("PerformanceTiming")}} contendo informações de performance relacionadas a latência.
+
{{domxref("Performance.navigation", "performance.navigation")}}
+
É um objeto {{domxref("PerformanceNavigation")}} representando o tipo de navegação que ocorre no contexto de navegação dado, como a quantidade de redirecionamentos necessários para buscar o recurso.
+
performance.memory
+
Uma extensao não-padrão adicionada ao Chrome.
+
diff --git a/files/pt-br/web/api/window/popstate_event/index.html b/files/pt-br/web/api/window/popstate_event/index.html new file mode 100644 index 0000000000..55f493f18b --- /dev/null +++ b/files/pt-br/web/api/window/popstate_event/index.html @@ -0,0 +1,144 @@ +--- +title: popstate +slug: Web/API/Window/popstate_event +translation_of: Web/API/Window/popstate_event +--- +

O evento popstate é disparado quando a entrada do histórico ativa é alterado. Se o histórico de entrada a ser ativado for criado por uma chamada history.pushState() ou for afetada por uma chamada history.replaceState(), a propriedade dos eventos popstate contém uma cópia do histórico de entrada do objeto.
+
+ Note  que apenas chamando history.pushState() ou history.replaceState() não ira disparar um evento popstate. O evento popstate apenas é disparado após uma ação no navegador como um click no botão de voltar (ou chamando history.back() por javascript)
+
+ Navegadores tendem a lidar com o evento popstate diferentemente no carregamento da página. Chrome (anterior versão 34) e Safari sempre emitem um evento popstate no carregamento da página, mas o Firefox não.

+ +

Informação geral

+ +
+
Especificação
+
HTML5
+
Interface
+
PopStateEvent
+
Bubbles
+
Yes
+
Cancelable
+
No
+
Alvo
+
defaultView
+
Ação padrão
+
None
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}The browsing context (window).
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.
state {{readonlyInline}}anyThe current history entry's state object (if any).
+ +

Compatiblidade com navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico3.0[2]{{CompatGeckoMobile("2")}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]
+
+ +

[1] A implementação tem um suporte limitado.

+ +

[2] A implementação em Android 2.2 e 2.3 tem problemas.

+ +

Exemplo

+ +

Um página no http://example.com/example.html roda o código abaixo e irá gerar os logs indicados

+ +
window.onpopstate = function(event) {
+  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
+};
+history.pushState({page: 1}, "title 1", "?page=1");
+history.pushState({page: 2}, "title 2", "?page=2");
+history.replaceState({page: 3}, "title 3", "?page=3");
+history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back(); // Logs "location: http://example.com/example.html, state: null
+history.go(2);  // Logs "location: http://example.com/example.html?page=3, state: {"page":3}
+
+ +

Observe que mesmo que a entrada do histórico inicial(para http://example.com/example.html) não tem nenhum estado associado a ele, um evento popstate é ainda disparado quando nós ativamos essa entrada após a segunda chamada para history.back ().
+  

+ +

Eventos relacionados

+ + diff --git a/files/pt-br/web/api/window/print/index.html b/files/pt-br/web/api/window/print/index.html new file mode 100644 index 0000000000..6bf664bfb0 --- /dev/null +++ b/files/pt-br/web/api/window/print/index.html @@ -0,0 +1,56 @@ +--- +title: Window.print() +slug: Web/API/Window/print +tags: + - DOM + - Window + - print +translation_of: Web/API/Window/print +--- +

{{ ApiRef() }}

+ +

Sumário

+ +

Abre a janela de impressão para imprimir o documento atual.

+ +

Sintaxe

+ +
window.print()
+
+ +

Notas

+ +

Começando com o  Chrome {{CompatChrome(46.0)}} este método é bloqueado dentro de um {{htmlelement("iframe")}} a menos que seu atributo sandbox tem o valor allow-modal .

+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'timers-and-user-prompts.html#printing', 'print()')}}{{Spec2('HTML WHATWG')}}
+ +

Compatibilidade entre Navegadores

+ + + +

{{Compat("api.Window.print")}}

+ +

Veja também

+ + + +

{{ languages( { "ja": "ja/DOM/window.print", "it": "it/DOM/window.print" , "zh-cn": "zh-cn/DOM/window.print" } ) }}

diff --git a/files/pt-br/web/api/window/prompt/index.html b/files/pt-br/web/api/window/prompt/index.html new file mode 100644 index 0000000000..e831fbcc4d --- /dev/null +++ b/files/pt-br/web/api/window/prompt/index.html @@ -0,0 +1,66 @@ +--- +title: Window.prompt() +slug: Web/API/Window/prompt +translation_of: Web/API/Window/prompt +--- +
{{ApiRef("Window")}}
+ +
O Window.prompt() exibe uma caixa de diálogo com uma mensagem opcional solicitando ao usuário a entrada de algum texto.
+ +

 

+ +

Sintaxe

+ +
resultado = window.prompt(texto, valor);
+
+ + + +

Exemplo

+ +
var signo = prompt("Qual é o seu signo?");
+
+if (signo.toLowerCase() == "escorpião") {
+  alert("Legal! Eu sou de Escorpião também!");
+}
+
+// há muitas formas de se usar o recurso prompt
+var sign = window.prompt(); // abrir uma janela de promtpt em branco
+var sign = prompt();       //  abrir uma janela de promtpt em branco
+var sign = window.prompt('Você está se sentindo com sorte'); // abrir uma janela com o texto "Você está se sentindo com sorte"
+var sign = window.prompt('Você está se sentindo com sorte', 'certamente'); // abrir uma janela com o texto "Você está se sentindo com sorte" e com o valor padrão "certamente"
+ +

Quando o usuário pressiona o botão OK, o texto digitado no campo de texto é retornado. Se o usuário pressionar OK sem ter digitado qualquer texto, uma cadeia de caracteres vazia é retornada. Se o usuário pressionar o botão Cancelar, esta função retornará null.

+ +

{{todo("external image!")}} O prompt acima aparece da seguinte forma (no Chrome do Windows 7):

+ +

+ +

Notas

+ +

Uma caixa de diálogo prompt contém uma caixa de texto de linha única, um botão Cancelar, e um botão OK, e retorna o (possivelmente vazio) texto que o usuário digitou naquela caixa de texto.

+ +

The following text is shared between this article, DOM:window.confirm and DOM:window.alertAs caixas de diálogo são janelas modais; eles impedem o usuário de acessar o resto da interface do programa até que a caixa de diálogo seja fechada. Por esta razão, você não deve abusar de qualquer função que crie uma caixa de diálogo (ou janela modal).

+ +

Por favor, note que o resultado é uma cadeia de caracteres. Isso significa que você deve, algumas vezes, converter o valor dado pelo usuário. Por exemplo, se a resposta deve ser um número, você deve converter o valor para Number: var aNumber = Number(window.prompt("Digite um número", "")); 

+ +

Os códigos do Mozilla Chrome (e.g. Firefox extensions) ao invés disso, devem usar os métodos da interface {{interface("nsIPromptService")}}.

+ +

No Safari, se o usuário clicar em Cancelar, a função retornará uma cadeia de caracteres vazia. Portanto, ele não diferenciará o cancelamento do usuário de uma cadeia de caracteres vazia na caixa de texto.

+ +

Esta função não tem efeito na versão Modern UI/Metro do Internet Explorer para Windows 8. Ele não exibe o prompt para o usuário, e sempre retornará undefined. Não está claro se é um erro ou um comportamento intencional. Versões desktop do IE implementam esta função.

+ +

Especificação

+ +

Especificado em HTML5.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/requestanimationframe/index.html b/files/pt-br/web/api/window/requestanimationframe/index.html new file mode 100644 index 0000000000..3adca4b22f --- /dev/null +++ b/files/pt-br/web/api/window/requestanimationframe/index.html @@ -0,0 +1,106 @@ +--- +title: window.requestAnimationFrame() +slug: Web/API/Window/requestAnimationFrame +tags: + - API + - DOM + - Intermediário + - Método(2) + - Referência do DOM + - Timers JavaScript +translation_of: Web/API/window/requestAnimationFrame +--- +

{{APIRef}}
+ O método window.requestAnimationFrame() fala para o navegador que deseja-se realizar uma animação e pede que o navegador chame uma função específica para atualizar um quadro de animação antes da próxima repaint (repintura). O método tem como argumento uma callback que deve ser invocado antes da repaint.

+ +
Nota: A rotina callback deve chamar requestAnimationFrame() se quiser animar outro quadro na próxima repaint.
+ +

Deve-se chamar esse método sempre que estiver pronto para atualizar a animação na tela. Isso irá requisitar que a função de animação seja chamada antes que o navegador realize a próxima repaint. O número de callbacks é normalmente 60 por segundo, mas geralmente acompanha a taxa de atualização do display na maioria dos navegadores, como recomenda a W3C. A taxa de callbacks é reduzida quando executados em aba de fundo ou em {{ HTMLElement("iframe") }} escondidos para melhorar performance e vida de bateria.

+ +

Um único argumento é passado para o método callback, um {{domxref("DOMHighResTimeStamp")}}, que indica o tempo atual no qual callbacks enfileiradas por requestAnimationFrame começam a disparar. Múltiplos callbacks em um único quadro, assim, cada um recebe o mesmo carimbo de data/hora . Esse carimbo de data/hora é um número decimal, em milisegundos, mas com precisão mínima de 1ms (1000 µs).

+ +

Sintaxe

+ +
window.requestAnimationFrame(callback);
+
+ +

Parâmetros

+ +
+
callback
+
Parâmetro especificando uma função a ser chamada quando chegar a hora de atualizar a animação para a próxima repaint. O callback possui um único argumento, um {{domxref("DOMHighResTimeStamp")}}, que indica a hora atual (a hora retornada de {{domxref('Performance.now()')}} ) para quando requestAnimationFrame começar a disparar callbacks.
+
+ +

Valor de retorno

+ +

Um valor inteiro long, a id da requisição, que identifica unicamente a entrada na lista de callbacks. Esse é um valor não-zero, mas não deve-se assumir mais nada sobre esse valor. Esse valor pode ser passado para {{domxref("window.cancelAnimationFrame()")}} para cancelar a requisição da atualização do callback.

+ +

Exemplo

+ +
var start = null;
+var element = document.getElementById("ElementoQueVcQuerAnimar");
+element.style.position = 'absolute';
+
+function step(timestamp) {
+  if (!start) start = timestamp;
+  var progress = timestamp - start;
+  element.style.left = Math.min(progress/10, 200) + "px";
+  if (progress < 2000) {
+    window.requestAnimationFrame(step);
+  }
+}
+
+window.requestAnimationFrame(step);
+
+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#animation-frames', 'requestAnimationFrame')}}{{Spec2('HTML WHATWG')}}Sem mudanças, substitui a anterior
{{SpecName('RequestAnimationFrame', '#dom-windowanimationtiming-requestanimationframe', 'requestAnimationFrame')}}{{Spec2('RequestAnimationFrame')}}Definição inicial
+ +

Compatibilidade de navegadores

+ +
{{Compat("api.Window.requestAnimationFrame")}}
+ +
+ +

[1] Anteriro ao Gecko 11.0 {{geckoRelease("11.0")}}, mozRequestAnimationFrame() podia ser chamado sem parâmetros de entrada. Isso não é mais suportado, como provavelmente não será parte do padrão

+ +

[2] O parâmetro do callback é {{domxref("DOMTimeStamp")}} ao invés de {{domxref("DOMHighResTimeStamp")}} se a versão prefixada do método foi utilizada DOMTimeStamp possui apenas precisão de milisegundo, mas DOMHighResTimeStamp possui precisão mínima de microsegundos.  Portanto, o tempo zero é diferente: DOMHighResTimeStamp possui o mesmo tempo zero que performance.now(), mas DOMTimeStamp possui o mesmo tempo zero que Date.now().

+ +

[3] A chamada correta no Chrome para cancelar a requisição é currently window.cancelAnimationFrame(). Versões anteriores, window.webkitCancelAnimationFrame() e window.webkitCancelRequestAnimationFrame(), foram descontinuados mas possuem suporte por enquanto.

+ +

[4] Suporte para a versão prefixada foi removida no Firefox 42.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/requestidlecallback/index.html b/files/pt-br/web/api/window/requestidlecallback/index.html new file mode 100644 index 0000000000..cdd2485d84 --- /dev/null +++ b/files/pt-br/web/api/window/requestidlecallback/index.html @@ -0,0 +1,70 @@ +--- +title: window.requestIdleCallback() +slug: Web/API/Window/requestIdleCallback +translation_of: Web/API/Window/requestIdleCallback +--- +
{{APIRef("HTML DOM")}}{{SeeCompatTable}}
+ +

O método window.requestIdleCallback() enfileira uma função para ser executado durante períodos onde o navegador está ocioso. Isso permite que desenvolvedores realizem tarefas de baixa prioridade em relação a o event loop em segundo plano. As funções são geralmente chamadas na ordem first-in-first-out (primeiro-a-entrar-primeiro-a-sair); Contudo, callbacks nos quais tem um timeout especificado, podem ser chamados na ordem out-of-order (fora-de-ordem) se necessário, afim de executar antes do tempo limite.

+ +

Você pode chamar requestIdleCallback() com uma função callback ociosa para agendar outro callback para ter lugar não antes da próxima passagem pelo event loop.

+ +
Um timeout é altamento recomendado, caso contrário, é possível que vários segundos passem antes que a função callback seja chamada.
+ +

Syntax

+ +
var handle = window.requestIdleCallback(callback[, options])
+ +

Return value

+ +

An ID which can be used to cancel the callback by passing it into the {{domxref("window.cancelIdleCallback()")}} method.

+ +

Parameters

+ +
+
callback
+
A reference to a function that should be called in the near future, when the event loop is idle. The callback function is passed an {{domxref("IdleDeadline")}} object describing the amount of time available and whether or not the callback has been run because the timeout period expired.
+
options {{optional_inline}}
+
Contains optional configuration parameters. Currently only one property is defined: +
    +
  • timeout: If timeout is specified and has a positive value, and the callback has not already been called by the time timeout milliseconds have passed, the callback will be called during the next idle period, even if doing so risks causing a negative performance impact.
  • +
+
+
+ +

Example

+ +

See our complete example in the article Cooperative Scheduling of Background Tasks API.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Background Tasks')}}{{Spec2('Background Tasks')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Window.requestIdleCallback")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/window/resize_event/index.html b/files/pt-br/web/api/window/resize_event/index.html new file mode 100644 index 0000000000..ac5214b5a2 --- /dev/null +++ b/files/pt-br/web/api/window/resize_event/index.html @@ -0,0 +1,190 @@ +--- +title: resize +slug: Web/API/Window/resize_event +translation_of: Web/API/Window/resize_event +--- +

O evento resize é disparado quando o document view é redimensionado.

+ +

O evento manipulador pode ser registrado para o evento resize usando o atributo window.onresize ou usando window.addEventListener('resize', ...) 

+ +

Em alguns browsers mais recentes é possível registrar o evento manipulador resize em qualquer elemento HTML.  E ainda é possível adicionar atributos onresize ou usar {{domxref("EventTarget.addEventListener", "addEventListener()")}} para implementar o manipulador em qualquer elemento.  Entretanto, eventos resize  apenas são disparados sobre (enviados para) o objeto {{domxref("Window", "window")}} ({{domxref("document.defaultView")}}). Apenas manipuladores registrados no objeto window recebem os eventos.

+ +

Existe uma nova proposta (2017) para permitir que todos os elementos sejam notificados de alterações de tamanho.  Veja Resize Observer para ler o documento rascunho, e Github issues para ler as discussões do que está ativo.

+ +

Informações gerais

+ +
+
Specifications
+
DOM L3, CSSOM View
+
Interface
+
UIEvent
+
Bubbles
+
Não
+
Cancelable
+
Não
+
Target
+
defaultView (window)
+
Default Action
+
Nenhuma
+
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetO evento alto (o primeiro alvo na árvore DOM).
type {{readonlyInline}}DOMStringO tipo de evento.
bubbles {{readonlyInline}}BooleanSe o evento normalmente bubbles ou não.
cancelable {{readonlyInline}}BooleanSe o evento é cancelado ou não.
view {{readonlyInline}}WindowProxydocument.defaultView (window do documento)
detail {{readonlyInline}}long (float)0.
+ +

Examples

+ +

Como os eventos resize podem ser altamente executados, o evento manipulador não deve executar operações computacionais caras como modificações DOM. Em vez disso, recomenda-se diminuir o impacto do evento usando requestAnimationFrame, setTimeout ou customEvent*, como a seguir:
+
+ * IMPORTANT: Por favor note que IE11 precisa do customEvent polyfill para funcionar corretamente.

+ +

requestAnimationFrame + customEvent

+ +
(function() {
+    var throttle = function(type, name, obj) {
+        obj = obj || window;
+        var running = false;
+        var func = function() {
+            if (running) { return; }
+            running = true;
+             requestAnimationFrame(function() {
+                obj.dispatchEvent(new CustomEvent(name));
+                running = false;
+            });
+        };
+        obj.addEventListener(type, func);
+    };
+
+    /* init - you can init any event */
+    throttle("resize", "optimizedResize");
+})();
+
+// handle event
+window.addEventListener("optimizedResize", function() {
+    console.log("Resource conscious resize callback!");
+});
+
+ +

requestAnimationFrame

+ +
var optimizedResize = (function() {
+
+    var callbacks = [],
+        running = false;
+
+    // fired on resize event
+    function resize() {
+
+        if (!running) {
+            running = true;
+
+            if (window.requestAnimationFrame) {
+                window.requestAnimationFrame(runCallbacks);
+            } else {
+                setTimeout(runCallbacks, 66);
+            }
+        }
+
+    }
+
+    // run the actual callbacks
+    function runCallbacks() {
+
+        callbacks.forEach(function(callback) {
+            callback();
+        });
+
+        running = false;
+    }
+
+    // adds callback to loop
+    function addCallback(callback) {
+
+        if (callback) {
+            callbacks.push(callback);
+        }
+
+    }
+
+    return {
+        // public method to add additional callback
+        add: function(callback) {
+            if (!callbacks.length) {
+                window.addEventListener('resize', resize);
+            }
+            addCallback(callback);
+        }
+    }
+}());
+
+// start process
+optimizedResize.add(function() {
+    console.log('Resource conscious resize callback!')
+});
+
+ +

setTimeout

+ +
(function() {
+
+  window.addEventListener("resize", resizeThrottler, false);
+
+  var resizeTimeout;
+  function resizeThrottler() {
+    // ignore resize events as long as an actualResizeHandler execution is in the queue
+    if ( !resizeTimeout ) {
+      resizeTimeout = setTimeout(function() {
+        resizeTimeout = null;
+        actualResizeHandler();
+
+       // The actualResizeHandler will execute at a rate of 15fps
+       }, 66);
+    }
+  }
+
+  function actualResizeHandler() {
+    // handle the resize event
+    ...
+  }
+
+}());
diff --git a/files/pt-br/web/api/window/scroll/index.html b/files/pt-br/web/api/window/scroll/index.html new file mode 100644 index 0000000000..01ece16bbd --- /dev/null +++ b/files/pt-br/web/api/window/scroll/index.html @@ -0,0 +1,57 @@ +--- +title: Window.scroll() +slug: Web/API/Window/scroll +tags: + - API + - CSSOM View + - Referencia + - metodo +translation_of: Web/API/Window/scroll +--- +
{{APIRef}}
+ +

Resumo

+ +

Rola a janela para uma posição específica no documento.

+ +

Sintaxe

+ +
window.scroll(x-coord, y-coord)
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
<!-- disponha o centésimo pixel vertical no topo da janela -->
+
+<button onClick="scroll(0, 100);">clique para rolar 100 pixels para baixo</button>
+
+ +

Notas

+ +

window.scrollTo é essencialmente equivalente a este método. Para rolar uma distância específica repetidamente, utilize o método window.scrollBy. Veja também window.scrollByLines, window.scrollByPages.

+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSSOM View', '#dom-window-scroll', 'window.scroll()') }}{{ Spec2('CSSOM View') }}Definição inicial.
diff --git a/files/pt-br/web/api/window/scrollby/index.html b/files/pt-br/web/api/window/scrollby/index.html new file mode 100644 index 0000000000..c3ee906d33 --- /dev/null +++ b/files/pt-br/web/api/window/scrollby/index.html @@ -0,0 +1,53 @@ +--- +title: Window.scrollBy() +slug: Web/API/Window/scrollBy +translation_of: Web/API/Window/scrollBy +--- +

{{ APIRef() }}

+ +

Resumo

+ +

Desloca o documento dentro da janela pelo valor fornecido.

+ +

Sintaxe

+ +
window.scrollBy(X, Y);
+
+ +

Parâmetros

+ + + +

Coordenadas positivas deslocarão para a direita e para baixo. Coordenadas negativas deslocarão para a esquerda e para cima.

+ +

Exemplo

+ +
// Desloca a altura interna da janela
+window.scrollBy(0, window.innerHeight);
+
+ +

Notas

+ +

window.scrollBy desloca uma quantidade específical enquanto window.scroll desloca para uma posição absoluta no documento. Veja Também window.scrollByLines, window.scrollByPages

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-scrollby', 'window.scrollBy()') }}{{ Spec2('CSSOM View') }}Initial definition.
diff --git a/files/pt-br/web/api/window/scrollbypages/index.html b/files/pt-br/web/api/window/scrollbypages/index.html new file mode 100644 index 0000000000..1ad5c70c47 --- /dev/null +++ b/files/pt-br/web/api/window/scrollbypages/index.html @@ -0,0 +1,41 @@ +--- +title: Window.scrollByPages() +slug: Web/API/Window/scrollByPages +translation_of: Web/API/Window/scrollByPages +--- +

{{ ApiRef() }}{{Non-standard_header}}

+ +

Resumo

+ +

Rola o documento atual para a página especificada.

+ +

Sintaxe

+ +
window.scrollByPages(pages)
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
// rola o documento para baixo até a página 1
+window.scrollByPages(1);
+
+// rola o documento para cima até a página 1
+window.scrollByPages(-1);
+
+ +

Notas

+ +

Veja também window.scrollBy, window.scrollByLines, window.scroll, window.scrollTo.

+ +

Specification

+ +

DOM Level 0. Not part of specification.

+ +

{{ languages( { "ja": "ja/DOM/window.scrollByPages", "pl": "pl/DOM/window.scrollByPages", "zh-cn": "zh-cn/DOM/window.scrollByPages" } ) }}

diff --git a/files/pt-br/web/api/window/scrollto/index.html b/files/pt-br/web/api/window/scrollto/index.html new file mode 100644 index 0000000000..10d844a41f --- /dev/null +++ b/files/pt-br/web/api/window/scrollto/index.html @@ -0,0 +1,56 @@ +--- +title: Window.scrollTo() +slug: Web/API/Window/scrollTo +tags: + - API + - CSSOM View + - NeedsCompatTable + - NeedsMarkupWork + - NeedsSpecTable + - Referencia + - metodo +translation_of: Web/API/Window/scrollTo +--- +
{{ APIRef }}
+ +

Resumo

+ +

Realiza a rolagem para um conjunto de coordenadas em particular em um documento.

+ +

Sintaxe

+ +
window.scrollTo(x-coord, y-coord)
+ +

Parâmetros

+ + + +

Exemplo

+ +
window.scrollTo( 0, 1000 );
+ +

Notas

+ +

Essa função é efetivamente a mesma que window.scroll. Para rolagem relativa, veja window.scrollBy, window.scrollByLines e window.scrollByPages.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSSOM View', '#dom-window-scroll', 'window.scroll()') }}{{ Spec2('CSSOM View') }}Definição inicial.
diff --git a/files/pt-br/web/api/window/scrolly/index.html b/files/pt-br/web/api/window/scrolly/index.html new file mode 100644 index 0000000000..28d7fd8797 --- /dev/null +++ b/files/pt-br/web/api/window/scrolly/index.html @@ -0,0 +1,76 @@ +--- +title: Window.scrollY +slug: Web/API/Window/scrollY +translation_of: Web/API/Window/scrollY +--- +
{{APIRef}}
+ +

Sumário

+ +

Retorna o número de pixels que o documento já rolou verticalmente.

+ +

Sintaxe

+ +
var y = window.scrollY;
+
+ + + +

Exemplo

+ +
// verificar e ir para a segunda página
+if (window.scrollY) {
+  window.scroll(0, 0);  // reinicia a posição do scroll para a posição superior esquerda do documento.
+}
+
+window.scrollByPages(1);
+ +

Notas

+ +

Utilize esta propriedade para verificar se o documento já foi rolado quando funções de rolagem relativa, tais como {{domxref("window.scrollBy")}}, {{domxref("window.scrollByLines")}}, ou {{domxref("window.scrollByPages")}}, forem utilizadas.

+ +

A propriedade pageYOffset é um alias para scrollY:

+ +
window.pageYOffset == window.scrollY; // always true
+ +

For cross-browser compatibility, use window.pageYOffset instead of window.scrollY. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. A fully compatible example:

+ +

Para compatibilidade cross-browser, utilize window.pageYOffset em vez de window.scrollY. Além disso, versões inferiores do Internet Explorer 9 não suportam ambas as propriedades, e deve ser contornado verificando outras propriedades não padronizadas.

+ +
var supportPageOffset = window.pageXOffset !== undefined;
+var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
+
+var x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft;
+var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
+
+ +

Especificação

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-scrolly', 'window.scrollY') }}{{ Spec2('CSSOM View') }}
+ +

Browser compatibility

+ +

{{Compat("api.Window.scrollY")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/sessionstorage/index.html b/files/pt-br/web/api/window/sessionstorage/index.html new file mode 100644 index 0000000000..b387b8af5b --- /dev/null +++ b/files/pt-br/web/api/window/sessionstorage/index.html @@ -0,0 +1,143 @@ +--- +title: Window.sessionStorage +slug: Web/API/Window/sessionStorage +tags: + - Armazenamento + - Propriedade + - Referencia + - Sessão +translation_of: Web/API/Window/sessionStorage +--- +

{{APIRef()}}

+ +

A propriedade sessionStorage permite acessar um objeto tipo session {{domxref("Storage")}}. A sessionStorage é similar ao localStorage, a única diferença é que enquanto os dados armazenados no localStorage não expiram, os dados no sessionstorage tem os seus dados limpos ao expirar a sessão da página. A sessão da página dura enquanto o browser está aberto e se mantém no recarregamento da página. Abrir a página em uma nova aba ou nova janela irá gerar uma nova sessão, o que diferencia de como os cookies trabalham.

+ +

Sintaxe

+ +
// Salva os dados na sessionStorage
+sessionStorage.setItem('chave', 'valor');
+
+// Obtém os dados da sessionStorage
+var data = sessionStorage.getItem('chave');
+ +

Valor

+ +

Objeto {{domxref("Storage")}}.

+ +

Exemplo

+ +

O seguinte trecho acessa o objeto da sessão do domínio atual {{domxref("Storage")}} e adiciona um item usando o {{domxref("Storage.setItem()")}}.

+ +
sessionStorage.setItem('myCat', 'Tom');
+ +

O exemplo a seguir salva automaticamente o conteúdo da caixa de texto, e caso o browser seja acidentalmente recarregado, o conteúdo da caixa de texto é restaurado.

+ +
// Obtem a caixa de texto que vamos rastrear
+var field = document.getElementById("campo");
+
+// Se tivermos um valor salvo automaticamente
+// (isto só ocorrerá se a página for acidentalmente recarregada)
+if (sessionStorage.getItem("autosave")) {
+  // Restaura o conteúdo da caixa de texto
+  field.value = sessionStorage.getItem("autosave");
+}
+
+// Verifica as mudanças que ocorrem na caixa de texto
+field.addEventListener("change", function() {
+  // E salva o resultado dentro de um objeto session storage
+  sessionStorage.setItem("autosave", field.value);
+});
+ + + +
+

Nota: Por favor use o artigo Using the Web Storage API para um exemplo completo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentários
{{SpecName('Web Storage', '#the-sessionstorage-attribute', 'sessionStorage')}}{{Spec2('Web Storage')}}
+ +

Browser compatíveis

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

Cada browser tem o seu nível de capacidade de armazenamento para localStorage e sessionStorage. Aqui está um teste detalhado de toda a capacidade de armazenamento de vários browsers.

+ +
+

Nota: desde o iOS 5.1, Safari Mobile armazena os dados do localStorage em uma pasta de cache, o que está sujeito a ocasionalmente ser limpa, de acordo com o SO, se houver pouco espaço.

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/setcursor/index.html b/files/pt-br/web/api/window/setcursor/index.html new file mode 100644 index 0000000000..d85dfb7c01 --- /dev/null +++ b/files/pt-br/web/api/window/setcursor/index.html @@ -0,0 +1,28 @@ +--- +title: Window.setCursor() +slug: Web/API/Window/setCursor +translation_of: Web/API/Window/setCursor +--- +
{{ ApiRef() }}
+ +
 
+ +

Sumário

+ +

Altera o cursor para a janela atual.

+ +

Exemplo

+ +
function setBusyCursor(enable) {
+  window.setCursor(enable ? "wait" : "auto");
+}
+ +

Notas

+ +

O cursor não retornará ao seu padrão até que seja definido novamente para auto.

+ +

Esta função é parte do ChromeWindow interface. Esta função não está habilitada para páginas web, que podem usar a propriedade CSS {{cssxref("cursor")}} em seu lugar.

+ +

Especificação

+ +

{{dom0}}

diff --git a/files/pt-br/web/api/window/setimmediate/index.html b/files/pt-br/web/api/window/setimmediate/index.html new file mode 100644 index 0000000000..693c51619b --- /dev/null +++ b/files/pt-br/web/api/window/setimmediate/index.html @@ -0,0 +1,107 @@ +--- +title: Window.setImmediate() +slug: Web/API/Window/setImmediate +translation_of: Web/API/Window/setImmediate +--- +
{{APIRef("HTML DOM")}}{{Non-standard_header}}
+ +

Esse método é usado para interromper operações de longa duração e executar uma função de retorno de chamada imediatamente após o navegador ter concluído outras operações, como eventos e atualizações de exibição.

+ +
Não se espera que este método se torne padrão, e é implementado somente por compilações recentes do Internet Explorer e Node.js 0.10+. Existem resistencias de ambos Gecko (Firefox) e Webkit (Google/Apple).
+ +

Sintaxe

+ +
var immediateID = setImmediate(func, [param1, param2, ...]);
+var immediateID = setImmediate(func);
+
+ + + +

Todos parametros serão passados diretamente para sua função .

+ +

Notas

+ +

O método {{ domxref("window.clearImmediate") }} pode ser usado para limpar as ações immediate, como por exemplo {{ domxref("window.clearTimeout") }} para {{ domxref("window.setTimeout") }}.

+ +

Esse método pode ser usado ao invés de setTimeout(fn, 0), para executar operações pesadas

+ +

Essa função pode ser emulada de algumas maneiras:

+ + + +

Todas essas técnicas são incorporadas em um setImmediate polyfill.

+ +

Especificações

+ +

Não faz parte de nenhuma especificação e não em uma faixa de padrões.

+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo }}{{CompatVersionUnknown}}{{ CompatNo }}10{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo }}{{CompatVersionUnknown}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

Ver também

+ +

{{ domxref("window.clearImmediate") }}

+ +

{{ spec("https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html", "Specification: Efficient Script Yielding") }}

+ +

Microsoft setImmediate API Demo

+ +

{{ languages( { "zh-cn": "zh-cn/DOM/window.setImmediate" } ) }}

diff --git a/files/pt-br/web/api/window/url/index.html b/files/pt-br/web/api/window/url/index.html new file mode 100644 index 0000000000..5c673ed4b6 --- /dev/null +++ b/files/pt-br/web/api/window/url/index.html @@ -0,0 +1,100 @@ +--- +title: Window.URL +slug: Web/API/Window/URL +translation_of: Web/API/URL +--- +

{{ApiRef("Window")}}{{SeeCompatTable}}

+ +

A propriedade Window.URL retorna um objeto que fornece métodos estáticos usados para criar e gerenciar URLs de objeto. Também pode ser chamado como um construtor para construir objetos {{domxref("URL")}}.

+ +

{{AvailableInWorkers}}

+ +

Sintaxe

+ +

Chamando um método estático:

+ +
img.src = URL.{{domxref("URL.createObjectURL", "createObjectURL")}}(blob);
+ +

Construindo um novo objeto:

+ +
var url = new {{domxref("URL.URL", "URL")}}("../cats/", "https://www.example.com/dogs/");
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('URL', '#dom-url', 'URL')}}{{Spec2('URL')}}Initial definition
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support8.0[2]{{CompatGeckoDesktop("2.0")}}[1]
+ {{CompatGeckoDesktop("19.0")}}
10.015.0[2]6.0[2]
+ 7.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}[2]{{CompatGeckoMobile("14.0")}}[1]
+ {{CompatGeckoMobile("19.0")}}
{{CompatVersionUnknown}}15.0[2]6.0[2]
+
+ +

[1] Do Gecko 2 (Firefox 4) ao Gecko 18 incluído, o Gecko retornou um objeto com o tipo interno nsIDOMMozURLProperty não padrão. Na prática, isso não fez diferença.

+ +

[2] Implementado sob o nome não padronizado webkitURL.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/window.localstorage/index.html b/files/pt-br/web/api/window/window.localstorage/index.html new file mode 100644 index 0000000000..8c7c379435 --- /dev/null +++ b/files/pt-br/web/api/window/window.localstorage/index.html @@ -0,0 +1,123 @@ +--- +title: Window.localStorage +slug: Web/API/Window/Window.localStorage +tags: + - API + - Armazenamento + - Propriedade + - Referencia + - WindowLocalStorage + - localStorage +translation_of: Web/API/Window/localStorage +--- +

{{APIRef()}}

+ +

A propriedade localStorage permite acessar um objeto {{domxref("Storage")}} local. A localStorage é similar ao sessionStorage. A única diferença é que enquanto os dados armazenados no localStorage não expiram, os dados no sessionStorage tem os seus dados limpos ao expirar a sessão da página — ou seja, quando a página (aba ou janela) é fechada.

+ +

Sintaxe

+ +
meuStorage = localStorage;
+ +

Valor

+ +

Objeto {{domxref("Storage")}}.

+ +

Exemplo

+ +

O seguinte trecho acessa o objeto {{domxref("Storage")}} local do domínio atual e adiciona um item usando o {{domxref("Storage.setItem()")}}.

+ +
localStorage.setItem('meuGato', 'Tom');
+ +
+

Nota: Por favor veja o artigo Using the Web Storage API para um exemplo completo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Storage', '#dom-localstorage', 'localStorage')}}{{Spec2('Web Storage')}} 
+ + + +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

Cada navegador tem o seu nível de capacidade de armazenamento para localStorage e {{domxref("sessionStorage")}}. Aqui está um teste detalhado de toda a capacidade de armazenamento de vários browsers.

+ +
+

Nota: desde o iOS 5.1, Safari Mobile armazena os dados do localStorage em uma pasta de cache, o que está sujeito a ocasionalmente ser limpa, de acordo com o SO, se houver pouco espaço. O modo de Navegação Privada do Safari Mobile não permite escrever no localStorage de forma alguma.

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/windowbase64/atob/index.html b/files/pt-br/web/api/windowbase64/atob/index.html new file mode 100644 index 0000000000..cb9058abe5 --- /dev/null +++ b/files/pt-br/web/api/windowbase64/atob/index.html @@ -0,0 +1,72 @@ +--- +title: WindowBase64.atob() +slug: Web/API/WindowBase64/atob +tags: + - API + - Referencia + - WindowBase64 + - metodo +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +--- +
{{APIRef("HTML DOM")}}
+ +

A função WindowBase64.atob() decodifica uma string de dados que foi codificada através da codificação base-64. Você pode usar o método {{domxref("WindowBase64.btoa","window.btoa()")}} para codificar e transmitir dados que, se não codificados, podem causar problemas de comunicação. Após transmití-los pode-se usar o método window.atob() para decodificar os dados novamente. Por exemplo, você pode codificar, transmitir,  e decodificar caracteres de controle como valores ASCII de 0 a 31.

+ +

Para utilizar com strings Unicode ou UTF-8, veja esta nota em Base64 encoding and decoding e essa nota em window.btoa().

+ +

Sintaxe

+ +
var dadoDecodificado = window.atob(dadoCodificado);
+ +

Exemplo

+ +
var dadoCodificado = window.btoa("Olá, mundo"); // codifica a string
+var dadoDecodificado = window.atob(dadoCodificado); // decodifica a string
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}Nenhuma mudança desde a última versão, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Versão de {{SpecName("HTML WHATWG")}}. Nenhuma mudança.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Versão de {{SpecName("HTML WHATWG")}}. Criação do WindowBase64 (antes as propriedades ficavam no target).
+ +

Compatibilidade de navegadores

+ +
{{Compat("api.WindowOrWorkerGlobalScope.atob")}}
+ +
+ +

[1] atob() também está disponível para os componentes do XPCOM implementado em JavaScript, porém o objeto window não é global nos componentes.

+ +

[2] A partir do Firefox 27, atob() ignora todos os caracteres de espaço no argumento para seguir as últimas especificações do HTML5. ({{bug(711180)}})

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/windowbase64/index.html b/files/pt-br/web/api/windowbase64/index.html new file mode 100644 index 0000000000..40051820b4 --- /dev/null +++ b/files/pt-br/web/api/windowbase64/index.html @@ -0,0 +1,120 @@ +--- +title: WindowBase64 +slug: Web/API/WindowBase64 +tags: + - API + - HTML-DOM + - Helper + - NeedsTranslation + - TopicStub + - WindowBase64 +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +

{{APIRef("HTML DOM")}}

+ +

The WindowBase64 helper contains utility methods to convert data to and from base64, a binary-to-text encoding scheme. For example it is used in data URIs.

+ +

There is no object of this type, though the context object, either the {{domxref("Window")}} for regular browsing scope, or the {{domxref("WorkerGlobalScope")}}  for workers, implements it.

+ +

Properties

+ +

This helper neither defines nor inherits any properties.

+ +

Methods

+ +

This helper does not inherit any methods.

+ +
+
{{domxref("WindowBase64.atob()")}}
+
Decodes a string of data which has been encoded using base-64 encoding.
+
{{domxref("WindowBase64.btoa()")}}
+
Creates a base-64 encoded ASCII string from a string of binary data.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windowbase64', 'WindowBase64')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windowbase64', 'WindowBase64')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#windowbase64", "WindowBase64")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(1)}} [1]{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1]  atob() is also available to XPCOM components implemented in JavaScript, even though {{domxref("Window")}} is not the global object in components.

+ +

See also

+ + diff --git a/files/pt-br/web/api/windoweventhandlers/index.html b/files/pt-br/web/api/windoweventhandlers/index.html new file mode 100644 index 0000000000..5eff621233 --- /dev/null +++ b/files/pt-br/web/api/windoweventhandlers/index.html @@ -0,0 +1,189 @@ +--- +title: WindowEventHandlers +slug: Web/API/WindowEventHandlers +tags: + - API + - HTML-DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/WindowEventHandlers +--- +
{{APIRef("HTML DOM")}}
+ +

WindowEventHandlers descreve os manipuladores de eventos comuns a várias interfaces como {{domxref("Window")}}, ou {{domxref("HTMLBodyElement")}} e  {{domxref("HTMLFrameSetElement")}}. Cada uma dessas interfaces podendo implementar manipuladores de eventos específicos adicionais.

+ +

WindowEventHandlers não é uma interface e nenhum objeto desse tipo pode ser criado.

+ +

Properties

+ +

As propriedades de evento, no formulário onXYZ, são definidas no {{domxref("WindowEventHandlers")}}, e implementadas por {{domxref("Window")}}, e {{domxref("WorkerGlobalScope")}} para desenvolvedores web.

+ +
+
{{domxref("WindowEventHandlers.onafterprint")}}
+
É uma {{domxref("EventHandler")}} representando o código que será chamando quando o evento {{event("afterprint")}} é invocado.
+
{{domxref("WindowEventHandlers.onbeforeprint")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("beforeprint")}} é invocado.
+
{{domxref("WindowEventHandlers.onbeforeunload")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento  {{event("beforeunload")}} é invocado.
+
{{domxref("WindowEventHandlers.onhashchange")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("hashchange")}} é invocado.
+
{{domxref("WindowEventHandlers.onlanguagechange")}} {{experimental_inline}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("languagechange")}} é invocado.
+
{{domxref("WindowEventHandlers.onmessage")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento  {{event("message")}} é invocado.
+
{{domxref("WindowEventHandlers.onoffline")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento  {{event("offline")}} é invocado.
+
{{domxref("WindowEventHandlers.ononline")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento  {{event("online")}} é invocado.
+
{{domxref("WindowEventHandlers.onpagehide")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("pagehide")}} é invocado.
+
{{domxref("WindowEventHandlers.onpageshow")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("pageshow")}} é invocado.
+
{{domxref("WindowEventHandlers.onpopstate")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("popstate")}} é invocado.
+
{{domxref("WindowEventHandlers.onresize")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("resize")}} é invocado.
+
{{domxref("WindowEventHandlers.onstorage")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("storage")}} é invocado.
+
{{domxref("WindowEventHandlers.onunload")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("unload")}} é invocado.
+
+ +

Métodos

+ +

Esta interface não define métodos.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. Added onlanguage since the {{SpecName("HTML 5")}} snapshot.
{{SpecName("HTML5 W3C", "#windoweventhandlers", "GlobalEventHandlers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowEventHandlers (properties where on the target before it).
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onhashchange{{CompatGeckoDesktop(1.9.2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onlanguage{{experimental_inline}}{{CompatGeckoDesktop(32)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onstorage{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onhashchange{{CompatGeckoMobile(1.9.2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onlanguage{{experimental_inline}}{{CompatGeckoMobile(32)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onstorage{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/windoweventhandlers/onhashchange/index.html b/files/pt-br/web/api/windoweventhandlers/onhashchange/index.html new file mode 100644 index 0000000000..5cca998fbe --- /dev/null +++ b/files/pt-br/web/api/windoweventhandlers/onhashchange/index.html @@ -0,0 +1,158 @@ +--- +title: WindowEventHandlers.onhashchange +slug: Web/API/WindowEventHandlers/onhashchange +translation_of: Web/API/WindowEventHandlers/onhashchange +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

O evento hashchange é disparado quando a hash da window muda. (ver {{domxref("Window.location", "location.hash")}}).

+ +

Sintaxe

+ +
window.onhashchange = funcRef;
+
+ +

ou

+ +
<body onhashchange="funcRef();">
+
+ +

ou

+ +
window.addEventListener("hashchange", funcRef, false);
+
+ +

Parâmetros

+ +
+
funcRef
+
Referência a uma função
+
+ +

Exemplo

+ +
if ("onhashchange" in window) {
+    alert("O browser têm suporte ao evento hashchange!");
+}
+
+function locationHashChanged() {
+    if (location.hash === "#algointeressante") {
+        algoInteressante();
+    }
+}
+
+window.onhashchange = locationHashChanged;
+
+ +

O evento hashchange

+ +

O evento hashchange disparado possui os seguintes campos

+ + + + + + + + + + + + + + + + + + + +
CampoTipoDescrição
newURL {{gecko_minversion_inline("6.0")}}DOMStringA nova URL para a qual a janela está navegando.
oldURL {{gecko_minversion_inline("6.0")}}DOMStringA antiga URL da qual a janela veio.
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML5.1')}} 
{{SpecName("HTML5 W3C", "#windoweventhandlers", "GlobalEventHandlers")}}{{Spec2('HTML5 W3C')}} 
+ +

Compatibilidade dos Browsers

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico5.0{{CompatGeckoDesktop("1.9.2")}} +

8.0

+ +

atributos oldURL/newURL não são suportados.

+
10.65.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico2.2{{CompatGeckoMobile("1.9.2")}}9.011.05.0
+
+ + diff --git a/files/pt-br/web/api/windoweventhandlers/onpopstate/index.html b/files/pt-br/web/api/windoweventhandlers/onpopstate/index.html new file mode 100644 index 0000000000..78bfa8fdc1 --- /dev/null +++ b/files/pt-br/web/api/windoweventhandlers/onpopstate/index.html @@ -0,0 +1,61 @@ +--- +title: WindowEventHandlers.onpopstate +slug: Web/API/WindowEventHandlers/onpopstate +translation_of: Web/API/WindowEventHandlers/onpopstate +--- +
{{APIRef}} {{gecko_minversion_header("2")}}
+ +

Sumário

+ +

Um evento manipulador para um evento popstate na janela

+ +

Um evento popstate é disparado para a janela toda vez que o histórico de atividades mudar entre dois históricos de entradas para o mesmo documento. Se o histórico de entrada a ser ativo for criado por uma chamada para history.pushState() ou for afetado por um chamada history.replaceState(), o estado do evento popstate contém uma cópia do histórico do estado de entrada do objeto.

+ +

Note que apenas chamando history.pushState() ou history.replaceState() não irá desencadear um evento popstate. O evento popstate é apenas desencadeado  por uma ação do navegador com clicar em um botão de voltar (ou chamar history.back() em JavaScript). E o evento é apenas desencadeado quando o usuário navega entre dois históricos de entrada do mesmo documento.
+
+ Navegadores tendem a lidar com o evento popstate diferente no carregamento da página. Chrome (anterior versão 34) e Safari sempre emite um evento popstate no carregamento da página, mas Firefox não.

+ +

Sintaxe

+ +
window.onpopstate = funcRef;
+
+ + + +

O evento popstate

+ +

Como um exemplo, a página no http://example.com/example.html roda o seguinte código que vai gerar alertas conforme indicado:

+ +
window.onpopstate = function(event) {
+  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
+};
+
+history.pushState({page: 1}, "title 1", "?page=1");
+history.pushState({page: 2}, "title 2", "?page=2");
+history.replaceState({page: 3}, "title 3", "?page=3");
+history.back(); // alertas "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back(); // alertas "location: http://example.com/example.html, state: null
+history.go(2);  // alertas "location: http://example.com/example.html?page=3, state: {"page":3}
+
+ +
+
Observe que mesmo que a entrada do histórico inicial (para http://example.com/example.html) não tem objeto estado associado com ele, um evento popstate é ainda disparado quando nós ativamos essa entrada depois da segunda chamada do history.back().
+
+
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/windoweventhandlers/onstorage/index.html b/files/pt-br/web/api/windoweventhandlers/onstorage/index.html new file mode 100644 index 0000000000..48820c0bfa --- /dev/null +++ b/files/pt-br/web/api/windoweventhandlers/onstorage/index.html @@ -0,0 +1,101 @@ +--- +title: WindowEventHandlers.onstorage +slug: Web/API/WindowEventHandlers/onstorage +tags: + - API + - Armazenamento web + - Propriedade + - Referencia + - WindowEventHandlers +translation_of: Web/API/WindowEventHandlers/onstorage +--- +
{{ ApiRef() }}
+ +

A propriedade WindowEventHandlers.onstorage contém um manipulador de eventos que executa quando o evento {{event("storage")}} dispara. Isto ocorre quando a área de armazenamento é mudada. (ex. um novo item é armazenado.)

+ +

Sintaxe

+ +
windowObj.onstorage = function() { ... };
+ +

Exemplos

+ +
window.onstorage = function(e) {
+  console.log('The ' + e.key + ' key has been changed from ' + e.oldValue + ' to ' + e.newValue + '.');
+};
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','webappapis.html#handler-window-onstorage','onstorage')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome para Android
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/windoworworkerglobalscope/fetch/index.html b/files/pt-br/web/api/windoworworkerglobalscope/fetch/index.html new file mode 100644 index 0000000000..804f04fc45 --- /dev/null +++ b/files/pt-br/web/api/windoworworkerglobalscope/fetch/index.html @@ -0,0 +1,305 @@ +--- +title: WindowOrWorkerGlobalScope.fetch() +slug: Web/API/WindowOrWorkerGlobalScope/fetch +translation_of: Web/API/WindowOrWorkerGlobalScope/fetch +--- +
{{APIRef("Fetch API")}}
+ +

O método fetch() do mixin {{domxref("WindowOrWorkerGlobalScope")}} inicia um processo de busca de um recurso da rede. Este, retorna uma promessa que resolve o objeto {{domxref("Response")}} que representa a resposta a sua requisição. 

+ +

WorkerOrGlobalScope é implementado por {{domxref("Window")}} e {{domxref("WorkerGlobalScope")}}, o que significa que o método fetch() está disponível em praticamente qualquer contexto em que você possa querer obter recursos.

+ +

Uma promessa {{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} rejeita com um {{jsxref("TypeError")}} quando um erro de rede é encontrado, embora isso geralmente signifique um problema de permissões ou similar. Uma verificação precisa de um fetch() bem-sucedido incluiria a verificação de uma promessa resolvida, e depois verificando se a propriedade {{domxref("Response.ok")}} possui valor true. Um status HTTP 404 não constitui um erro de rede.

+ +

O método fetch() é controlado pela diretiva connect-src da Content Security Policy em vez da diretiva dos recursos que está recuperando.

+ +
+

Nota: Os parâmetros do método fetch() são idênticos aos do construtor {{domxref("Request.Request","Request()")}}.

+
+ +

Sintaxe

+ +
Promise<Response> fetch(input[, init]);
+ +

Parâmetros

+ +
+
input
+
Isto define o recurso que você deseja buscar. Isto pode ser: +
    +
  • Um {{domxref("USVString")}} contendo uma URL direta para o recurso que você quer obter. Alguns navegadores aceitam blob: e data: como esquemas.
  • +
  • Um objeto {{domxref("Request")}}.
  • +
+
+
init {{optional_inline}}
+
Um objeto opcional que contém configurações personalizadas que você pode aplicar à requisição. As opções possíveis são: +
    +
  • method: Método HTTP, por exemplo, GET, POST.
  • +
  • headers: Qualquer cabeçalho que você queira adicionar à sua requisição, contido dentro de um objeto {{domxref("Headers")}} ou um objeto literal com valores {{domxref("ByteString")}}.
  • +
  • body: Qualquer corpo que você queira adicionar à sua requisição: podendo ser um {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, ou um objeto {{domxref("USVString")}}. Note que uma requisição usando os métodos GET ou HEAD não pode ter um corpo.
  • +
  • mode: O modo que deseja usar para a requisição, por exemplo, cors, no-cors, ou same-origin.
  • +
  • credentials: A credencial que deseja usar para a requisição: omit, same-origin, ou include. Para enviar automaticamente cookies para o domínio atual, esta opção deve ser fornecida. Começando com o Chrome 50, essa propriedade também usa uma instância {{domxref("FederatedCredential")}} ou uma instância {{domxref("PasswordCredential")}}.
  • +
  • cache: O modo de cache que deseja usar na requisição: default, no-store, reload, no-cache, force-cache, ou only-if-cached.
  • +
  • redirect: O modo de redirecionamento pode usar: follow (segue automaticamente o redirecionamento), error (aborta com um erro se ocorrer um redirecionamento), ou manual (manipula redirecionamentos manualmente). No Chrome o padrão foi follow antes do Chrome 47 e manual a partir do Chrome 47.
  • +
  • referrer: Um {{domxref("USVString")}} especificando no-referrerclient, ou uma URL. O padrão é client.
  • +
  • referrerPolicy: Especifica o valor do cabeçalho HTTP referer. Pode ser um destes: no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url.
  • +
  • integrity: Contém o valor de integridade de subrecurso da requisição (por exemplo, sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
  • +
  • signal: Uma instância do objeto {{domxref("FetchSignal")}}; permite que você se comunique com um pedido de busca e controle-o através de um {{domxref("FetchController")}}. {{non-standard_inline}}
  • +
  • observe: Um objeto {{domxref("ObserverCallback")}} — o objetivo exclusivo deste objeto é fornecer uma função de retorno de chamada que é executada quando a solicitação fetch é executada. Isto retorna um objeto {{domxref("FetchObserver")}} que pode ser usado para recuperar informações sobre o status de uma solicitação fetch. {{non-standard_inline}}
  • +
+
+
+ +

Valor de Retorno

+ +

Uma {{domxref("Promise")}} que resolve um objeto {{domxref("Response")}}.

+ +

Exceptions

+ + + + + + + + + + + + + + +
TipoDescrição
TypeErrorDesdo o Firefox 43, fetch()
+ lançará um TypeError se a URL tiver credenciais, como http://user:password@example.com.
+ +

Example

+ +

In our Fetch Request example (see Fetch Request live) we create a new {{domxref("Request")}} object using the relevant constructor, then fetch it using a fetch() call. Since we are fetching an image, we run {{domxref("Body.blob()")}} on the response to give it the proper MIME type so it will be handled properly, then create an Object URL of it and display it in an {{htmlelement("img")}} element.

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  return response.blob();
+}).then(function(response) {
+  var objectURL = URL.createObjectURL(response);
+  myImage.src = objectURL;
+});
+ +

In our Fetch with init then Request example (see Fetch Request init live) we do the same thing except that we pass in an init object when we invoke fetch():

+ +
var myImage = document.querySelector('img');
+
+var myHeaders = new Headers();
+myHeaders.append('Content-Type', 'image/jpeg');
+
+var myInit = { method: 'GET',
+               headers: myHeaders,
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest,myInit).then(function(response) {
+  ...
+});
+ +

Note that you could also pass the init object in with the Request constructor to get the same effect, e.g.:

+ +
var myRequest = new Request('flowers.jpg', myInit);
+ +

You can also use an object literal as headers in init.

+ +
var myInit = { method: 'GET',
+               headers: {
+                   'Content-Type': 'image/jpeg'
+               },
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg', myInit);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}Defined in a WindowOrWorkerGlobalScope partial in the newest spec.
{{SpecName('Fetch','#dom-global-fetch','fetch()')}}{{Spec2('Fetch')}}Initial definition
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}Adds {{domxref("FederatedCredential")}} or {{domxref("PasswordCredential")}} instance as a possible value for init.credentials.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42)}}14{{CompatGeckoDesktop(34)}}[1]
+ {{CompatGeckoDesktop(39)}}
+ {{CompatGeckoDesktop(52)}}[2]
{{CompatNo}}29
+ 28[1]
{{CompatNo}}
Streaming response body{{CompatChrome(43)}}14{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Support for blob: and data:{{CompatChrome(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
referrerPolicy{{CompatChrome(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}
signal and observer{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}[3]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(42)}}14{{CompatGeckoMobile(52)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42)}}
Streaming response body{{CompatNo}}{{CompatChrome(43)}}14{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43)}}
Support for blob: and data:{{CompatNo}}{{CompatChrome(43)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43)}}
referrerPolicy{{CompatNo}}{{CompatChrome(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}{{CompatChrome(52)}}
signal and observer{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}[3]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] API is implemented behind a preference.

+ +

[2] fetch() now defined on {{domxref("WindowOrWorkerGlobalScope")}} mixin.

+ +

[3] Hidden behind a preference in 55+ Nightly. In about:config, you need to create two new boolean prefs — dom.fetchObserver.enabled and dom.fetchController.enabled — and set the values of both to true.

+ +

See also

+ + diff --git a/files/pt-br/web/api/windoworworkerglobalscope/index.html b/files/pt-br/web/api/windoworworkerglobalscope/index.html new file mode 100644 index 0000000000..d1321eb031 --- /dev/null +++ b/files/pt-br/web/api/windoworworkerglobalscope/index.html @@ -0,0 +1,189 @@ +--- +title: WindowOrWorkerGlobalScope +slug: Web/API/WindowOrWorkerGlobalScope +tags: + - API + - DOM + - DOM API + - NeedsTranslation + - Service Worker + - TopicStub + - Window + - WindowOrWorkerGlobalScope + - Worker + - WorkerGlobalScope +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +
{{ApiRef()}}
+ +

O mixin WindowOrWorkerGlobalScope descreve vários recursos comuns às interfaces Window e WorkerGlobalScope. Cada uma dessas interfaces pode, obviamente, adicionar mais recursos além dos listados abaixo.

+ +
+

Nota: WindowOrWorkerGlobalScope é um mixin e não uma interface; você não pode atualmente criar um objeto do tipo WindowOrWorkerGlobalScope.

+
+ +

Properties

+ +

These properties are defined on the {{domxref("WindowOrWorkerGlobalScope")}} mixin, and implemented by {{domxref("Window")}} and {{domxref("WorkerGlobalScope")}}.

+ +
+
+
{{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 origin of the global scope, serialized as a string.
+
+
+ +

Methods

+ +

These properties are defined on the {{domxref("WindowOrWorkerGlobalScope")}} mixin, and implemented by {{domxref("Window")}} and {{domxref("WorkerGlobalScope")}}.

+ +
+
{{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("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.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG",'webappapis.html#windoworworkerglobalscope-mixin', 'WindowOrWorkerGlobalScope mixin')}}{{Spec2('HTML WHATWG')}}This is where the main mixin is defined.
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}Definition of the fetch() method.
{{SpecName('Service Workers', '#self-caches', 'caches')}}{{Spec2('Service Workers')}}Definition of the caches property.
{{SpecName('IndexedDB 2', '#dom-windoworworkerglobalscope-indexeddb', 'indexedDB')}}{{Spec2('IndexedDB 2')}}Definition of the indexedDB property.
{{SpecName('Secure Contexts', 'webappapis.html#dom-origin', 'isSecureContext')}}{{Spec2('Secure Contexts')}}Definition of the isSecureContext property.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(52)}}54{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
origin{{CompatGeckoDesktop(54)}}59{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewEdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}54
origin{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(54)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}59
+
+ +

 

+ +

See also

+ + diff --git a/files/pt-br/web/api/windoworworkerglobalscope/setinterval/index.html b/files/pt-br/web/api/windoworworkerglobalscope/setinterval/index.html new file mode 100644 index 0000000000..b7ade5307d --- /dev/null +++ b/files/pt-br/web/api/windoworworkerglobalscope/setinterval/index.html @@ -0,0 +1,629 @@ +--- +title: WindowOrWorkerGlobalScope.setInterval() +slug: Web/API/WindowOrWorkerGlobalScope/setInterval +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +
{{APIRef("HTML DOM")}}
+ +
 
+ +

O método setInterval() oferecido das interfaces {{domxref("Window")}} e {{domxref("Worker")}}, repetem chamadas de funções or executam trechos de código, com um tempo de espera fixo entre cada chamada. Isso retorna um ID único para o intervalo, podendo remove-lo mais tarde apenas o chamando {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}}. Este metodo é definido pelo mixin {{domxref("WindowOrWorkerGlobalScope")}}.

+ +

Sintaxe.

+ +
var intervalID = scope.setInterval(func, delay[, param1, param2, ...]);
+var intervalID = scope.setInterval(code, delay);
+
+ +

Parâmetros

+ +
+
func
+
Uma {{jsxref("function")}} para ser executada a cada delay em milisegundos.  Não é passado nenhum parâmetro para a função, e não retorna nenhum valor esperado.
+
code
+
Uma sintaxe opcional permite você incuir uma string ao invés de uma função, no qual é compilado e executada a cada delay em milisegundos. Esta sintaxe não é recomendada pelos mesmos motivos que envolvem riscos de segurança de {{jsxref("eval", "eval()")}}.
+
delay
+
O tempo, em milisegundos (milésimos de segundo), o temporizador deve atrasar entre cada execução de uma especifica função ou código. Se esse parâmetro for menos que 10, um valor de 10 é usado. Note que o atraso pode vir a ser mais longo; veja {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}} para exemplos.
+
param1, ..., paramN {{optional_inline}}
+
Parâmetros adicionais que são passados através da função especificada pela func quando o temporizador expirar.
+
+ +
+

Note: Passing additional parameters to setInterval() in the first syntax does not work in Internet Explorer 9 and earlier. If you want to enable this functionality on that browser, you must use a polyfill (see the Callback arguments section).

+
+ +

Return value

+ +

intervalID retornado é um número, non-zero valor que identifica o temporizador criado pela chamada do setInterval(); este valor pode ser passado para {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} afim de cancelar o timeout.

+ +

Isso pode ser útil, estar ciente que o setInterval() e {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} compartilham o mesmo grupo de IDs, e que o clearInterval() e {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} podem tecnicamente serem usados em conjunto. Para deixar claro, contudo, você deve sempre tentar evitar combina-los, afim de evitar confusão na manutenção do seu código.

+ +
Note: The delay parameter is converted to a signed 32-bit integer. This effectively limits delay to 2147483647 ms, since it's specified as a signed integer in the IDL.
+ +

Exemplos

+ +

Exemplo 1: Sintaxe básica

+ +

O seguinte exemplo mostra a sintaxe básica do setInterval()

+ +
var intervalID = window.setInterval(myCallback, 500);
+
+function myCallback() {
+  // Your code here
+}
+
+ +

Exemplo 2: Alternando duas cores

+ +

O seguinte exemplo chama a função flashtext() uma vez por segundo até o botão de parar ser pressionado.

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="UTF-8" />
+  <title>setInterval/clearInterval example</title>
+
+  <script>
+    var nIntervId;
+
+    function changeColor() {
+      nIntervId = setInterval(flashText, 1000);
+    }
+
+    function flashText() {
+      var oElem = document.getElementById('my_box');
+      oElem.style.color = oElem.style.color == 'red' ? 'blue' : 'red';
+      // oElem.style.color == 'red' ? 'blue' : 'red' is a ternary operator.
+    }
+
+    function stopTextColor() {
+      clearInterval(nIntervId);
+    }
+  </script>
+</head>
+
+<body onload="changeColor();">
+  <div id="my_box">
+    <p>Hello World</p>
+  </div>
+
+  <button onclick="stopTextColor();">Stop</button>
+</body>
+</html>
+
+ +

Exemplo 3: Simulação de máquina de escrever

+ +

O seguinte exemplo simula uma máquina de escrever primeiro limpando e digitando lentamente o conteúdo para  NodeList que corresponde a um grupo especificado de seletores.

+ +
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8" />
+<title>JavaScript Typewriter - MDN Example</title>
+<script>
+  function Typewriter (sSelector, nRate) {
+
+  function clean () {
+    clearInterval(nIntervId);
+    bTyping = false;
+    bStart = true;
+    oCurrent = null;
+    aSheets.length = nIdx = 0;
+  }
+
+  function scroll (oSheet, nPos, bEraseAndStop) {
+    if (!oSheet.hasOwnProperty('parts') || aMap.length < nPos) { return true; }
+
+    var oRel, bExit = false;
+
+    if (aMap.length === nPos) { aMap.push(0); }
+
+    while (aMap[nPos] < oSheet.parts.length) {
+      oRel = oSheet.parts[aMap[nPos]];
+
+      scroll(oRel, nPos + 1, bEraseAndStop) ? aMap[nPos]++ : bExit = true;
+
+      if (bEraseAndStop && (oRel.ref.nodeType - 1 | 1) === 3 && oRel.ref.nodeValue) {
+        bExit = true;
+        oCurrent = oRel.ref;
+        sPart = oCurrent.nodeValue;
+        oCurrent.nodeValue = '';
+      }
+
+      oSheet.ref.appendChild(oRel.ref);
+      if (bExit) { return false; }
+    }
+
+    aMap.length--;
+    return true;
+  }
+
+  function typewrite () {
+    if (sPart.length === 0 && scroll(aSheets[nIdx], 0, true) && nIdx++ === aSheets.length - 1) { clean(); return; }
+
+    oCurrent.nodeValue += sPart.charAt(0);
+    sPart = sPart.slice(1);
+  }
+
+  function Sheet (oNode) {
+    this.ref = oNode;
+    if (!oNode.hasChildNodes()) { return; }
+    this.parts = Array.prototype.slice.call(oNode.childNodes);
+
+    for (var nChild = 0; nChild < this.parts.length; nChild++) {
+      oNode.removeChild(this.parts[nChild]);
+      this.parts[nChild] = new Sheet(this.parts[nChild]);
+    }
+  }
+
+  var
+    nIntervId, oCurrent = null, bTyping = false, bStart = true,
+    nIdx = 0, sPart = "", aSheets = [], aMap = [];
+
+  this.rate = nRate || 100;
+
+  this.play = function () {
+    if (bTyping) { return; }
+    if (bStart) {
+      var aItems = document.querySelectorAll(sSelector);
+
+      if (aItems.length === 0) { return; }
+      for (var nItem = 0; nItem < aItems.length; nItem++) {
+        aSheets.push(new Sheet(aItems[nItem]));
+        /* Uncomment the following line if you have previously hidden your elements via CSS: */
+        // aItems[nItem].style.visibility = "visible";
+      }
+
+      bStart = false;
+    }
+
+    nIntervId = setInterval(typewrite, this.rate);
+    bTyping = true;
+  };
+
+  this.pause = function () {
+    clearInterval(nIntervId);
+    bTyping = false;
+  };
+
+  this.terminate = function () {
+    oCurrent.nodeValue += sPart;
+    sPart = "";
+    for (nIdx; nIdx < aSheets.length; scroll(aSheets[nIdx++], 0, false));
+    clean();
+  };
+}
+
+/* usage: */
+var oTWExample1 = new Typewriter(/* elements: */ '#article, h1, #info, #copyleft', /* frame rate (optional): */ 15);
+
+/* default frame rate is 100: */
+var oTWExample2 = new Typewriter('#controls');
+
+/* you can also change the frame rate value modifying the "rate" property; for example: */
+// oTWExample2.rate = 150;
+
+onload = function () {
+  oTWExample1.play();
+  oTWExample2.play();
+};
+</script>
+<style type="text/css">
+span.intLink, a, a:visited {
+  cursor: pointer;
+  color: #000000;
+  text-decoration: underline;
+}
+
+#info {
+  width: 180px;
+  height: 150px;
+  float: right;
+  background-color: #eeeeff;
+  padding: 4px;
+  overflow: auto;
+  font-size: 12px;
+  margin: 4px;
+  border-radius: 5px;
+  /* visibility: hidden; */
+}
+</style>
+</head>
+
+<body>
+
+<p id="copyleft" style="font-style: italic; font-size: 12px; text-align: center;">CopyLeft 2012 by <a href="https://developer.mozilla.org/" target="_blank">Mozilla Developer Network</a></p>
+<p id="controls" style="text-align: center;">[&nbsp;<span class="intLink" onclick="oTWExample1.play();">Play</span> | <span class="intLink" onclick="oTWExample1.pause();">Pause</span> | <span class="intLink" onclick="oTWExample1.terminate();">Terminate</span>&nbsp;]</p>
+<div id="info">
+Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt.
+</div>
+<h1>JavaScript Typewriter</h1>
+
+<div id="article">
+<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum.</p>
+<form>
+<p>Phasellus ac nisl lorem: <input type="text" /><br />
+<textarea style="width: 400px; height: 200px;">Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum.</textarea></p>
+<p><input type="submit" value="Send" />
+</form>
+<p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibStartum quis. Cras adipiscing ultricies fermentum. Praesent bibStartum condimentum feugiat.</p>
+<p>Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p>
+</div>
+</body>
+</html>
+ +

View this demo in action. See also: clearInterval().

+ +

Argumentos callback

+ +

Como já foi discutido, Internet Explorer 9 e versões anteriores não suportam passar argumentos para a função callback em ambos setTimeout() ou setInterval(). O seguinte código IE-specific demonstra um método para superar esta limitação. Para usar, apenas adicione o seguinte código no topo do seu script.

+ +
/*\
+|*|
+|*|  IE-specific polyfill that enables the passage of arbitrary arguments to the
+|*|  callback functions of javascript timers (HTML5 standard syntax).
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
+|*|  https://developer.mozilla.org/User:fusionchess
+|*|
+|*|  Syntax:
+|*|  var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
+|*|  var intervalID = window.setInterval(code, delay);
+|*|
+\*/
+
+if (document.all && !window.setTimeout.isPolyfill) {
+  var __nativeST__ = window.setTimeout;
+  window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+    var aArgs = Array.prototype.slice.call(arguments, 2);
+    return __nativeST__(vCallback instanceof Function ? function () {
+      vCallback.apply(null, aArgs);
+    } : vCallback, nDelay);
+  };
+  window.setTimeout.isPolyfill = true;
+}
+
+if (document.all && !window.setInterval.isPolyfill) {
+  var __nativeSI__ = window.setInterval;
+  window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+    var aArgs = Array.prototype.slice.call(arguments, 2);
+    return __nativeSI__(vCallback instanceof Function ? function () {
+      vCallback.apply(null, aArgs);
+    } : vCallback, nDelay);
+  };
+  window.setInterval.isPolyfill = true;
+}
+
+ +

Outra possibilidade é uso uma função anônima para chama o callback, apesar de que esta solução seja um pouco mais pesada. Exemplo:

+ +
var intervalID = setInterval(function() { myFunc('one', 'two', 'three'); }, 1000);
+ +

Outra possibilidade é usar o function's bind. Exemplo:

+ +
var intervalID = setInterval(function(arg1) {}.bind(undefined, 10), 1000);
+ +

{{h3_gecko_minversion("Inactive tabs", "5.0")}}

+ +

Starting in Gecko 5.0 {{geckoRelease("5.0")}}, intervals are clamped to fire no more often than once per second in inactive tabs.

+ +

O problema do "this"

+ +

Quando você passa um método para setInterval() ou qualquer outra função, ela é chamada com o valor do this errado. Este problema é explicado em detalhes em JavaScript reference.

+ +

Explicação

+ +

O código executado pelo setInterval() roda em um contexto de execução separado da função que foi chamada. Como uma consequência, o this da função chamada, é setado como o objeto window (ou global), esse não é o mesmo valor do this para a função chamada em setTimeout. veja o seguinte exemplo (que usa setTimeout() ao invés de setInterval() - o problema segue para ambos os temporizadores)

+ +
myArray = ['zero', 'one', 'two'];
+
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+myArray.myMethod(); // prints "zero,one,two"
+myArray.myMethod(1); // prints "one"
+setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
+setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1,5 seconds
+// passing the 'this' object with .call won't work
+// because this will change the value of this inside setTimeout itself
+// while we want to change the value of this inside myArray.myMethod
+// in fact, it will be an error because setTimeout code expects this to be the window object:
+setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error
+
+ +

 

+ +

Como você pode ver, não há maneiras de passar o objeto this para a função callback.

+ +

 

+ +

Uma possível solução

+ +

Um possível caminho para resolver o problema do this, é sobreescrever as duas funções globais nativas setTimeout() ou setInterval() com duas non-native que permitem sua invocação através do método Function.prototype.call. O seguinte exemplo mostra a possível substituição.

+ +
// Enable the passage of the 'this' object through the JavaScript timers
+
+var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
+
+window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeST__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+
+window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeSI__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+ +
These two replacements also enable the HTML5 standard passage of arbitrary arguments to the callback functions of timers in IE. So they can be used as non-standard-compliant polyfills also. See the callback arguments paragraph for a standard-compliant polyfill.
+ +

Teste da nova implementação:

+ +
myArray = ['zero', 'one', 'two'];
+
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+setTimeout(alert, 1500, 'Hello world!'); // the standard use of setTimeout and setInterval is preserved, but...
+setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds
+
+ +

Outra, mais complexa, solução para o problema do this é the following framework.

+ +
JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Also, ES2015 supports arrow functions, with lexical this allowing us to write setInterval( () => this.myMethod) if we're inside myArray method.
+ +

MiniDaemon - A framework for managing timers

+ +

In pages requiring many timers, it can often be difficult to keep track of all of the running timer events. One approach to solving this problem is to store information about the state of a timer in an object. Following is a minimal example of such an abstraction. The constructor architecture explicitly avoids the use of closures. It also offers an alternative way to pass the this object to the callback function (see The "this" problem for details). The following code is also available on GitHub.

+ +
For a more complex but still modular version of it (Daemon) see JavaScript Daemons Management. This more complex version is nothing but a big and scalable collection of methods for the Daemon constructor. However, the Daemon constructor itself is nothing but a clone of MiniDaemon with an added support for init and onstart functions declarable during the instantiation of the daemon. So the MiniDaemon framework remains the recommended way for simple animations, because Daemon without its collection of methods is essentially a clone of it.
+ +

minidaemon.js

+ +
/*\
+|*|
+|*|  :: MiniDaemon ::
+|*|
+|*|  Revision #2 - September 26, 2014
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
+|*|  https://developer.mozilla.org/User:fusionchess
+|*|  https://github.com/madmurphy/minidaemon.js
+|*|
+|*|  This framework is released under the GNU Lesser General Public License, version 3 or later.
+|*|  http://www.gnu.org/licenses/lgpl-3.0.html
+|*|
+\*/
+
+function MiniDaemon (oOwner, fTask, nRate, nLen) {
+  if (!(this && this instanceof MiniDaemon)) { return; }
+  if (arguments.length < 2) { throw new TypeError('MiniDaemon - not enough arguments'); }
+  if (oOwner) { this.owner = oOwner; }
+  this.task = fTask;
+  if (isFinite(nRate) && nRate > 0) { this.rate = Math.floor(nRate); }
+  if (nLen > 0) { this.length = Math.floor(nLen); }
+}
+
+MiniDaemon.prototype.owner = null;
+MiniDaemon.prototype.task = null;
+MiniDaemon.prototype.rate = 100;
+MiniDaemon.prototype.length = Infinity;
+
+  /* These properties should be read-only */
+
+MiniDaemon.prototype.SESSION = -1;
+MiniDaemon.prototype.INDEX = 0;
+MiniDaemon.prototype.PAUSED = true;
+MiniDaemon.prototype.BACKW = true;
+
+  /* Global methods */
+
+MiniDaemon.forceCall = function (oDmn) {
+  oDmn.INDEX += oDmn.BACKW ? -1 : 1;
+  if (oDmn.task.call(oDmn.owner, oDmn.INDEX, oDmn.length, oDmn.BACKW) === false || oDmn.isAtEnd()) { oDmn.pause(); return false; }
+  return true;
+};
+
+  /* Instances methods */
+
+MiniDaemon.prototype.isAtEnd = function () {
+  return this.BACKW ? isFinite(this.length) && this.INDEX < 1 : this.INDEX + 1 > this.length;
+};
+
+MiniDaemon.prototype.synchronize = function () {
+  if (this.PAUSED) { return; }
+  clearInterval(this.SESSION);
+  this.SESSION = setInterval(MiniDaemon.forceCall, this.rate, this);
+};
+
+MiniDaemon.prototype.pause = function () {
+  clearInterval(this.SESSION);
+  this.PAUSED = true;
+};
+
+MiniDaemon.prototype.start = function (bReverse) {
+  var bBackw = Boolean(bReverse);
+  if (this.BACKW === bBackw && (this.isAtEnd() || !this.PAUSED)) { return; }
+  this.BACKW = bBackw;
+  this.PAUSED = false;
+  this.synchronize();
+};
+
+ +
MiniDaemon passes arguments to the callback function. If you want to work on it with browsers that natively do not support this feature, use one of the methods proposed above.
+ +

Syntax

+ +

var myDaemon = new MiniDaemon(thisObject, callback[, rate[, length]]);

+ +

Description

+ +

Returns a JavaScript Object containing all information needed by an animation (like the this object, the callback function, the length, the frame-rate).

+ +

Parameters

+ +
+
thisObject
+
The this object on which the callback function is called. It can be an object or null.
+
callback
+
The function that is repeatedly invoked . It is called with three parameters: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is increasing or decreasing). It is something like callback.call(thisObject, index, length, backwards). If the callback function returns a false value the daemon is paused.
+
rate (optional)
+
The time lapse (in number of milliseconds) between each invocation. The default value is 100.
+
length (optional)
+
The total number of invocations. It can be a positive integer or Infinity. The default value is Infinity.
+
+ +

MiniDaemon instances properties

+ +
+
myDaemon.owner
+
The this object on which is executed the daemon (read/write). It can be an object or null.
+
myDaemon.task
+
The function that is repeatedly invoked (read/write). It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is decreasing or not) – see above. If the myDaemon.task function returns a false value the daemon is paused.
+
myDaemon.rate
+
The time lapse (in number of milliseconds) between each invocation (read/write).
+
myDaemon.length
+
The total number of invocations. It can be a positive integer or Infinity (read/write).
+
+ +

MiniDaemon instances methods

+ +
+
myDaemon.isAtEnd()
+
Returns a boolean expressing whether the daemon is at the start/end position or not.
+
myDaemon.synchronize()
+
Synchronize the timer of a started daemon with the time of its invocation.
+
myDaemon.pause()
+
Pauses the daemon.
+
myDaemon.start([reverse])
+
Starts the daemon forward (index of each invocation increasing) or backwards (index decreasing).
+
+ +

MiniDaemon global object methods

+ +
+
MiniDaemon.forceCall(minidaemon)
+
Forces a single callback to the minidaemon.task function regardless of the fact that the end has been reached or not. In any case the internal INDEX property is increased/decreased (depending on the actual direction of the process).
+
+ +

Example usage

+ +

Your HTML page:

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="UTF-8" />
+  <title>MiniDaemin Example - MDN</title>
+  <script type="text/javascript" src="minidaemon.js"></script>
+  <style type="text/css">
+    #sample_div {
+      visibility: hidden;
+    }
+  </style>
+</head>
+
+<body>
+  <p>
+    <input type="button" onclick="fadeInOut.start(false /* optional */);" value="fade in" />
+    <input type="button" onclick="fadeInOut.start(true);" value="fade out">
+    <input type="button" onclick="fadeInOut.pause();" value="pause" />
+  </p>
+
+  <div id="sample_div">Some text here</div>
+
+  <script type="text/javascript">
+    function opacity (nIndex, nLength, bBackwards) {
+      this.style.opacity = nIndex / nLength;
+      if (bBackwards ? nIndex === 0 : nIndex === 1) {
+        this.style.visibility = bBackwards ? 'hidden' : 'visible';
+      }
+    }
+
+    var fadeInOut = new MiniDaemon(document.getElementById('sample_div'), opacity, 300, 8);
+  </script>
+</body>
+</html>
+ +

View this example in action

+ +

Notes

+ +

The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations.

+ +

You can cancel the interval using {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}.

+ +

If you wish to have your function called once after the specified delay, use {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.

+ +

Ensure that execution duration is shorter than interval frequency

+ +

If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}. For example, if using setInterval to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its allotted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.

+ +

In these cases, a recursive setTimeout() pattern is preferred:

+ +
(function loop(){
+   setTimeout(function() {
+      // Your logic here
+
+      loop();
+  }, delay);
+})();
+
+ +

In the above snippet, a named function loop() is declared and is immediately executed. loop() is recursively called inside setTimeout() after the logic has completed executing. While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.

+ +

Throttling of intervals

+ +

setInterval() is subject to the same throttling restrictions in Firefox as {{domxref("WindowOrWorkerGlobalScope.setTimeout","setTimeout()")}}; see Reasons for delays longer than specified.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setinterval', 'WindowOrWorkerGlobalScope.setInterval()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.setInterval")}}

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/windowtimers/cleartimeout/index.html b/files/pt-br/web/api/windowtimers/cleartimeout/index.html new file mode 100644 index 0000000000..f03f43979f --- /dev/null +++ b/files/pt-br/web/api/windowtimers/cleartimeout/index.html @@ -0,0 +1,100 @@ +--- +title: WindowTimers.clearTimeout() +slug: Web/API/WindowTimers/clearTimeout +tags: + - API + - Method + - Window +translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout +--- +
+
+
{{APIRef("HTML DOM")}}
+
+
+ +

Sumário

+ +

O método clearTimeout() do escopo {{domxref("WindowOrWorkerGlobalScope")}} cancela um timeout previamente estabelecido pela função {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}.

+ +

Síntaxe

+ +
escopo.clearTimeout(timeoutID)
+
+ +

Parâmetros

+ +
+
timeoutID
+
O ID do timeout que você deseja cancelar. Esse ID é o retorno da função setTimeout().
+
+ +

É interessante ressaltar que os conjuntso de IDs usados pelos métodos {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} e {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} são compartilhados, o que significa que clearTimeout() e {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} podem ser tecnicamente utilizados de forma intercambiável. No entanto, para obter-se maior clareza, isso deve ser evitado.

+ +

Exemplo

+ +

Execute o script abaixo em uma página web e clique na página uma vez. Você verá uma mensagem aparecer um segundo depois. Se você continuar clicando na página várias vezes nesse intervalo de tempo, a mensagem aparecerá uma única vez.

+ +
var alarme = {
+  relembrar: function(aMessage) {
+    alert(aMessage);
+    delete this.timeoutID;
+  },
+
+  setup: function() {
+    if (typeof this.timeoutID === 'number') {
+        this.cancelar();
+    }
+
+    this.timeoutID = window.setTimeout(function(msg) {
+        this.relembrar(msg);
+    }.bind(this), 1000, 'Wake up!');
+  },
+
+  cancelar: function() {
+    window.clearTimeout(this.timeoutID);
+  }
+};
+window.onclick = function() { alarme.setup() };
+ +

Notas

+ +

Passar um ID inválido para clearTimeout não causa nenhum efeito (não lança nenhuma exceção).

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'WindowOrWorkerGlobalScope.clearTimeout()')}}{{Spec2("HTML WHATWG")}}Método movido para WindowOrWorkerGlobalScope .
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'clearTimeout()')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.clearTimeout")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/windowtimers/index.html b/files/pt-br/web/api/windowtimers/index.html new file mode 100644 index 0000000000..bd995e8f74 --- /dev/null +++ b/files/pt-br/web/api/windowtimers/index.html @@ -0,0 +1,116 @@ +--- +title: WindowTimers +slug: Web/API/WindowTimers +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +
{{APIRef("HTML DOM")}}
+ +

WindowTimers contains utility methods to set and clear timers.

+ +

There is no object of this type, though the context object, either the {{domxref("Window")}} for regular browsing scope, or the {{domxref("WorkerGlobalScope")}}  for workers, implements it.

+ +

Properties

+ +

This interface do not define any property, nor inherit any.

+ +

Methods

+ +

This interface do not inherit any method.

+ +
+
{{domxref("WindowTimers.clearInterval()")}}
+
Cancels the repeated execution set using {{domxref("WindowTimers.setInterval()")}}.
+
{{domxref("WindowTimers.clearTimeout()")}}
+
Cancels the repeated execution set using {{domxref("WindowTimers.setTimeout()")}}.
+
{{domxref("WindowTimers.setInterval()")}}
+
Schedules the execution of a function each X milliseconds.
+
{{domxref("WindowTimers.setTimeout()")}}
+
Sets a delay for executing a function.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windowtimers', 'WindowTimers')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windowtimers', 'WindowTimers')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#windowtimers", "WindowTimers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(1)}}1.04.04.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

See also

+ + diff --git a/files/pt-br/web/api/worker/index.html b/files/pt-br/web/api/worker/index.html new file mode 100644 index 0000000000..8cf54eccb0 --- /dev/null +++ b/files/pt-br/web/api/worker/index.html @@ -0,0 +1,166 @@ +--- +title: Worker +slug: Web/API/Worker +translation_of: Web/API/Worker +--- +

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

+ +

A interface Worker da API do Web Worker representa uma tarefa em background (segundo plano) que pode ser facilmente criada e emitir mensagens de volta ao seu criador. Criar um worker é possível chamando o construtor Worker("path/to/worker/script") e especificando um script para ser executado em sua própria thread.

+ +

Um worker pode, por sua vez, gerar outros workers, contanto que estes estejam hospedados na mesma origem da página principal (Nota: workers aninhados não estão atualmente implementados no Blink). Além disso, workers podem utilizar XMLHttpRequest para E/S de rede, desde que seja estipulado que os atributos responseXML e channel em XMLHttpRequest retornem sempre null.

+ +

Não são todas as interfaces e funções que estão disponíveis para o script associado a um Worker.

+ +
+

No Firefox, se você deseja utilizar workers em extensões e gostaria de ter acesso a js-ctypes, você deveria utilizar o objeto {{ domxref("ChromeWorker") }} .

+
+ +

Construtores

+ +
+
{{domxref("Worker.Worker", "Worker()")}}
+
Cria um worker dedicado da web que executa o script especificado na URL. Workers também podem ser construídos usando Blobs.
+
+ +

Propriedades

+ +

Herda as propriedades do pai, {{domxref("EventTarget")}}, e implementa as propriedades que compõem o {{domxref("AbstractWorker")}}.

+ +

Manipuladores de Eventos

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
Um {{ domxref("EventListener") }} é chamado sempre quando um {{domxref("ErrorEvent")}} do tipo error é passado através do worker. Este é herdado pelo {{domxref("AbstractWorker")}}.
+
{{domxref("Worker.onmessage")}}
+
Um {{ domxref("EventListener") }} é chamado sempre quando um {{domxref("MessageEvent")}} do tipo message é passado através do worker — ou seja, quando uma mensagem é enviada para o documento pai do worker via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}. A mensagem é armazenada na propriedade de dados do evento {{domxref("MessageEvent.data", "data")}}.
+
+ +

Métodos

+ +

Os métodos são herdados de seu pai. {{domxref("EventTarget")}}, e implementa os métodos de {{domxref("AbstractWorker")}}.

+ +
+
{{domxref("Worker.postMessage()")}}
+
Envia uma mensagem — qual pode consistir de qualquer objeto do JavaScript — para o escopo interno do worker.
+
{{domxref("Worker.terminate()")}}
+
Imediatamente encerra o worker. Isso não oferece ao worker a oportunidade de concluir suas operações; imediatamente o interrompe. ServiceWorker não suportam esse método.
+
+ +

Eventos

+ +
+
message
+
O evento é disparado quando o script pai do worker recebe uma mensagem do mesmo.
+ Também é disponibilizado via onmessage.
+
messageerror
+
Dispara quando um Worker recebe uma mensagem que não pode ser deserializada
+ Também é disponibilizado via onmessageerror.
+
rejectionhandled
+
Dispara sempre que um {{jsxref("Promise")}} é rejeitado, indenpendentemente de haver ou não um manipulador para capturar sua rejeição.
+ Também é disponibilizado via onrejectionhandled.
+
unhandledrejection
+
Dispara sempre que um {{jsxref ("Promise")}} rejeita, independentemente de haver ou não um manipulador para capturar a rejeição. Também disponível por meio da propriedade do manipulador de eventos onunhandledrejection.
+
.
+
+ +

Exemplos

+ +

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('input#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).

+ +

Specifications

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

Browser compatibility

+ +

Support varies for different types of workers. See each worker type's page for specifics.

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support43.510.010.64
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support4.43.51.0.110.011.55.1{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/xmldocument/async/index.html b/files/pt-br/web/api/xmldocument/async/index.html new file mode 100644 index 0000000000..63de77faea --- /dev/null +++ b/files/pt-br/web/api/xmldocument/async/index.html @@ -0,0 +1,37 @@ +--- +title: Document.async +slug: Web/API/XMLDocument/async +translation_of: Web/API/XMLDocument/async +--- +

{{APIRef("DOM")}}{{Deprecated_header}} {{Non-standard_header}}

+ +

document.async pode ser configurado para indicar se uma chamada {{domxref ("document.load")}} deve ser uma solicitação assíncrona ou síncrona. True é o valor padrão, indicando que os documentos devem ser carregados de forma assíncrona.

+ +

 

+ +

(Carregamento de documentos assicronos a partir da versão 1.4 alpha.)

+ +

Exemplo

+ +
function loadXMLData(e) {
+  alert(new XMLSerializer().serializeToString(e.target)); // Retorna o conteúdo de querydata.xml em String
+}
+
+var xmlDoc = document.implementation.createDocument("", "test", null);
+
+xmlDoc.async = false;
+xmlDoc.onload = loadXMLData;
+xmlDoc.load('querydata.xml');
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/xmldocument/index.html b/files/pt-br/web/api/xmldocument/index.html new file mode 100644 index 0000000000..ddfbeaaac3 --- /dev/null +++ b/files/pt-br/web/api/xmldocument/index.html @@ -0,0 +1,61 @@ +--- +title: DocumentoXML +slug: Web/API/XMLDocument +tags: + - API + - DOM + - DocumentoXML + - Experimental + - Interface +translation_of: Web/API/XMLDocument +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

A interface XMLDocument representa um document XML. Ele herda de {{DOMxRef("Document")}} e não adiciona nenhum método específico ou propriedades para este: no entanto, alguns algoritmos tem comportamento diferente com os dois tipos de documentos.

+ +

Propridades

+ +

Esta interface não tem e nem herda nenhuma propriedade específica.

+ +

Metodos

+ +

Esta interface não adiciona nenhum método novo.

+ +
+
{{DOMxRef("XMLDocument.load()")}} {{Non-standard_Inline}} {{Deprecated_Inline}}
+
Carrega um documento XML
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("DOM WHATWG", "#xmldocument", "XMLDocument")}}{{Spec2("DOM WHATWG")}}Sem alterações.
{{SpecName("DOM4", "#xmldocument", "XMLDocument")}}{{Spec2("DOM4")}}Definição Inicial.
+ +

Compatibilidade com Navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/xmlhttprequest/abort/index.html b/files/pt-br/web/api/xmlhttprequest/abort/index.html new file mode 100644 index 0000000000..52c1a52068 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/abort/index.html @@ -0,0 +1,118 @@ +--- +title: XMLHttpRequest.abort() +slug: Web/API/XMLHttpRequest/abort +tags: + - AJAX + - API + - HTTP + - HttpRequest + - Referencia + - XMLHttpRequest + - cancelando +translation_of: Web/API/XMLHttpRequest/abort +--- +

{{APIRef('XMLHttpRequest')}}

+ +

O método XMLHttpRequest.abort() aborta a requisição se ela já tiver sido enviada. Quando uma requisição é abortada, o seu readyState é modificado para 0 (Desativado), mas o evento readystatechange não é disparado.

+ +

Sitaxe

+ +
xhrInstance.abort();
+ +

Parâmetros

+ +

Nenhum.

+ +

Retorno

+ +

Nenhum.

+ +

Exemplo

+ +
var xhr = new XMLHttpRequest(),
+    method = "GET",
+    url = "https://developer.mozilla.org/";
+xhr.open(method,url,true);
+
+xhr.send();
+
+xhr.abort();
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest', '#the-abort()-method')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidade entre navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(1)}}{{CompatUnknown}}{{CompatIe('5')}}[1]
+ {{CompatIe('7')}}
{{CompatVersionUnknown}}{{CompatSafari('1.2')}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Esse recurso foi implementado através de ActiveXObject (). O Internet Explorer implementa o padrão XMLHttpRequest desde a versão 7.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/xmlhttprequest/index.html b/files/pt-br/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..de045c5314 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/index.html @@ -0,0 +1,724 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - Fixit + - HTTP + - MakeBrowserAgnostic + - NeedsCleanup + - NeedsMobileBrowserCompatibility + - NeedsTranslation + - TopicStub + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest +--- +

{{APIRef("XMLHttpRequest")}}

+ +

XMLHttpRequest é um objeto que fornece funcionalidade ao cliente para transferir dados entre um cliente e um servidor. Ele fornece uma maneira fácil de recuperar dados de um URL sem ter que fazer uma atualização de página inteira. Isso permite que uma página da Web atualize apenas uma parte do conteúdo sem interromper o que o usuário esteja fazendo. XMLHttpRequest é usado constantemente na programação de AJAX.

+ +

XMLHttpRequest foi originalmente projetado pela Microsoft e adotado pela Mozilla, Apple e Google. Está sendo padronizado pela WHATWG. Apesar do nome, XMLHttpRequest pode ser usado para recuperar qualquer tipo de dados, e não apenas XML, suportando também, protocolos diferentes de HTTP (incluindo file e ftp ).

+ +

Para criar uma instância de XMLHttpRequest , basta fazer isso:

+ +
var myRequest = new XMLHttpRequest();
+
+ +

Para obter detalhes sobre como usar XMLHttpRequest , consulte Usando XMLHttpRequest.

+ +

Métodos

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
XMLHttpRequest(JSObject objParameters);
void abort();
DOMString getAllResponseHeaders();
DOMString? getResponseHeader(DOMString header);
void open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);
void overrideMimeType(DOMString mime);
void send();
+ void send(ArrayBuffer data);
+ void send(Blob data);
+ void send(Document data);
+ void send(DOMString? data);
+ void send(FormData data);
void setRequestHeader(DOMString header, DOMString value);
Métodos não-padrão
[noscript] void init(in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow);
[noscript] void openRequest(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);
void sendAsBinary(in DOMString body);
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AtributoTipoDescrição
+

onreadystatechange

+
Function? +

A função de objeto JavaScript que é chamado sempre que o atributo readyState sofre alteração. A função de callback é chamada a partir da thread existente na interface de usuário.

+ +
Aviso: Este não deve ser usado com chamadas síncronas e não deve ser utilizado a partir do código nativo.
+
readyStateretorna o cabeçalho da requisição. +

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValorEstadoDescrição
0UNSENTopen() não foi chamado ainda.
1OPENEDsend() não foi chamado ainda.
2HEADERS_RECEIVEDsend() foi chamado, e cabeçalhos e status estão disponíveis.
3LOADINGDownload; responseText contém dados parciais.
4DONEA operação está concluída.
+
responseArrayBuffer, Document,Blob, DOMString +

Retorna um objeto JavaScript de tipo {{domxref("ArrayBuffer")}}, {{domxref("Blob")}} ou {{domxref("Document")}}, de acordo com  o que estiver contido no responseTypeRetorna null se a request não esteja completa ou não obteve sucesso.

+
responseText {{ReadOnlyInline()}}DOMStringA resposta à request, em formato texto, retorna null se a solicitação não teve êxito ou que ainda não foi enviada.
responseTypeXMLHttpRequestResponseType +

Pode ser configurado para alterar o tipo de resposta.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValorTipo de dados de resposta de propriedade
"" (string vazia)String (este é o padrão)
"arraybuffer"ArrayBuffer
"blob"{{ domxref("Blob") }}
"document"{{ domxref("Document") }}
"json"Objeto JavaScript, analisado a partir de uma seqüência de caracteres JSON retornado pelo servidor.
"text"String
"moz-blob"Usado pelo Firefox para permitir recuperar dados parciais do tipo {{ domxref("Blob") }},de eventos de progresso. Isso permite que o manipulador de eventos de progresso iniciar o processamento de dados enquanto ele ainda está sendo recebido.
"moz-chunked-text" +

Semelhante ao "text" , mas o streaming ainda está fluindo. Isto significa que o valor na response , só está disponível durante a expedição do "progress" do evento e contém apenas os dados recebidos desde a última "progress" do evento.

+ +

Quando response é acessado durante um evento "progress", este contém uma string com os dados. Caso contrário, retorna null .

+ +

Este modo atualmente só funciona no Firefox.

+
"moz-chunked-arraybuffer" +

Semelhante ao "arraybuffer", mas está fluindo. Isto significa que o valor na response , só está disponível durante a expedição do "progress" do evento e contém apenas os dados recebidos desde a última "progress" do evento.

+ +

Quando response é acessado durante um "progress" evento que contém uma seqüência com os dados. Caso contrário, retorna null .

+ +

Este modo atualmente só funciona no Firefox.

+ +

.

+
+ +
Nota:  Começando com 11,0 Gecko (Firefox 11.0 / 11.0 Thunderbird / SeaMonkey 2.8), bem como WebKit construir 528, esses navegadores não permitem que você use o atributo responseType ao executar solicitações síncronas. Tentativas de fazer isso geram uma exceção do tipo NS_ERROR_DOM_INVALID_ACCESS_ERR. Esta mudança foi proposta para padronização junto à W3C.
+
responseXML {{ReadOnlyInline()}}Document? +

A resposta ao pedido como um DOM Document objeto, ou null se o pedido não foi bem sucedida, ainda não foi enviado, ou não pode ser analisado como XML ou HTML. A resposta é analisado como se fosse um text/html stream. Quando o responseType está definido para "document" e que a solicitação tenha sido feita de forma assíncrona, a resposta é analisado como se fosse um text/html stream.

+ +
Nota: Se o servidor não se aplica o text/xml cabeçalho Content-Type, você pode usar overrideMimeType() para forçar XMLHttpRequest para analisá-lo como XML de qualquer maneira.
+
status {{ReadOnlyInline()}}unsigned shortO status de resposta da requisição. Este é o retorno do codigo da requisição HTTP (por exemplo, status é 200 qual a solicitação for bem-sucedida).
statusText {{ReadOnlyInline()}}DOMStringA cadeia de resposta retornado pelo servidor HTTP. Ao contrário do status , o que inclui todo o texto da mensagem de resposta (" 200 OK ", por exemplo).
timeoutunsigned long +

    
+ O número de milissegundos de um pedido pode tomar antes de ser automaticamente encerrada. Um valor de 0 (que é o padrão) significa que não há tempo limite.

+ +
Nota: Você não pode usar um tempo limite para solicitações síncronas com uma janela proprietária.
+
uploadXMLHttpRequestUploadO processo de upload pode ser rastreado através da ação de retorno de um evento para upload.
withCredentialsboolean +

Indica se ou não de cross-site Access-Control solicitações devem ser feitas usando credenciais, como cookies ou cabeçalhos de autorização. O padrão é false .

+ +
Nota: Esta não afeta as solicitações no mesmo local.
+ +
Nota: Começando com 11,0 Gecko (Firefox 11.0 / 11.0 Thunderbird / SeaMonkey 2.8), Gecko não permite que você use os atributos withCredentials ao realizar solicitações síncronas. Ao tentar fazer isso o sistema gera uma exceção do tipo NS_ERROR_DOM_INVALID_ACCESS_ERR.
+
+ +

Propriedades não-padrão

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeTypeDescription
channel {{ReadOnlyInline()}}{{Interface("nsIChannel")}}O canal utilizado pelo objecto aquando da execução do pedido. Esta é null se o canal não foi criado ainda. No caso de um pedido de múltiplas partes, isto é o canal inicial, não as diferentes partes do pedido de várias partes. Requer privilégios elevados para o acesso.​​
mozAnon {{ReadOnlyInline()}}boolean +

Se for verdadeiro (true) o pedido será enviado sem cabeçalhos de cookies e autenticação.

+
mozSystem {{ReadOnlyInline()}}boolean +

Se for verdadeiro (true) , a política de mesma origem não será aplicada sobre o pedido.

+
mozBackgroundRequestboolean +

Indica se o objeto representa uma solicitação de serviço de fundo. Se true , nenhum grupo carga está associada com o pedido, e diálogos de segurança estão impedidos de ser mostrado para o usuário. Requer privilégios elevados para o acesso.

+ +

Nos casos em que uma caixa de diálogo de segurança (como a autenticação ou uma notificação certificado ruim) normalmente seriam mostrados, o pedido simplesmente falhar em seu lugar.

+ +
Nota: Esta propriedade deve ser definida antes de chamar open().
+
mozResponseArrayBuffer {{ obsolete_inline("6") }} {{ReadOnlyInline()}}ArrayBufferA resposta ao pedido, como uma matriz de JavaScript digitado. Esta é NULL se o pedido não foi bem-sucedida, ou se não foi enviada ainda.
multipart {{ obsolete_inline("22") }}boolean +

Este Gecko somente recurso foi removido no Firefox / Gecko 22. Por favor Utilize Server-Sent Events, Web Sockets ou responseText de eventos de progresso em seu lugar.

+ +

Indica se ou não a resposta está prevista para ser uma corrente de, possivelmente, vários documentos XML. Se definido como true , o tipo de conteúdo da resposta inicial deve ser multipart/x-mixed-replace ou ocorrerá um erro. Todos os pedidos devem ser assíncrona.

+ +

Isso permite o suporte para servidor push; para cada documento XML que está escrito a este pedido, um novo documento XML DOM é criado eo onload manipulador é chamado entre os documentos.

+ +
Nota: Quando este estiver definido, o onload manipulador e outros manipuladores de eventos não são repostas após a primeira XmlDocument é carregado, eo onload manipulador é chamado após cada parte da resposta é recebida.
+
+ +

Construtor

+ +

XMLHttpRequest()

+ +

O construtor inicia um XMLHttpRequest. Ele deve ser chamado antes de quaisquer outras chamadas de método.

+ +

Gecko/Firefox 16 acrescenta um parâmetro não-padrão para o construtor que pode ativar o modo anônimo (veja Bug 692677). Definir o mozAnon bandeira de true eficácia se assemelha a AnonXMLHttpRequest() construtor descrito na especificação XMLHttpRequest que não tenha sido implementado em qualquer navegador ainda (em setembro de 2012).

+ +
XMLHttpRequest (
+  JSObject objParameters
+);
+ +
Parâmetros (não-padrão)
+ +
+
objParameters
+
Há dois sinalizadores que você pode definir: +
+
mozAnon
+
Boolean: Definir esse sinalizador de true fará com que o navegador para não expor a origem e as credenciais do usuário ao buscar recursos. Mais importante, isto significa que os cookies não será enviado a menos que explicitamente adicionado usando setRequestHeader.
+
mozSystem
+
Boolean: Definir esse sinalizador de true . permite fazer conexões entre sites sem a necessidade de o servidor para opt-in usando CORS requer a configuração mozAnon: true . Ou seja, este não pode ser combinada com o envio de cookies ou outras credenciais do usuário. Isso só funciona em privilegiados (revisto) Apps;ele não funciona em páginas da web arbitrários carregados no Firefox.
+
+
+
+ +

Métodos

+ +

abort()

+ +

Aborta o pedido, se já foi enviada.

+ +

getAllResponseHeaders()

+ +
DOMString getAllResponseHeaders();
+ +

Retorna todos os cabeçalhos de resposta como uma string, ou null se nenhuma resposta foi recebida. Nota: Para os pedidos de várias partes, isso retorna os cabeçalhos da parte atual da solicitação, não a partir do canal original.

+ +

getResponseHeader()

+ +
DOMString? getResponseHeader(DOMString header);
+ +

Retorna a string contendo o texto do cabeçalho especificado, ou null se quer a resposta ainda não foi recebida ou o cabeçalho não existe na resposta.

+ +

open()

+ +

Inicializa um pedido. Este método é para ser usado a partir do código JavaScript; para inicializar um pedido do código nativo, use openRequest() em seu lugar.​

+ +
Nota: Chamar esse método uma solicitação já está ativo (aquele para o qual open() ou openRequest() já foi chamado) é o equivalente de chamar abort().
+ +
void open(
+   DOMString method,
+   DOMString url,
+   optional boolean async,
+   optional DOMString user,
+   optional DOMString password
+);
+
+ +
Parameters
+ +
+
method
+
O método HTTP para usar, como "GET", "POST", "PUT", "DELETE", etc. ignorado para URLs não-HTTP (S).
+
url
+
O URL para o qual enviar a solicitação.
+
async
+
Um parâmetro booleano opcional, por padrão true , indicando se a operação deve ou não ser executada de forma assíncrona. Se esse valor for false , o send() método não retorna até que a resposta seja recebida. Se true , a notificação de uma transação concluída é fornecida usando ouvintes de evento. Isso deve ser true se o multipart atributo for true , ou uma exceção será lançada.
+
user
+
O nome de usuário opcional para usar para fins de autenticação; por padrão, essa é uma seqüência vazia.
+
password
+
A senha opcional para usar para fins de autenticação; por padrão, essa é uma seqüência vazia.
+
+ +

overrideMimeType()

+ +

Substitui o tipo de MIME retornado pelo servidor. Isto pode ser utilizado, por exemplo, para forçar uma corrente a ser tratada e analisada como text/xml, mesmo que o servidor não relatam como método. Este método deve ser chamado antes send() .

+ +
void overrideMimeType(DOMString mimetype);
+ +

send()

+ +

Envia a solicitação. Se o pedido é assíncrono (que é o padrão), este método retorna assim que o pedido for enviado. Se o pedido é síncrono, este método não retorna até a resposta chegar.

+ +
Nota:  Qualquer ouvintes de eventos que pretende definir tem de ser definida antes de chamar send().
+ +
void send();
+void send(ArrayBuffer data);
+void send(Blob data);
+void send(Document data);
+void send(DOMString? data);
+void send(FormData data);
+ +
Notas
+ +

Se os dados são um Document , ele é serializado antes de serem enviados. Ao enviar um documento, as versões do Firefox antes da versão 3 sempre enviavam a solicitação usando codificação UTF-8; Firefox 3 envia corretamente o documento usando a codificação especificada por body.xmlEncoding , ou UTF-8 se nenhum encoding é especificado.

+ +

Se são uma nsIInputStream , deve ser compatível com nsIUploadChannel 's setUploadStream() método. Nesse caso, um cabeçalho Content-Length é adicionado ao pedido, com o seu valor obtido usando nsIInputStream 's available() método. Quaisquer cabeçalhos incluídos na parte superior da corrente são tratados como parte do corpo da mensagem. MIMEType da transmissão deve ser especificado definindo o cabeçalho Content-Type usando o setRequestHeader() método antes de chamar send().

+ +

A melhor maneira de enviar conteúdo binário (como em arquivos de upload) está usandoArrayBuffers ou Blobs  em conjuncton com o send() método. No entanto, se você quiser enviar uma stringifiable dados brutos, use o sendAsBinary() método em vez disso.

+ +

setRequestHeader()

+ +

Define o valor de uma solicitação HTTP header. Você deve chamar setRequestHeader() após open() , mas antes de send().

+ +
void setRequestHeader(
+   DOMString header,
+   DOMString value
+);
+
+ +
Parametros
+ +
+
header
+
O nome do cabeçalho cujo valor deve ser definido.
+
value
+
O valor definido como o corpo do cabeçalho.
+
+ +

Métodos não-padrão

+ +

init()

+ +

Inicializa o objeto para uso a partir do código C ++.

+ +
Nota: Este método não deve ser chamado a partir do JavaScript.
+ +
[noscript] void init(
+   in nsIPrincipal principal,
+   in nsIScriptContext scriptContext,
+   in nsPIDOMWindow ownerWindow
+);
+
+ +
Parametros
+ +
+
principal
+
O principal a ser usado para o pedido; não deve ser null.
+
scriptContext
+
O contexto de script a ser usada para o pedido; não deve ser null.
+
ownerWindow
+
A janela associada com o pedido; pode ser null.
+
+ +

openRequest()

+ +

Inicializa um pedido. Este método é para ser usado a partir do código nativo; para inicializar um pedido do código JavaScript, usar open() em seu lugar. Consulte a documentação do open() .

+ +

sendAsBinary()

+ +

Uma variante do send() método que envia dados binários.

+ +
void sendAsBinary(
+   in DOMString body
+);
+
+ +

Este método, usado em conjuncton com o readAsBinaryString  método do FileReader API tornar possível read and upload any type of file e para  stringify os dados brutos.

+ +
Parametros
+ +
+
body
+
O corpo da solicitação como um DOMString. Estes dados poderão ser convertidos para uma seqüência de caracteres de byte único por truncamento (removendo o byte de mais alta ordem de cada personagem).
+
+ +
sendAsBinary() polyfill
+ +

Desde sendAsBinary() é um recurso experimental, aqui está uma polyfill para navegadores que não suportam o sendAsBinary() método, mas o apoio typed arrays.

+ +
/*\
+|*|
+|*|  :: XMLHttpRequest.prototype.sendAsBinary() Polifyll ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
+|*|
+\*/
+
+if (!XMLHttpRequest.prototype.sendAsBinary) {
+  XMLHttpRequest.prototype.sendAsBinary = function (sData) {
+    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
+    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
+      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
+    }
+    /* send as ArrayBufferView...: */
+    this.send(ui8Data);
+    /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
+  };
+}
+ +
Nota: É possível construir este polyfill colocar dois tipos de dados como argumento para send() : um ArrayBuffer (ui8Data.buffer - o código comentado) ou um ArrayBufferView ( ui8Data , que é uma typed array of 8-bit unsigned integers – descomentada código). No entanto, no Google Chrome, quando você tenta enviar uma ArrayBuffer , a seguinte mensagem de aviso aparecerá: ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead. ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead.
+ +

Notas

+ + + +

Eventos

+ +

onreadystatechange como uma propriedade do XMLHttpRequest instância é suportado em todos os navegadores.

+ +

Desde então, foram implementadas uma série de manipuladores de eventos adicionais em vários navegadores ( onload , onerror , onprogress , etc.). Estes são suportados no Firefox. Em particular, veja {{ interface("nsIXMLHttpRequestEventTarget") }} and Using XMLHttpRequest.

+ +

avegadores mais recentes, incluindo o Firefox, também suporta ouvir as XMLHttpRequest eventos via padrão addEventListener APIs Além de definir on* propriedades para uma função de manipulador.

+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support (XHR1)11.05 (via ActiveXObject)
+ 7 (XMLHttpRequest)
{{ CompatVersionUnknown() }}1.2
send(ArrayBuffer)99{{ compatUnknown() }}11.60{{ compatUnknown() }}
send(Blob)73.6{{ compatUnknown() }}12{{ compatUnknown() }}
send(FormData)64{{ compatUnknown() }}12{{ compatUnknown() }}
sendAsBinary(DOMString){{ compatNo() }} – use the polyfill1.9{{ compatUnknown() }}{{ compatUnknown() }}{{ compatUnknown() }}
response1061011.60{{ compatUnknown() }}
responseType = 'arraybuffer'1061011.60{{ compatUnknown() }}
responseType = 'blob'1961012{{ compatUnknown() }}
responseType = 'document'181110{{ CompatNo() }}{{ CompatNo() }}
responseType = 'json'{{ CompatNo() }}10{{ CompatNo() }}12{{ CompatNo() }}
Progress Events73.51012{{ compatUnknown() }}
withCredentials33.510124
timeout{{ CompatNo() }}12.08{{ compatUnknown() }}{{ CompatNo() }}
responseType = 'moz-blob'{{ CompatNo() }}12.0{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}0.16{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Notas Gecko

+ +

Gecko 11.0 {{ geckoRelease("11.0") }} removeu o suporte para o uso do responseTypewithCredentials atribui ao realizar solicitações síncronas. Tentativa de fazer isso gera uma NS_ERROR_DOM_INVALID_ACCESS_ERR exception. Esta mudança foi proposta para o W3C para a normalização.

+ +

Gecko 12.0 {{ geckoRelease("12.0") }} e suporte posteriormente usando XMLHttpRequest para ler a partir data: URLs.

+ +

Veja também

+ + + +

{{ languages( { "es": "es/XMLHttpRequest", "fr": "fr/XMLHttpRequest", "it": "it/XMLHttpRequest", "ja": "ja/XMLHttpRequest", "ko": "ko/XMLHttpRequest", "pl": "pl/XMLHttpRequest", "zh-cn": "zh-cn/DOM/XMLHttpRequest" } ) }}

diff --git a/files/pt-br/web/api/xmlhttprequest/onreadystatechange/index.html b/files/pt-br/web/api/xmlhttprequest/onreadystatechange/index.html new file mode 100644 index 0000000000..b67e816ae4 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/onreadystatechange/index.html @@ -0,0 +1,120 @@ +--- +title: XMLHttpRequest.onreadystatechange +slug: Web/API/XMLHttpRequest/onreadystatechange +tags: + - AJAX + - API + - Evento + - Manipulador de eventos + - XHR + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/onreadystatechange +--- +
{{APIRef}}
+ +

Um EventHandler é chamado sempre que o atributo readyState é modificado. O callback é chamado a partir da interface do usuário. A propriedade XMLHttpRequest.onreadystatechange contém o manipulador de eventos que é chamado quando o evento readystatechange é disparado, ou seja, toda vez que a propriedade {{domxref("XMLHttpRequest.readyState", "readyState")}} do {{domxref("XMLHttpRequest")}} é modificada.

+ +
+

Atenção: Isso não deve ser usado com solicitações síncronas e não deve ser usado como código nativo.

+
+ +

O evento readystatechange não será chamado quando a XMLHttpRequest request for cancelada pelo método abort().

+ +
+

Atualização: Está disparando na última versão de navegadores (Firefox 51.0.1, Opera 43.0.2442.991, Safari 10.0.3 (12602.4.8), Chrome 54.0.2840.71, Edge, IE11). Exemplo aqui - basta recarregar a página algumas vezes.

+
+ +

Sitaxe

+ +
XMLHttpRequest.onreadystatechange = callback;
+ +

Valores

+ + + +

Exemplo

+ +
var xhr = new XMLHttpRequest(),
+    method = "GET",
+    url = "https://developer.mozilla.org/";
+
+xhr.open(method, url, true);
+xhr.onreadystatechange = function () {
+        if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
+            console.log(xhr.responseText);
+        }
+    };
+xhr.send();
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest', '#handler-xhr-onreadystatechange')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(1)}}{{CompatGeckoDesktop(1.0)}}{{CompatIe(7)}}[1]{{CompatVersionUnknown}}{{CompatSafari(1.2)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Internet Explorer versão 5 e 6 suportam chamadas ajax usando ActiveXObject().

diff --git a/files/pt-br/web/api/xmlhttprequest/open/index.html b/files/pt-br/web/api/xmlhttprequest/open/index.html new file mode 100644 index 0000000000..131d78d21f --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/open/index.html @@ -0,0 +1,72 @@ +--- +title: XMLHttpRequest.open() +slug: Web/API/XMLHttpRequest/open +tags: + - Referencia + - metodo +translation_of: Web/API/XMLHttpRequest/open +--- +
{{APIRef('XMLHttpRequest')}}
+ +

O {{domxref("XMLHttpRequest")}} métodoopen() inicializa uma nova requisição, ou reinicializa uma requisição já existente.

+ +
Note: Chamar este método para uma requisição já ativada  (uma que open() já tenha sido chamada) é equivalente a chamar {{domxref("XMLHttpRequest.abort", "abort()")}}.
+ +

Sintaxe

+ +
XMLHttpRequest.open(method, url)
+XMLHttpRequest.open(method, url, async)
+XMLHttpRequest.open(method, url, async, user)
+XMLHttpRequest.open(method, url, async, user, password)
+
+ +

Parâmetros

+ +
+
method
+
O método de requisição HTTP para ser usado, como "GET", "POST", "PUT", "DELETE", etc. Ignorado para URLs não-HTTP(S).
+
url
+
Um {{domxref("DOMString")}} representando a URL para enviar a requisição.
+
async {{optional_inline}}
+
Parâmetro booleano opcional, valor padrão true, indica quando realizar a operação de forma assíncrona. Se este valor for false, o método send() não retorna nada até que a resposta da requisição seja recebida. Se o valor for true, notificação de uma transação concluída é provida usando event listeners. Isso deve ser verdadeiro se o atributo multipart é true, ou uma exceção será lançada. +
Nota: Requisições Síncronas no thread principal podem ser facilmente disruptivas para a experiência de usuário e devem ser evitadas; de fato, muitos navegadores descontinuaram inteiramente o suporte para XHR síncrono no thread principal. Requisições síncronas são permitidas nos {{domxref("Worker")}}s.
+
+
user {{optional_inline}}
+
O nome de usuário opcional para ser usado em autenticação; por padrão, isso é o valor null.
+
password {{optional_inline}}
+
A senha de usuário opcional para ser usado em autenticação; por padrão, isso é o valor null.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest', '#the-open()-method', 'open()')}}{{Spec2('XMLHttpRequest')}} +

Padrão WHATWG

+
+ +

Compatibilidade de Navegador

+ + + +

{{Compat("api.XMLHttpRequest.open")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/xmlhttprequest/readystate/index.html b/files/pt-br/web/api/xmlhttprequest/readystate/index.html new file mode 100644 index 0000000000..77474ae587 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/readystate/index.html @@ -0,0 +1,154 @@ +--- +title: XMLHttpRequest.readyState +slug: Web/API/XMLHttpRequest/readyState +tags: + - AJAX + - Property + - Reference + - XML + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/readyState +--- +

{{APIRef('XMLHttpRequest')}}

+ +

A propriedade XMLHttpRequest.readyState retorna o estado de um XMLHttpRequest. Uma requisição XHR que existe em um dos seguintes estados:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValorEstadoDescrição
0UNSENTUm cliente foi criado. Mas o método open()  não foi chamado ainda.
1OPENEDO método open() foi chamado.
2HEADERS_RECEIVEDo método send() foi chamado e os cabeçalhos e status estão disponíveis .
3LOADINGBaixando e responseText contem os dados parciais.
4DONEOperação concluída.
+ +
+
UNSENT
+
O XMLHttpRequest foi criado. Mas o método open() não foi chamado ainda.
+
OPENED
+
O método open() foi invocado. Durante esse estado, os headers da requisição podem ser inseridos usando o método setRequestHeader()  e o método send() pode ser chamado, iniciando a busca.
+
HEADERS_RECEIVED
+
O método send() foi chamado e os cabeçalhos de respostas foram recebidos.
+
LOADING
+
A resposta da requisição está sendo recebida. se o responseType for "text" ou  um texto em branco, o responseText terá o texto parcial da resposta conforme seu carregamento.
+
DONE
+
A Operação de busca está completa. Isso pode significar que a trasferência foi concluída com êxito ou que falhou.
+
+ +
+

Os nomes de estado são diferentes no Internet Explorer. Ao invés de UNSENT, OPENED, HEADERS_RECEIVED, LOADING DONE, os nomes usados são: READYSTATE_UNINITIALIZED (0), READYSTATE_LOADING (1), READYSTATE_LOADED (2), READYSTATE_INTERACTIVE (3) e READYSTATE_COMPLETE (4).

+
+ +

Exemplo

+ +
var xhr = new XMLHttpRequest();
+console.log('UNSENT', xhr.readyState); // readyState will be 0
+
+xhr.open('GET', '/api', true);
+console.log('OPENED', xhr.readyState); // readyState will be 1
+
+xhr.onprogress = function () {
+    console.log('LOADING', xhr.readyState); // readyState will be 3
+};
+
+xhr.onload = function () {
+    console.log('DONE', xhr.readyState); // readyState will be 4
+};
+
+xhr.send(null);
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusCommentários
{{SpecName('XMLHttpRequest', '#states')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidade entre navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
SuporteChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(1)}}{{CompatGeckoDesktop("1.0")}}[1]{{CompatIe(7)}}{{CompatVersionUnknown}}{{CompatSafari("1.2")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
SuporteAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/xmlhttprequest/requisicoes_sincronas_e_assincronas/index.html b/files/pt-br/web/api/xmlhttprequest/requisicoes_sincronas_e_assincronas/index.html new file mode 100644 index 0000000000..81b8fb8d3e --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/requisicoes_sincronas_e_assincronas/index.html @@ -0,0 +1,234 @@ +--- +title: Requisições síncronas e assíncronas +slug: Web/API/XMLHttpRequest/Requisicoes_sincronas_e_assincronas +translation_of: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests +--- +

XMLHttpRequest suporta comunicações síncronas e assíncronas. No geral, entretando, requisições assíncronas devem prevalecer sobre requisições síncronas por questões de performance.

+ +

Requisições síncronas podem bloquear a execução do codigo, gerando um "congelamento" da tela, prejudicando a experiência do usuário. 

+ +

Requisição assíncrona

+ +

Se você usa XMLHttpRequest de uma extensão, você deveria usá-la de forma assíncrona. Neste caso, você recebe um callback quando os dados forem recebidos, o que permite que o browser continue seu trabalho normalmente enquanto sua requisição estiver sendo processada.

+ +

Exemplo: envie um arquivo para o console de log

+ +

Esse é o exemplo mais simples de uso do XMLHttpRequest assíncrono.

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

A Linha 2 define o terceiro parâmetro como true, indicando que a requisição deve ser tratada assincronamente.

+ +

A Linha 3 cria um objeto função do tipo event handler e atribui ele ao atributo onload da requisição.

+ +

Na LInha 4, Este handler verifica o estado da requisição, através da variável readyState, para ver se a transação está completa, e se o status do HTTP é 200. Em caso positivo lê o conteúdo recebido. Se um erro ocorrer, uma mensagem de erro será exibida no console.

+ +

A requisição é, de fato, realizada na Linha 15. A rotina de callback é invocada quando o estado da requisição muda.

+ +

Exemplo: Criando uma função standard para ler arquivos externos

+ +

Em alguns casos, você pode precisar ler muitos arquivos externos. Esta é uma função padrão que utiliza o objeto XMLHttpRequest de forma assíncrona para alternar o conteúdo do arquivo legível para um listener especificado.

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

Uso:

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

A assinatura da função loadFile declara (i) uma URL de destino que será lida (via HTTP GET), (ii) uma função de callback para executar na conclusão bem-sucedida da instância xhr, e (iii) uma lista opcional de argumentos adicionais que são "passados através" do objeto XHR caso a função de callback seja bem-sucedida.

+ +

A linha 1 declara uma função que será invocada quando a operação XHR for completada com sucesso.  Isso, por sua vez, invoca uma função de callback especificada na invocação da função loadFile (neste caso, a função showMessage) que foi atribuída a propriedade do objeto XHR (Linha 7). Os  argumentos adicionais (caso existam) fornecem a invocação da função loadFile são "aplicados" para a execução da função de callback..

+ +

A linha 3 declara uma função que será invocada quando a operação XHR não for completada com sucesso.

+ +

A linha 7 define no objeto XHR  the success callback function given as the second argument to loadFile.

+ +

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

+ +

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

+ +

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

+ +

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

+ +

Line 12 actually initiates the request.

+ +

Example: using a timeout

+ +

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

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

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

+ +

Usage:

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

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

+ +
+

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

+
+ +

Synchronous request

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

Em casos raros, o uso do método síncrono é preferível ao invés do método assíncrono.

+ +

Example: HTTP synchronous request

+ +

This example demonstrates how to make a simple synchronous request.

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

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

+ +

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

+ +

Example: Synchronous HTTP request from a Worker

+ +

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

+ +

example.html (the main page):

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

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

+ +
Hello World!!
+
+ +

myTask.js (the Worker):

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

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

+ +

Adapting Sync XHR usecases to the Beacon API

+ +

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

+ +

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

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

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

+ +

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

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

See also

+ + + +

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

diff --git a/files/pt-br/web/api/xmlhttprequest/send/index.html b/files/pt-br/web/api/xmlhttprequest/send/index.html new file mode 100644 index 0000000000..21fa359025 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/send/index.html @@ -0,0 +1,129 @@ +--- +title: XMLHttpRequest.send() +slug: Web/API/XMLHttpRequest/send +tags: + - AJAX + - API + - Método HTTP + - NeedsExample + - Referencia + - Requisição HTTP + - Requisição XHR + - XHR + - XMLHttpRequest + - send +translation_of: Web/API/XMLHttpRequest/send +--- +

{{APIRef('XMLHttpRequest')}}

+ +

O método send(), do {{domxref("XMLHttpRequest")}}, envia uma requisição para o servidor.Se a solicitação for assíncrona (que é o padrão), esse método retornará assim que a solicitação for enviada e o resultado for entregue usando eventos. Se a solicitação for síncrona, esse método não retornará até que a resposta chegue.

+ +

send() aceita um parâmetro opcional que permite especificar o corpo da solicitação; isso é usado principalmente para solicitações como {{HTTPMethod("PUT")}}. Se o método de solicitação for {{HTTPMethod("GET")}} ou {{HTTPMethod("HEAD")}}, o parâmetro body será ignorado e o corpo da solicitação será definido como null.

+ +

Se nenhum cabeçalho {{HTTPHeader("Accept")}} tiver sido definido usando {{domxref("XMLHttpRequest.setRequestHeader", "setRequestHeader()")}}, um cabeçalho Accept com o tipo "*/*" (qualquer tipo) é enviado.

+ +

Sintaxe

+ +
XMLHttpRequest.send(body)
+
+ +

Parâmetros

+ +
+
body {{optional_inline}}
+
Um corpo de dados a ser enviado na solicitação XHR. Isso pode ser: +
    +
  • Um {{domxref("Document")}}, caso em que é serializado antes de ser enviado.
  • +
  • Um BodyInit, que conforme a espeficicação Fetch, pode ser um objeto {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("ReadableStream")}} ou {{domxref("USVString")}}.
  • +
+ Se nenhum valor for  espeficicado para o corpo, o valor padrão de null é usado.
+
+ +

A melhor maneira de enviar conteúdo binário (por exemplo, em uploads de arquivos) é usando um {{domxref("ArrayBufferView")}} ou {{domxref("Blob")}} em conjunto com o método send().

+ +

Valor retornado

+ +

undefined.

+ +

Exceções

+ + + + + + + + + + + + + + + + + + +
ExceçãoDescrição
InvalidStateErrorsend() já foi invocado para a requisição, e/ou a requisição está completa.
NetworkErrorO tipo de recurso a ser buscada é um {{domxref("Blob")}} e o método não é GET.
+ +

Exemplo: GET

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+xhr.onload = function () {
+  // Requisição finalizada. Faça o processamento aqui.
+};
+
+xhr.send(null);
+// xhr.send('string');
+// xhr.send(new Blob());
+// xhr.send(new Int8Array());
+// xhr.send(document);
+ +

Exemplo: POST

+ +
var xhr = new XMLHttpRequest();
+xhr.open("POST", '/server', true);
+
+// Envia a informação do cabeçalho junto com a requisição.
+xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+
+xhr.onreadystatechange = function() { // Chama a função quando o estado mudar.
+    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
+        // Requisição finalizada. Faça o processamento aqui.
+    }
+}
+xhr.send("foo=bar&lorem=ipsum");
+// xhr.send(new Int8Array());
+// xhr.send(document);
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest', '#the-send()-method', 'send()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidade com os navegadores

+ +
{{Compat("api.XMLHttpRequest.send")}}
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/xmlhttprequest/setrequestheader/index.html b/files/pt-br/web/api/xmlhttprequest/setrequestheader/index.html new file mode 100644 index 0000000000..246692fa09 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/setrequestheader/index.html @@ -0,0 +1,77 @@ +--- +title: XMLHttpRequest.setRequestHeader() +slug: Web/API/XMLHttpRequest/setRequestHeader +tags: + - API + - Cabeçalho HTTP + - HTTP + - XHR + - XMLHttpRequest + - header + - metodo + - setRequestHeader +translation_of: Web/API/XMLHttpRequest/setRequestHeader +--- +
{{APIRef('XMLHttpRequest')}}
+ +
 
+ +

O método setRequestHeader() de {{domxref("XMLHttpRequest")}} define o valor do cabeçalho de uma requisição HTTP. Ao usar setRequestHeader(), você deve chamá-lo depois de chamar o método {{domxref("XMLHttpRequest.open", "open()")}}, mas antes de chamar o método {{domxref("XMLHttpRequest.send", "send()")}}. Se esse método é chamado muitas vezes com o mesmo cabeçalho, os valores são somados em um único cabeçalho de requisição HTTP.

+ +

A cada vez que você chama setRequestHeader() depois de ter chamado-o pelo menos uma vez, o texto especificado é somado ao final do conteúdo do cabeçalho existente.

+ +

Se nenhum cabeçalho {{HTTPHeader("Accept")}} foi definido usando este método, um cabeçalho Accept com o tipo "*/*" é enviado com a requisição quando {{domxref("XMLHttpRequest.send", "send()")}} é chamado.

+ +

Por razões de segurança, alguns cabeçalhos só podem ser controlados pelo agente do usuário. Esses cabeçalhos incluem o cabeçalho {{Glossary("Forbidden_header_name", "forbidden header names", 1)}} e o cabeçalho {{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}.

+ +
+

Observação: Para seu campos personalizados, você pode encontrar uma exceção "not allowed by Access-Control-Allow-Headers in preflight response" quando você envia requisições através de domínios. Neste caso, você precisa definir o cabeçalho {{HTTPHeader("Access-Control-Allow-Headers")}} no seu cabeçalho de resposta no lado do servidor.

+
+ +

Sintaxe

+ +
XMLHttpRequest.setRequestHeader(header, value)
+
+ +

Parâmetros

+ +
+
header
+
O nome do cabeçalho cujo valor está para ser definido.
+
value
+
O valor a ser definido como o corpo do cabeçalho.
+
+ +

Valor de retorno

+ +

undefined.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest', '#the-setRequestHeader()-method', 'setRequestHeader()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidade com navegadores

+ + + +

{{Compat("api.XMLHttpRequest.setRequestHeader")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/xmlhttprequest/timeout/index.html b/files/pt-br/web/api/xmlhttprequest/timeout/index.html new file mode 100644 index 0000000000..d80b67d77d --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/timeout/index.html @@ -0,0 +1,51 @@ +--- +title: XMLHttpRequest.timeout +slug: Web/API/XMLHttpRequest/timeout +translation_of: Web/API/XMLHttpRequest/timeout +--- +
{{APIRef('XMLHttpRequest')}}
+ +

A propriedade XMLHttpRequest.timeout é um unsigned long que representa o número de milisegundos que uma requisição deve esperar até ser automaticamente terminada. O valor padrão para essa propriedade é 0, o que significa que o navegador deverá esperar uma resposta indefinidamente. A propriedade Timeout não deveria ser usada para requisições XMLHttpRequests síncronas em um {{Glossary('document environment')}} ou uma exceção do tipo InvalidAccessError será lançada. Quando um timeout ocorre, o evento timeout é disparado. {{gecko_minversion_inline("12.0")}}

+ +
+
+
Nota: Você não pode usar um timeout para requisições síncronas dentro de uma janela.
+
+
Utilizando um timeout com uma requisição assíncrona 
+
+ +

No Internet Explorer, a propriedade timeout pode ser usada apenas depois de o método open() ter sido invocado e antes de se chamar o método send().

+ +

Exemplo

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+xhr.timeout = 2000; // tempo em milisegundos
+
+xhr.onload = function () {
+  // Requisição finalizada. O processamento deve ser colocado aqui.
+};
+
+xhr.ontimeout = function (e) {
+  // Timeout na chamada XMLHttpRequest. Ação de timeout aqui.
+};
+
+xhr.send(null);
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('XMLHttpRequest', '#the-timeout-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
diff --git a/files/pt-br/web/api/xmlhttprequest/usando_xmlhttprequest/index.html b/files/pt-br/web/api/xmlhttprequest/usando_xmlhttprequest/index.html new file mode 100644 index 0000000000..b541e64bc1 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/usando_xmlhttprequest/index.html @@ -0,0 +1,688 @@ +--- +title: Usando XMLHttpRequest +slug: Web/API/XMLHttpRequest/Usando_XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest +--- +

XMLHttpRequest torna o envio de requisições HTTP muito fácil.  Basta criar uma instância do objeto, abrir uma url e enviar uma requisição. O status HTTP do resultado assim como o seu conteúdo estarão disponíveis quando a transação for completada. Esta página descreve alguns casos comuns de uso desse poderoso objeto JavaScript.

+ +
function reqListener () {
+  console.log(this.responseText);
+};
+
+var oReq = new XMLHttpRequest();
+oReq.onload = reqListener;
+oReq.open("get", "yourFile.txt", true);
+oReq.send();
+ +

Tipos de Requisições

+ +

Uma requisição feita via XMLHttpRequest pode buscar dados de duas maneiras, sícrona e assíncrona. O tipo de requisição é dado pelo argumento async que é opcional (terceiro argumento) e é definido no método XMLHttpRequest open(). Se esse argumento for true ou não especificado, o XMLHttpRequest será processado de maneira assíncrona, caso contrário o processamento será síncrono. Uma discussão detalhada e demonstrações desses dois tipos podem ser encontradas na página requisições síncronas e assíncronas. No geral a melhor prática é a das solicitações assíncronas.

+ +

Manipulando Respostas

+ +

Existem vários tipos de atributos de resposta definidos pela especificação da W3C para o  XMLHttpRequest.  Eles informam ao cliente que efetuou a requisição XMLHttpRequest informações importantes sobre o status da resposta. Em alguns casos onde se lida com tipos de resposa de não-texto, os tipos de resposta podem envolver alguma manipulação e/ou análise conforme descrito nas seções seguintes.

+ +

Analisando e manipulando a propriedade responseXML

+ +

Se você utiliza o XMLHttpRequest para obter o conteúdo de um documento XML remoto, a propriedade responseXML será um objeto DOM que contém um documento XML, o que pode dificultar a manipulação e análise.

+ +

As cinco formas mais utilizadas para análisar e manipular um arquivo XML são:

+ +
    +
  1. Usando XPath para análisar parte deles.
  2. +
  3. Usando JXON para converter em um Objeto JavaScript.
  4. +
  5. Manualmente Parsing and serializing XML para strings ou objetos.
  6. +
  7. Usando XMLSerializer para serializar árvores do DOM para strings ou para arquivos.
  8. +
  9. RegExp pode ser usado se você souber de antemão qual é o conteúdo do XML. Você pode remover quebras de linhas, usando a RegExp para procurar as quebras de linha. No entanto, este é o "último método", caso o código do XML sofra alterações, o método se torna falho.
  10. +
+ +

Analisando e manipulando uma propriedade responseText contendo um documento HTML

+ +
Nota: A especificação W3C do XMLHttpRequest permite analisar HTML através da propriedade XMLHttpRequest.responseXML . Leia o artigo sobre HTML in XMLHttpRequest para maiores detalhes.
+ +

Se você usa o XMLHttpRequest para recuperar o conteúdo de uma página HTML remota, a propriedade responseText será uma string contendo um a "sopa" de todos as tags HTML, o que pode ser difícil de manipular e analizar. Existem três formas básicas para analizar esta sopa de string HTML:

+ +
    +
  1. Use a propriedade  XMLHttpRequest.responseXML.
  2. +
  3. Introduza o conteúdo dentro do corpo de um document fragment Através de fragment.body.innerHTML e percorra o fragmento do DOM.
  4. +
  5. RegExp pode se usada se você sempre conhece o conteúdo HTML responseText de que tem em mãos. Você pode quere remover quebras de linha, se você usar RegExp para varrer no que diz respeito a quebra de linhas. Contudo, este método é um "último recurso" uma vez que se o código HTML mudar um pouco, o método provavelmente irá falhar.
  6. +
+ +

Manipulação de dados binários

+ +

Apesar de XMLHttpRequest ser mais comumente usado para enviar e receber dados textual, ele pode ser utilizado para enviar e receber conteúdo binário. Existem vários métodos bem testados para forçar a resposta de um XMLHttpRequest para o envio de dados binário. Eles envolvem a utilização do método  .overrideMimeType()  sobre o objeto  XMLHttpRequest e é uma solução viável.

+ +
var oReq = new XMLHttpRequest();
+oReq.open("GET", url, true);
+// recupera dados não processados como uma string binária
+oReq.overrideMimeType("text/plain; charset=x-user-defined");
+/* ... */
+
+ +

A especificação XMLHttpRequest Level 2  adiciona novo responseType attributes que tornam o envio e recebimento de dados muito mais fácil.

+ +
var oReq = new XMLHttpRequest();
+
+oReq.open("GET", url, true);
+oReq.responseType = "arraybuffer";
+oReq.onload = function(e) {
+  var arraybuffer = oReq.response; // não é responseText
+  /* ... */
+}
+oReq.send();
+
+ +

Para mais exemplos confira a página Sending and Receiving Binary Data.

+ +

Monitorando o progresso

+ +

XMLHttpRequest fornece a capacidade de ouvir vários eventos que podem ocorrer enquanto o pedido está sendo processado. Isso inclui notificações periódicas de progresso, notificações de erro e assim por diante.

+ +

Suporte para evento de progresso DOM monitorando a conexão XMLHttpRequest transfers siga a Web API specification for progress events: estes eventos implementam a interface {{domxref("ProgressEvent")}} .

+ +
var oReq = new XMLHttpRequest();
+
+oReq.addEventListener("progress", updateProgress, false);
+oReq.addEventListener("load", transferComplete, false);
+oReq.addEventListener("error", transferFailed, false);
+oReq.addEventListener("abort", transferCanceled, false);
+
+oReq.open();
+
+// ...A transferência foi cancelada pelo usuário
+
+// progresso de transferências do servidor para o cliente (downloads)
+function updateProgress (oEvent) {
+  if (oEvent.lengthComputable) {
+    var percentComplete = oEvent.loaded / oEvent.total;
+    // ...
+  } else {
+    // Não é possível calcular informações de progresso uma vez que a dimensão total é desconhecida
+  }
+}
+
+function transferComplete(evt) {
+  alert("A transferência foi concluída.");
+}
+
+function transferFailed(evt) {
+  alert("Um erro ocorreu durante a transferência do arquivo.");
+}
+
+function transferCanceled(evt) {
+  alert("A transferência foi cancelada pelo usuário.");
+}
+ +

Lines 3-6 adiciona receptores de eventos (event listeners) para os vários que são enviados ao executar uma transferência de dados usando XMLHttpRequest.

+ +
Nota: Você precisa adicionar os receptores de eventos (event listeners) antes de chamar open() sobre a requisição.  Caso contrário, os eventos de prograsso não dispararão..
+ +

O manipulador de evento  de prograsso, especificado pela função updateProgress() neste exemplo, recebe o número total de bytes para transferir, bem como o número de bytes transferidos até o momento em total de eventos e campos  carregados . No entanto, se o campo lengthComputable é false, o comprimento total não é conhecido e será zero..

+ +

Eventos de progresso existem para ambos as transferências de download e upload. The download events are fired on the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object, as shown below:

+ +
var oReq = new XMLHttpRequest();
+
+oReq.upload.addEventListener("progress", updateProgress, false);
+oReq.upload.addEventListener("load", transferComplete, false);
+oReq.upload.addEventListener("error", transferFailed, false);
+oReq.upload.addEventListener("abort", transferCanceled, false);
+
+oReq.open();
+
+ +
Nota: eventos de progresso não estão disponíveis para o arquivo: protocol.
+ +
Nota: Atualmente, existem bugs em aberto para o evento de progresso que continua fetando a versão 25 do Firefox sobre OS X e Linux.
+ +
+

Nota: Iniciando no {{Gecko("9.0")}}, eventos de progresso agora podem ser invocados a entrar para cada pedaço de dados recebidos, incluindo o último bloco, nos casos em que o último pacote é recebido e a conexão fechada antes do evento progresso ser disparado. Neste caso, o evento de progresso é automaticamente acionado quando o evento load ocorre para esse pacote. Isso permite que você agora acompanhe de forma confiável apenas observando o evento de progresso

+
+ +
+

Nota: A partir do {{Gecko("12.0")}}, se o seu evento de progresso e chamado com um responseType de "moz-blob", o valor da resposta será um {{domxref("Blob")}} contendo os dados recebidos até agorar.

+
+ +

POde-se também detectar todas as três condições de fim de carga (abort, load, or error) usando o evento loadend:

+ +
req.addEventListener("loadend", loadEnd, false);
+
+function loadEnd(e) {
+  alert("A transferência terminou (embora não sabemos se ele conseguiu ou não).");
+}
+
+ +

Note que não há nenhuma maneira de ter certeza a partir da informação recebida pelo evento loadend sobre qual condição causou a operação de encerrar; no entanto, você pode usar isso para lidar com tarefas que precisam ser realizadas em todos os cenários de fim-de-transferência.

+ +

Submitting forms and uploading files

+ +

Instances of XMLHttpRequest can be used to submit forms in two ways:

+ + + +

The second way (using the FormData API) is the simplest and the fastest, but has the disadvantage that the data thus collected can not be stringified: they are in every way a blob. It is the best solution for simple cases.
+ The first way (pure AJAX) is instead the most complex, but in compensation is also the most flexible and powerful: it lends itself to wider uses and the data thus collected can be stringified and reused for other purposes such as, for example, populating the status object during a manipulation of the browser history, or other.

+ +

Using nothing but pure AJAX

+ +

Submitting forms without the FormData API does not require other APIs, except that, only if you want to upload one or more files, the FileReader API.

+ +

A brief introduction to the submit methods

+ +

An html {{ HTMLElement("form") }} can be sent in four ways:

+ + + +

Now, consider to submit a form containing only two fields, named foo and baz. If you are using the POST method, the server will receive a string similar to one of the following three ones depending on the encoding type you are using:

+ + + +

Instead, if you are using the GET method, a string like the following will be simply added to the URL:

+ +
?foo=bar&baz=The%20first%20line.%0AThe%20second%20line.
+ +

A little vanilla framework

+ +

All these things are done automatically by the web browser whenever you submit a {{ HTMLElement("form") }}. But if you want to do the same things using JavaScript you have to instruct the interpreter about all things. So, how to send forms in pure AJAX is too complex to be explained in detail here. For this reason we posted here a complete (but still didactic) framework, which is able to use all the four ways of submit and, also, to upload files:

+ +
+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Sending forms with pure AJAX &ndash; MDN</title>
+<script type="text/javascript">
+
+"use strict";
+
+/*\
+|*|
+|*|  :: XMLHttpRequest.prototype.sendAsBinary() Polifyll ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
+\*/
+
+if (!XMLHttpRequest.prototype.sendAsBinary) {
+  XMLHttpRequest.prototype.sendAsBinary = function (sData) {
+    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
+    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
+      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
+    }
+    /* send as ArrayBufferView...: */
+    this.send(ui8Data);
+    /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
+  };
+}
+
+/*\
+|*|
+|*|  :: AJAX Form Submit Framework ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
+|*|
+|*|  This framework is released under the GNU Public License, version 3 or later.
+|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
+|*|
+|*|  Syntax:
+|*|
+|*|   AJAXSubmit(HTMLFormElement);
+\*/
+
+var AJAXSubmit = (function () {
+
+  function ajaxSuccess () {
+    /* console.log("AJAXSubmit - Success!"); */
+    alert(this.responseText);
+    /* you can get the serialized data through the "submittedData" custom property: */
+    /* alert(JSON.stringify(this.submittedData)); */
+  }
+
+  function submitData (oData) {
+    /* the AJAX request... */
+    var oAjaxReq = new XMLHttpRequest();
+    oAjaxReq.submittedData = oData;
+    oAjaxReq.onload = ajaxSuccess;
+    if (oData.technique === 0) {
+      /* method is GET */
+      oAjaxReq.open("get", oData.receiver.replace(/(?:\?.*)?$/, oData.segments.length > 0 ? "?" + oData.segments.join("&") : ""), true);
+      oAjaxReq.send(null);
+    } else {
+      /* method is POST */
+      oAjaxReq.open("post", oData.receiver, true);
+      if (oData.technique === 3) {
+        /* enctype is multipart/form-data */
+        var sBoundary = "---------------------------" + Date.now().toString(16);
+        oAjaxReq.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + sBoundary);
+        oAjaxReq.sendAsBinary("--" + sBoundary + "\r\n" + oData.segments.join("--" + sBoundary + "\r\n") + "--" + sBoundary + "--\r\n");
+      } else {
+        /* enctype is application/x-www-form-urlencoded or text/plain */
+        oAjaxReq.setRequestHeader("Content-Type", oData.contentType);
+        oAjaxReq.send(oData.segments.join(oData.technique === 2 ? "\r\n" : "&"));
+      }
+    }
+  }
+
+  function processStatus (oData) {
+    if (oData.status > 0) { return; }
+    /* the form is now totally serialized! do something before sending it to the server... */
+    /* doSomething(oData); */
+    /* console.log("AJAXSubmit - The form is now serialized. Submitting..."); */
+    submitData (oData);
+  }
+
+  function pushSegment (oFREvt) {
+    this.owner.segments[this.segmentIdx] += oFREvt.target.result + "\r\n";
+    this.owner.status--;
+    processStatus(this.owner);
+  }
+
+  function plainEscape (sText) {
+    /* how should I treat a text/plain form encoding? what characters are not allowed? this is what I suppose...: */
+    /* "4\3\7 - Einstein said E=mc2" ----> "4\\3\\7\ -\ Einstein\ said\ E\=mc2" */
+    return sText.replace(/[\s\=\\]/g, "\\$&");
+  }
+
+  function SubmitRequest (oTarget) {
+    var nFile, sFieldType, oField, oSegmReq, oFile, bIsPost = oTarget.method.toLowerCase() === "post";
+    /* console.log("AJAXSubmit - Serializing form..."); */
+    this.contentType = bIsPost && oTarget.enctype ? oTarget.enctype : "application\/x-www-form-urlencoded";
+    this.technique = bIsPost ? this.contentType === "multipart\/form-data" ? 3 : this.contentType === "text\/plain" ? 2 : 1 : 0;
+    this.receiver = oTarget.action;
+    this.status = 0;
+    this.segments = [];
+    var fFilter = this.technique === 2 ? plainEscape : escape;
+    for (var nItem = 0; nItem < oTarget.elements.length; nItem++) {
+      oField = oTarget.elements[nItem];
+      if (!oField.hasAttribute("name")) { continue; }
+      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT";
+      if (sFieldType === "FILE" && oField.files.length > 0) {
+        if (this.technique === 3) {
+          /* enctype is multipart/form-data */
+          for (nFile = 0; nFile < oField.files.length; nFile++) {
+            oFile = oField.files[nFile];
+            oSegmReq = new FileReader();
+            /* (custom properties:) */
+            oSegmReq.segmentIdx = this.segments.length;
+            oSegmReq.owner = this;
+            /* (end of custom properties) */
+            oSegmReq.onload = pushSegment;
+            this.segments.push("Content-Disposition: form-data; name=\"" + oField.name + "\"; filename=\""+ oFile.name + "\"\r\nContent-Type: " + oFile.type + "\r\n\r\n");
+            this.status++;
+            oSegmReq.readAsBinaryString(oFile);
+          }
+        } else {
+          /* enctype is application/x-www-form-urlencoded or text/plain or method is GET: files will not be sent! */
+          for (nFile = 0; nFile < oField.files.length; this.segments.push(fFilter(oField.name) + "=" + fFilter(oField.files[nFile++].name)));
+        }
+      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
+        /* field type is not FILE or is FILE but is empty */
+        this.segments.push(
+          this.technique === 3 ? /* enctype is multipart/form-data */
+            "Content-Disposition: form-data; name=\"" + oField.name + "\"\r\n\r\n" + oField.value + "\r\n"
+          : /* enctype is application/x-www-form-urlencoded or text/plain or method is GET */
+            fFilter(oField.name) + "=" + fFilter(oField.value)
+        );
+      }
+    }
+    processStatus(this);
+  }
+
+  return function (oFormElement) {
+    if (!oFormElement.action) { return; }
+    new SubmitRequest(oFormElement);
+  };
+
+})();
+
+</script>
+</head>
+<body>
+
+<h1>Sending forms with pure AJAX</h1>
+
+<h2>Using the GET method</h2>
+
+<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h2>Using the POST method</h2>
+<h3>Enctype: application/x-www-form-urlencoded (default)</h3>
+
+<form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h3>Enctype: text/plain</h3>
+
+<form action="register.php" method="post" enctype="text/plain" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      Your name: <input type="text" name="user" />
+    </p>
+    <p>
+      Your message:<br />
+      <textarea name="message" cols="40" rows="8"></textarea>
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h3>Enctype: multipart/form-data</h3>
+
+<form action="register.php" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Upload example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" /><br />
+      Sex:
+      <input id="sex_male" type="radio" name="sex" value="male" /> <label for="sex_male">Male</label>
+      <input id="sex_female" type="radio" name="sex" value="female" /> <label for="sex_female">Female</label><br />
+      Password: <input type="password" name="secret" /><br />
+      What do you prefer:
+      <select name="image_type">
+        <option>Books</option>
+        <option>Cinema</option>
+        <option>TV</option>
+      </select>
+    </p>
+    <p>
+      Post your photos:
+      <input type="file" multiple name="photos[]">
+    </p>
+    <p>
+      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" /> <label for="vehicle_bike">I have a bike</label><br />
+      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" /> <label for="vehicle_car">I have a car</label>
+    </p>
+    <p>
+      Describe yourself:<br />
+      <textarea name="description" cols="50" rows="8"></textarea>
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+</body>
+</html>
+
+ +

To test it, please, create a page named register.php (which is the action attribute of these sample forms) and just put the following minimalistic content:

+ +
<?php
+
+  /* register.php */
+
+  header("Content-type: text/plain");
+
+  echo ":: data received via GET ::\n\n";
+  print_r($_GET);
+
+  echo "\n\n:: Data received via POST ::\n\n";
+  print_r($_POST);
+
+  echo "\n\n:: Data received as \"raw\" (text/plain encoding) ::\n\n";
+  if (isset($HTTP_RAW_POST_DATA)) { echo $HTTP_RAW_POST_DATA; }
+
+  echo "\n\n:: Files received ::\n\n";
+  print_r($_FILES);
+
+?>
+ +

The syntax of this script is the following:

+ +
AJAXSubmit(myForm);
+ +
Note: This little vanilla framework uses the FileReader API, which is a recent technique (but only when there are files to upload, the method of the {{ HTMLElement("form") }} is POST and the enctype attribute is setted to multipart/form-data). For this reason, the pure-AJAX upload is to be considered an experimental technique. Instead, if you don't want to upload files, this framework will not use any recent API.
+Note also that the best way to send binary content is using ArrayBuffers or Blobs in conjuncton with the send() method and, possibly, with the readAsArrayBuffer() method of the FileReader API. But, since the aim of this little script is to work with a stringifiable raw data, we used the sendAsBinary() method in conjunction with the readAsBinaryString() method of the FileReader API. So, this is the best solution when working with a relatively few data which must be stringified in order to be reused later. Anyhow, since working with strings instead of typed arrays implies a greater waste of resources, this script makes sense only when you are dealing with small files (like images, documents, mp3, etc.). Otherwise, if you don't want to stringify the submitted or uploaded data, in addition to typed arrays, consider also the use of the FormData API.
+ +

Using FormData objects

+ +

The FormData constructor lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to "multipart/form-data". FormData objects can be utilized in a number of ways with an XMLHttpRequest. For examples and explanations of how one can utilize FormData with XMLHttpRequests see the Using FormData Objects page. For didactic purpose only we post here a translation of the previous example transformed so as to make use of the FormData API. Note the brevity of the code:

+ +
+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Sending forms with FormData &ndash; MDN</title>
+<script type="text/javascript">
+"use strict";
+
+function ajaxSuccess () {
+  alert(this.responseText);
+}
+
+function AJAXSubmit (oFormElement) {
+  if (!oFormElement.action) { return; }
+  var oReq = new XMLHttpRequest();
+  oReq.onload = ajaxSuccess;
+  if (oFormElement.method.toLowerCase() === "post") {
+    oReq.open("post", oFormElement.action, true);
+    oReq.send(new FormData(oFormElement));
+  } else {
+    var oField, sFieldType, nFile, sSearch = "";
+    for (var nItem = 0; nItem < oFormElement.elements.length; nItem++) {
+      oField = oFormElement.elements[nItem];
+      if (!oField.hasAttribute("name")) { continue; }
+      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT";
+      if (sFieldType === "FILE") {
+        for (nFile = 0; nFile < oField.files.length; sSearch += "&" + escape(oField.name) + "=" + escape(oField.files[nFile++].name));
+      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
+        sSearch += "&" + escape(oField.name) + "=" + escape(oField.value);
+      }
+    }
+    oReq.open("get", oFormElement.action.replace(/(?:\?.*)?$/, sSearch.replace(/^&/, "?")), true);
+    oReq.send(null);
+  }
+}
+</script>
+</head>
+<body>
+
+<h1>Sending forms with FormData</h1>
+
+<h2>Using the GET method</h2>
+
+<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h2>Using the POST method</h2>
+<h3>Enctype: application/x-www-form-urlencoded (default)</h3>
+
+<form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h3>Enctype: text/plain</h3>
+
+<p>The text/plain encoding is not supported by the FormData API.</p>
+
+<h3>Enctype: multipart/form-data</h3>
+
+<form action="register.php" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Upload example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" /><br />
+      Sex:
+      <input id="sex_male" type="radio" name="sex" value="male" /> <label for="sex_male">Male</label>
+      <input id="sex_female" type="radio" name="sex" value="female" /> <label for="sex_female">Female</label><br />
+      Password: <input type="password" name="secret" /><br />
+      What do you prefer:
+      <select name="image_type">
+        <option>Books</option>
+        <option>Cinema</option>
+        <option>TV</option>
+      </select>
+    </p>
+    <p>
+      Post your photos:
+      <input type="file" multiple name="photos[]">
+    </p>
+    <p>
+      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" /> <label for="vehicle_bike">I have a bike</label><br />
+      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" /> <label for="vehicle_car">I have a car</label>
+    </p>
+    <p>
+      Describe yourself:<br />
+      <textarea name="description" cols="50" rows="8"></textarea>
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+</body>
+</html>
+
+ +
Note: As we said, FormData objects are not stringifiable objects. If you want to stringify a submitted data, use the previous pure-AJAX example. Note also that, although in this example there are some file {{ HTMLElement("input") }} fields, when you submit a form through the FormData API you do not need to use the FileReader API also: files are automatically loaded and uploaded.
+ +

Cross-site XMLHttpRequest

+ +

Modern browsers support cross-site requests by implementing the web applications working group's Access Control for Cross-Site Requests standard.  As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work.  Otherwise, an INVALID_ACCESS_ERR exception is thrown.

+ +

Bypassing the cache

+ +

A, cross-browser compatible approach to bypassing the cache is to append a timestamp to the URL, being sure to include a "?" or "&" as appropriate.  For example:

+ +
http://foo.com/bar.html -> http://foo.com/bar.html?12345
+http://foo.com/bar.html?foobar=baz -> http://foo.com/bar.html?foobar=baz&12345
+
+ +

Since the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.

+ +

You can automatically adjust URLs using the following code:

+ +
var oReq = new XMLHttpRequest();
+
+oReq.open("GET", url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime(), true);
+oReq.send(null);
+ +

Security

+ +

{{fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference capability.policy..XMLHttpRequest.open to allAccess to give specific sites cross-site access.  This is no longer supported.")}}

+ +

{{fx_minversion_note(5, "Versions of Firefox prior to Firefox 5 could use netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\"); to request cross-site access. This is no longer supported, even though it produces no warning and permission dialog is still presented.")}}

+ +

The recommended way to enable cross-site scripting is to use the Access-Control-Allow-Origin HTTP header in the response to the XMLHttpRequest.

+ +

XMLHttpRequests being stopped

+ +

If you end up with an XMLHttpRequest having status=0 and statusText=null, it means that the request was not allowed to be performed. It was UNSENT. A likely cause for this is when the XMLHttpRequest origin (at the creation of the XMLHttpRequest) has changed when the XMLHttpRequest is then open(). This case can happen for example when one has an XMLHttpRequest that gets fired on an onunload event for a window: the XMLHttpRequest gets in fact created when the window to be closed is still there, and then the request is sent (ie open()) when this window has lost its focus and potentially different window has gained focus. The way to avoid this problem is to set a listener on the new window "activate" event that gets set when the old window has its "unload" event fired.

+ +

Using XMLHttpRequest from JavaScript modules / XPCOM components

+ +

Instantiating XMLHttpRequest from a JavaScript module or an XPCOM component works a little differently; it can't be instantiated using the XMLHttpRequest() constructor. The constructor is not defined inside components and the code results in an error. The best way to work around this is to use the XPCOM component constructor.

+ +
const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1");
+var oReq = XMLHttpRequest();
+ +

Unfortunately in versions of Gecko prior to Gecko 16 there is a bug which can cause requests created this way to be cancelled for no reason.  If you need your code to work on Gecko 15 or earlier, you can get the XMLHttpRequest constructor from the hidden DOM window like so.

+ +
const { XMLHttpRequest } = Components.classes["@mozilla.org/appshell/appShellService;1"]
+                                     .getService(Components.interfaces.nsIAppShellService)
+                                     .hiddenDOMWindow;
+var oReq = XMLHttpRequest();
+
+ +

See also

+ +
    +
  1. MDC AJAX introduction
  2. +
  3. HTTP access control
  4. +
  5. How to check the security state of an XMLHTTPRequest over SSL
  6. +
  7. XMLHttpRequest - REST and the Rich User Experience
  8. +
  9. Microsoft documentation
  10. +
  11. Apple developers' reference
  12. +
  13. "Using the XMLHttpRequest Object" (jibbering.com)
  14. +
  15. The XMLHttpRequest Object: W3C Specification
  16. +
  17. Web Progress Events specification
  18. +
-- cgit v1.2.3-54-g00ecf